繁体   English   中英

Java 问题中的 While 循环

[英]While Loops in Java Problems

现在我们正在学习 while 循环 - 这就是挑战。 “程序应该反复提示用户输入一个数字。保持用户输入数字的运行总数,并记录用户输入的数量。只要用户输入的东西不是数字,程序就应该停止整数。当用户完成后,打印用户输入的条目数及其总和。”

“与此程序的示例交互可能如下所示:程序:输入一个整数以继续或输入一个非整数值以完成。然后按回车。

用户:2

程序:输入一个整数以继续或输入一个非整数值以完成。 然后按回车。

用户:6

程序:输入一个整数以继续或输入一个非整数值以完成。 然后按回车。

用户:89

程序:输入一个整数以继续或输入一个非整数值以完成。 然后按回车。

用户:q

程序:您输入了 3 个整数。 您输入的总和是 97。”

这是我到目前为止所拥有的。

import java.util.Scanner;
public class InputSequence
{
    public static void main (String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
        int sum = 0;
        int total = 0;
        while (scan.hasNextInt())
        {
            scan.next();
            System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
            int input = scan.nextInt();
            sum = input + input;
            total = total + 1;
        }
        System.out.println ("You entered " + total + " integers. The sum of your entries is " + sum);
    }
}

我只是有点困惑,因为我的交互似乎在 while 循环中每 2 次跳过 system.out.println ,然后不将第一个输入计入总数。 我相信总和也不总是正确计算。 另外,如果我输入了很多整数,然后输入一个非整数来结束程序,我将收到一个错误而不是结束消息。 但是,假设我先输入两个整数,然后输入一个字符串,我会得到结束消息。

您的问题在于可以删除的scan.next()中的用法,并且应该正确显示System.out.println

.next()方法是nextInt()的通用方法,它返回一个String

您可以做的另一件事是从while循环切换到do while以防止您重复此行两次:

System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");

一个例子是:

Scanner scan = new Scanner(System.in);
        int sum = 0;
        int total = 0;
        do {
            System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
            int input = scan.nextInt();
            sum = input + input;
            total = total + 1;
        } while (scan.hasNextInt());
        System.out.println ("You entered " + total + " integers. The sum of your entries is " + sum);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM