2015-10-05 106 views
0

該程序已完成,但我想對其進行修改。我正在嘗試在完成更多輸入後重新啓動它。我試圖用一個循環與一個字符,但它似乎導致它崩潰作爲我的數組的結果。我目前正在調查這件事,但我正在發佈,因爲你可能在我之前想到了這一點。 感謝先進!如何重新啓動程序

編輯:現在已經解決了!謝謝大家!將其更改爲 字符串的想法奏效,這將解釋錯誤。我很欣賞你所有的 輸入!

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!"); 

    } 
} 
+2

儘管課堂可能需要超級評論,但在這裏他們有點分散注意力,你可能會去除其中的大部分。 –

+0

請注意,您不會在循環的開始處重新設置'numbers'變量。 –

+0

@HovercraftFullOfEels是的同意評論。評論過多會導致評論無效。這是代碼,不是litterature – Dici

回答

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 = 0,sum = 0。 numbers.clear();

+0

它的工作原理!謝謝,Jawad!我正要嘗試一個字符串,我不知道爲什麼我不想先嚐試它! – snipem1438