用于在循环中创建字符串以报告数字的代码

时间:2019-01-31 00:52:03

标签: string loops input while-loop sum

我创建了一个功能正常的代码。我确定转义函数为-1,以便用户退出程序,并使用if/else仅添加正整数之和。

我知道我必须保存通过if语句的数字(仅是正数),并且我想到的唯一方法是通过String

不幸的是,每当我尝试将字符串添加为while循环的一部分时,当我只需要一行时,它将一遍又一遍地打印该语句。

我也在努力将用户输入设置为一行。我知道它与.nextLine()命令有关,但是如果我将其拉到方括号之外(我尝试这样做),那么它将读为错误。

实际上,有关将String转换为字符或输入String的资料也将非常有帮助。显然,这是我缺乏很大一部分理解的地方。

public static void main(String args[])
{
  int userNum = 0;
  int sum = 0;

   Scanner s = new Scanner(System.in);
  String str3;

  System.out.print("Enter positive integers (to exit enter -1):\n ");

     //Loop for adding sum with exit -1
     while(userNum != -1){ 

           //condition to only calculate positive numbers user entered
           if(userNum > 0){
              //calculation of all positive numbers user entered
              sum += userNum;
              str3 = String.valueOf(userNum);}
              userNum = s.nextInt();
              }
      System.out.println("The values of the sum are: " + str3);
      System.out.println("The Sum: " + sum);
     }
}

我希望可以打印出用户输入,

  

输入正整数(退出时输入-1): _ _ ___ //与用户   在同一行中输入。

然后... 从字符串值读取同一行,而不是多行。

1 个答案:

答案 0 :(得分:1)

变量str需要初始化为:

String str3 = "";

并且在循环中,每个输入的数字必须串联到str

int userNum = 0;
int sum = 0;

Scanner s = new Scanner(System.in);
String str3 = "";

System.out.print("Enter positive integers (to exit enter -1):\n ");
while (userNum != -1) {
    userNum = s.nextInt();
    if (userNum > 0) {
        sum += userNum;
        str3 += " " + userNum;
    }
}
System.out.println("The values of the sum are: " + str3);
System.out.println("The Sum: " + sum);