字符串作为while循环中的前哨值

问题描述 投票:-2回答:1

我正在尝试编写一个程序,询问用户是否要输入实数。如果是,则提示用户输入数字。不断提示输入数字,直到用户说“否”。一旦发生这种情况,请输出所输入数字的平均值。

我认为我一直在尝试为哨兵值实现字符串。我希望哨兵值是“否”。但是,这是我的最后一次尝试,当我输入“是”时,我得到一个InputMismatchException。另外,不确定这是做某项工作的时间/时间或时间。所有这些都是新事物,不确定如何去做,因为我们没有使用字符串作为前哨的示例。

public static void main(String[] args) {

int count = 0;
float total = 0;        
float inputNumber;


Scanner scan = new Scanner ( System.in );

System.out.println("Want to enter a number?");

String reply = "";


inputNumber = scan.nextFloat();

do {
    reply = scan.nextLine();
    if (reply.equalsIgnoreCase("yes")) {
        System.out.println("Enter a number > ");

        total+= inputNumber ;
        count++ ;

        System.out.println("Enter another number, or " +
                "enter \"no\" to terminate > " );
        inputNumber = scan.nextFloat(); 
    }
}   
while (! reply.equalsIgnoreCase("no")) ;

if (count != 0) {
    System.out.println("The average of the numbers is " + 
            (total / count));
}

}

}

java while-loop do-while
1个回答
0
投票
  • 先删除inputNumber = scan.nextFloat();
  • 修复循环。
  • scan.nextLine()之后添加scan.nextFloat()
    public static void main(String[] args) {
        int count = 0;
        float total = 0f;
        float inputNumber = 0f;

        Scanner scan = new Scanner ( System.in );

        System.out.println("Want to enter a number?");
        String reply = scan.nextLine();

        while (reply.equalsIgnoreCase("yes")) {
            System.out.println("Enter a number > ");
            inputNumber = scan.nextFloat();
            scan.nextLine();
            total += inputNumber;
            count++;

            System.out.println("Enter another number, or enter \"no\" to terminate > ");
            reply = scan.nextLine();
        }

        if (count != 0) {
            System.out.println("The average of the numbers is " + (total / count));
        }
    }

编辑

    public static void main(String[] args) {
        int count = 0;
        float total = 0f;
        float inputNumber = 0f;

        Scanner scan = new Scanner ( System.in );

        System.out.println("Want to enter a number?");
        String reply = scan.nextLine();

        if (!reply.equalsIgnoreCase("yes"))
            return;

        System.out.println("Enter a number > ");
        while (!reply.equalsIgnoreCase("no")) {
            reply = scan.nextLine();
            try {
                inputNumber = Float.parseFloat(reply);
            } catch (NumberFormatException e) {
                continue;
            }
            total += inputNumber;
            count++;
            System.out.println("Enter another number, or enter \"no\" to terminate > ");
        }
        if (count != 0) {
            System.out.println("The average of the numbers is " + (total / count));
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.