如何分隔循环中输入的一串数字?

时间:2014-09-28 21:14:23

标签: java

我需要帮助拉出数字并用逗号分隔它们,例如,如果我输入1 2 3 4 5,它应该打印出来

Entered Numbers: 1, 2, 3, 4, 5
The Sum: 15

相反,我得到了这个

Entered Numbers: 12345
The Sum: 15

代码:

/*A program that prompts the user to enter a positive integer number. The program should accept integers until the user enters the 
value -1 (negative one). After the user enters -1, the program should display the entered numbers followed by their sum*/

import java.util.Scanner;

public class InputSum
{
   public static void main(String [] args)
   {
      //create a way to receive user input
      Scanner input = new Scanner(System.in);

      //Variables
      int sum = 0;
      String value;

      //Input
      System.out.println("Enter a positive integer (Enter -1 to quit): ");
      value = input.nextLine();

      String x = "";

      //Loop Statements
      while (Integer.parseInt(value) != -1)
         {
            sum = Integer.parseInt(value) + sum;
            x = x + value;
            value = input.nextLine();
         }
      //Output
      System.out.println("Entered Numbers: " + x);
      System.out.println("The sum: " + sum);
   }
}      

3 个答案:

答案 0 :(得分:0)

您可以使用replace()来执行您想要的操作。以这种格式使用它

value = value.replace(" ", ","); //First param is the char you want to replace; The second is the one you want to replace the first param with

答案 1 :(得分:0)

使用Split string方法获取每个数字,然后使用trim来获取带空格的限制。然后将该字符串粘贴到int中,并将其粘贴到总和中。只有循环部分发生了变化。其他一切都是一样的。

public static void main(String [] args)
{
  //create a way to receive user input
  Scanner input = new Scanner(System.in);

  //Variables
  int sum = 0;
  String value;

  //Input
  System.out.println("Enter a positive integer (Enter -1 to quit): ");
  value = input.nextLine();

  for(String eachNum:value.split(",")) {
     sum=Interger.parseInt(eachNum.trim());
  }

  //Output
  System.out.println("Entered Numbers: " + value);
  System.out.println("The sum: " + sum);
}

答案 2 :(得分:0)

替换

String x = "";

//Loop Statements
while (Integer.parseInt(value) != -1
     {
        sum = Integer.parseInt(value) + sum;
        x = x + value;
        value = input.nextLine();
     }

 String x = value;

  //Loop Statements
  while (Integer.parseInt(value) != -1)
     {
        sum = Integer.parseInt(value) + sum;
        x = x + ", " + value;
        value = input.nextLine();
     }