java - Do While 循环跳过用户输入

标签 java loops while-loop do-while

我希望它在用户输入“Y”或“y”时再次循环,并在输入“N”或“n”时退出。退出选项有效,但是,当他们输入 Y/y 时,它会显示第一个系统,但不允许用户选择他们想要执行的操作。相反,继续的选项会再次弹出并阻止用户做出任何选择。

这是代码:

import java.util.Scanner;

public class Calc2 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        double numOne, numTwo, ans;
        String option;

        do {

            System.out.println(
                    "For addition press '1', for subtraction press '2', for division press '3', for multiplication press '4'");
            String choice = input.nextLine();

            if (choice.contains("1")) {
                System.out.println("Enter the first number : ");
                numOne = input.nextDouble();
                System.out.println("Enter the second number : ");
                numTwo = input.nextDouble();

                ans = numOne + numTwo;
                System.out.println("The answer is: " + ans + " ya bish.");
            }

            else if (choice.contains("2")) {
                System.out.println("Enter the first number : ");
                numOne = input.nextDouble();
                System.out.println("Enter the second number : ");
                numTwo = input.nextDouble();

                ans = numOne - numTwo;
                System.out.println("The answer is: " + ans + " ya bish.");
            } else if (choice.contains("4")) {
                System.out.println("Enter the first number : ");
                numOne = input.nextDouble();
                System.out.println("Enter the second number : ");
                numTwo = input.nextDouble();

                ans = numOne * numTwo;
                System.out.println("The answer is: " + ans + " ya bish.");
            } else if (choice.contains("3")) {
                System.out.println("Enter the first number : ");
                numOne = input.nextDouble();
                System.out.println("Enter the second number : ");
                numTwo = input.nextDouble();

                ans = numOne / numTwo;
                System.out.println("The answer is: " + ans + " ya bish.");

            }
            System.out.println("Press 'Y' to continue or 'N' to quit.");

            option = input.next();
        } while (option.equals("Y") || option.equals("y"));

        if (option.equals("N") || option.equals("n")) {
            System.out.println("Thank you. ");
        }

    }
}

如果有人能帮助我,我将不胜感激。谢谢!

最佳答案

请更改代码中的以下行

    String choice = input.nextLine();

来自此代码

    String choice = input.next();

关于java - Do While 循环跳过用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32163575/

相关文章:

java - Hibernate - 解析映射文件(.hbm.xml)时出现问题

r - 在 R 中将大文件分区为小文件

php - 使用 Cycle2 成对显示肖像图像

loops - Rust:在 “while let”中访问可变参数

c - 下面的代码在 C 中做了什么?

java - while 循环会在一段时间后停止执行吗?

Java - 马尔可夫链文本生成器 - 解析文本文件

java - Java多线程中如何实现信号量概念?生产者消费者

java - 如何从处理库导入数据文件夹?

java - 实现统一和跳过变量