我正在开发一个项目,该项目将从用户输入到控制台中随机设置一组数字,添加总和数字并显示输入的数字以及以空格分隔格式的数字总和,如果输入的数字是1234,它将输出1 2 3 4 = 10
我的工作代码是:
import java.util.Scanner;
public class MurphyCounter
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int mstop;
int number;
int sum;
int mcounter;
Scanner input = new Scanner(System.in);
System.out.print(" Now many numbers am I adding? ");
mstop = console.nextInt();
System.out.println();
sum = 0;
mcounter = 0;
System.out.println(" Please provide " + mstop
+ " numbers.");
while (mcounter < mstop)
{
number = console.nextInt();
sum = sum + number;
mcounter++;
}
System.out.printf("The sum of these %s " +
"numbers = %d%n", mstop, sum);
System.out.println();
if (mcounter != 0)
System.out.printf("Thank you for your input" );
else
我正在撞墙,已经过了一个星期的大部分时间...... 请帮忙!
答案 0 :(得分:0)
您不存储输入数字,如果您只想在最后打印它们就足以将它们存储在字符串numbers += " " + Integer.toString(number);
中。
然后整个主要看起来像这样:
public static void main(String[] args) {
int mstop;
int number;
int sum;
int mcounter;
String numbers = "";
Scanner input = new Scanner(System.in);
System.out.print(" Now many numbers am I adding? ");
mstop = console.nextInt();
System.out.println();
sum = 0;
mcounter = 0;
System.out.println(" Please provide " + mstop + " numbers.");
while (mcounter < mstop) {
number = console.nextInt();
sum = sum + number;
numbers += " " + Integer.toString(number);
mcounter++;
}
System.out.print("The sum of these " + mstop + " numbers:" + numbers
+ " = " + sum);
System.out.println();
if (mcounter != 0) {
System.out.printf("Thank you for your input");
}
}