我正在学习低级 Java 编程类(class),但我无法弄清楚教授布置给我们的一些内容。我们最初编写了一个程序,将放置在数组列表中的整数相加。然后,她要求我们尽可能使其用户友好,而无需用户输入特定数量的整数。所以我想出了这个:
public class CalculatorREDONE
{
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter any numbers you would like to add. ");
Scanner input = new Scanner(System.in);
do
{
numbers.add((int) input.nextInt()); //inserting input into the arraylist
System.out.println("The sum is " + sum(numbers)); //test output
}while(input.hasNextInt()); // I believe this needs to change but I am unsure what it should be
System.out.println(sum(numbers));
//My Problem here is that the loop doesn't end, therefore cannot print this output
input.close();
}
public static int sum(ArrayList<Integer> list)
{
int total = 0;
for (int i = 0; i < list.size(); i++)
{
total += list.get(i);
}
return total;
}
}
抱歉评论困惑,我试图向你们展示我所做的事情背后的心态。提前非常感谢任何提出建议的人!
最佳答案
看看这是否有助于您从用户那里获取输入来终止程序。
public class CalculatorREDONE {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter any numbers you would like to add or -1 to exit");
Scanner input = new Scanner(System.in);
// boolean nextAvailable = true;
while(true)
{
String nextVal = input.nextLine();
if(nextVal.isEmpty()) {
break;
}
numbers.add(Integer.parseInt(nextVal)); //inserting input into the arraylist
// System.out.println("The sum is " + sum(numbers)); //test output
} //while (!input.next().); // I believe this needs to change but I am unsure what it should be
System.out.println(sum(numbers));
//My Problem here is that the loop doesn't end, therefore cannot print this output
input.close();
}
public static int sum(List<Integer> list) {
int total = 0;
for (int i = 0; i < list.size(); i++) {
total += list.get(i);
}
return total;
}
}
关于java - 在 Java 中按 Enter 键结束循环的见解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33006120/