首页 > 解决方案 > 字符串作为 while 循环中的标记值

问题描述

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

我想我一直在尝试为哨兵值实现一个字符串。我希望哨兵值是“否”。但是在我在这里进行的最后一次尝试中,当我输入“是”时,我得到了 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));
}

}

}

标签: javawhile-loopdo-while

解决方案


  • 先删除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));
        }
    }

推荐阅读