1

So, I'm trying to be able to take in user input and add up each number in the string and print it out as well as calculating the product. I figured out how to take in each digit but i'm having trouble with numbers of variable length. this is what it prints currently :

Please enter '.' when you want to terminate
1 2 3
Numbers: 1 2 3
Sum: 13  Product: 12

This is the method that calculates user input after scanning

public void set(String userInput)// method set returns void
{
    num=0;// reset each variable so new input can be passed
    sum=0;
    product=1;
    String empty="";

    for(int index=0; index<userInput.length(); index++)// goes through each character in string
    {

        if(Character.isDigit(userInput.charAt(index))==true)// checks if character in the string is a digit
        { 
            empty+=userInput.charAt(index);
        }
        else
        {
            //if it is then parse that character into an integer and assign it to num
            num=Integer.parseInt(empty);

            // adds each digit to sum
            sum+=num;
            product*=num;
            // multiplies each digit by product and stores in "product"
        }
    } 
}
4

2 回答 2

1

看起来您需要在使用后清除空白,并确保在最后一位之后继续处理。你得到 1 + 12 和 1 * 12 而缺少 3。

于 2013-08-30T22:32:22.110 回答
0

我建议你,从一开始就用空格分隔数字:

用户输入是:1 2 3 10 20

然后你可以得到一个数组

String[] numbers = userInput.trim().split(" ");

你必须调整你的代码。

于 2013-08-30T22:31:50.693 回答