【发布时间】:2015-10-05 21:51:32
【问题描述】:
这个程序已经完成,但我想进行修改。我试图让它在完成后重新启动以获取更多输入。我尝试使用带有 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!");
}
}
【问题讨论】:
-
虽然上课可能需要大型 cmets,但在这里它们有点分散注意力,您可能会删除其中的大部分。
-
请注意,您永远不会在循环开始时重新设置
numbers变量。 -
@HovercraftFullOfEels 是的,同意 cmets。太多的 cmets 会杀死 cmets。这是代码,不是文献
-
好的,我将删除 cmets,但它们是必需的。如果没有所有这些 cmets,您将在课堂上获得 50%。我实际上应该在每一行都有它们。 >
-
它崩溃是因为您尝试使用 .charAt(0)。并且此时字符串为空。