java - 在 Java 中按 Enter 键结束循环的见解

标签 java loops key enter

我正在学习低级 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/

相关文章:

C# While 无限循环

c - 当用户输入正整数而不是字符时打破循环

c - 在 C 编程中使用无限循环是否值得推荐/值得重视

javascript - Propublica API 使用 JavaScript 验证 key

java - 在java中注入(inject)击键

jquery - JavaScript/jQuery 中是否有类似 php 函数 key() 的函数?

java - 为什么我们允许在 Java 中引用枚举成员的枚举成员?

java - 这个递归是如何工作的以及如何让它打印出根?

java - 我可以在 Apache Derby 版本 10.11 中使用 MERGE INTO 吗?

java - slick2d 中的文本旋转