我一直试图弄清楚我的代码几个小时,我知道这可能很简单,但我真的很感激一些帮助!
这是我的问题:
// Purpose: This program will prompt the user to enter a positive integer.
// The program will accept integers until the user enters a -1.
// Once the -1 is entered, the program will display the integers followed
// by their sum.
import java.util.Scanner;
public class InputSum
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
// variable declaration
int inputNumber;
int stringNumber = 0;
int num = 0;
int sum = 0;
// prompt user to enter an integer
System.out.print("Enter a positive integer: ");
inputNumber = scan.nextInt();
// continue to have user enter integers until:
while (inputNumber >= 0)
{
sum += inputNumber;
stringNumber = inputNumber++;
System.out.print("\n Enter another positive integer (enter -1 to quit): ");
inputNumber = scan.nextInt();
// -1 is entered
if (inputNumber == -1)
{
break;
}
}
// display results
System.out.print("\n The integers you entered were: " + Integer.toString(stringNumber));
System.out.print("\n The sum of the intergers are: " + sum);
}
}
// Purpose: This program will prompt the user to enter a positive integer.
// The program will accept integers until the user enters a -1.
// Once the -1 is entered, the program will display the integers followed
// by their sum.
import java.util.Scanner;
public class InputSum
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
// variable declaration
int inputNumber;
int stringNumber = 0;
int num = 0;
int sum = 0;
// prompt user to enter an integer
System.out.print("Enter a positive integer: ");
inputNumber = scan.nextInt();
// continue to have user enter integers until:
while (inputNumber >= 0)
{
sum += inputNumber;
stringNumber = inputNumber++;
System.out.print("\n Enter another positive integer (enter -1 to quit): ");
inputNumber = scan.nextInt();
// -1 is entered
if (inputNumber == -1)
{
break;
}
}
// display results
System.out.print("\n The integers you entered were: " + Integer.toString(stringNumber));
System.out.print("\n The sum of the intergers are: " + sum);
}
}
现在我的结果正确地显示了我的总和,但是它应该显示我在用逗号分隔的行中输入的整数。 (EX:如果用户输入1,1,1我的结果应该是你输入的整数:1,1,1整数的总和是:3)。现在它将我输入的整数添加到sentinel值并将结果显示为:您输入的整数是:1。
我真的坚持如何做到这一点。有什么建议?谢谢!
答案 0 :(得分:0)
您只打印输入的最后一个号码:
System.out.print("\n The integers you entered were: " + Integer.toString(stringNumber));
如果您想打印所有输入数字,则必须将它们存储在某处。
如果您希望将其存储在stringNumber
中,请将其类型更改为StringBuilder
,并将每个数字附加到其中。
StringBuilder stringNumber = new StringBuilder();
...
stringNumber.append(inputNumber);
stringNumber.append(", ");
...
System.out.print("\n The integers you entered were: " + stringNumber.toString());
您必须对此代码稍作调整,以避免打印额外的","在最后一个号码之后。
答案 1 :(得分:0)
您每次都必须存储输入。
替换
stringNumber = inputNumber++;
通过
stringNumber += inputNumber+", ";
这会将输入存储在inputNumber
。
更改
System.out.print("\n The integers you entered were: " + Integer.toString(stringNumber));
到
System.out.print("\n The integers you entered were: " + stringNumber);
这将显示输入的所有输入。