如何重新启动程序

时间:2015-10-05 21:51:33

标签: java loops input sum

这个程序已经完成,但我想做一个修改。我想在它完成后需要更多输入才能重新启动它。我试图使用带有char的循环,但它似乎导致它因我的数组而崩溃。我正在调查这个,但是我发帖,因为你可能会在我面前解决这个问题。 先谢谢!

  编辑:现在已经解决了!谢谢大家!把它改成一个想法   字符串工作,这将解释错误。我很感激你   输入!

import java.util.*;
import java.io.*;
public class InputSum
{

   public static void main (String[] args)
   {

      Scanner scan = new Scanner(System.in); //Initializes scanner

      int num=0;  //Creates array for input numbers
      int sum=0;
      char restart = 'y';
      List<Integer> numbers = new ArrayList<Integer>(); 

      while (restart == 'y') {
         System.out.print("Please input integers, note that -1 ends the submissions: "); 

         for(; ;)
         {
            num = scan.nextInt(); //Continues to read numbers and add them to the sum
            if (num == -1){
               break;
            }
            numbers.add(Integer.valueOf(num)); //Adds the values to the value of num to the array list
            sum += num; //Calculates the sum
            continue;  
         }
         System.out.print("The numbers entered are:    " + numbers); //Prints the numbers and the sum
         System.out.print("\nThe sum of the numbers is:  " + sum + "\n");
         System.out.print("Would you like to restart? Y or N: ");
         restart = scan.nextLine().charAt(0);  
      }
      System.out.print("The program has ended!");

   }
}

1 个答案:

答案 0 :(得分:2)

试试这个:

  Scanner scan = new Scanner(System.in); //Initializes scanner

  int num=0;  //Creates array for input numbers
  int sum=0;
  String restart ="y";
  List<Integer> numbers = new ArrayList<Integer>(); //Creates array list for input

  while (restart.equals("y")) {
     System.out.print("Please input integers, note that -1 ends the submissions: "); //Prompts the user for input

     num=0;
     sum=0;         
     numbers.clear();

     for(; ;)
     {
        num = scan.nextInt(); //Continues to read numbers and add them to the sum
        if (num == -1){
           break;
        }
        numbers.add(Integer.valueOf(num)); //Adds the values to the value of num to the array list
        sum += num; //Calculates the sum
        continue;  
     }
     System.out.print("The numbers entered are:    " + numbers); //Prints the numbers and the sum
     System.out.print("\nThe sum of the numbers is:  " + sum + "\n");
     System.out.print("Would you like to restart? Y or N: ");
     restart = scan.next();  
  }

  System.out.print("The program has ended!");

使用scan.next而不是scan.nextLine()并重置num,sum和数字。 num = 0,sum = 0。 numbers.clear();