gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:12:45 26 4
gpt4 key购买 nike

我希望它在用户输入“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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com