gpt4 book ai didi

java - 使用||在 while 循环中使其需要太多输入值

转载 作者:行者123 更新时间:2023-12-02 02:28:19 26 4
gpt4 key购买 nike

public class MetricConversion {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String masses = "null";
String volumes = "null";
String temps = "null";
String lengths = "null";
int answer1 = 0;

String[] options = {"Mass = 1","Temperature = 2","Length = 3","Volume = 4"};
System.out.println("What would you like to convert?");
for(int i = 0;i<options.length;i++)
System.out.println(options[i]);

while(!input.hasNextInt() || input.nextInt() > options.length)
{
String garbage = input.nextLine();
System.out.println("That input is not valid, try again");
}
answer1 = input.nextInt();
input.nextLine();

我遇到的问题是

    while(!input.hasNextInt() || input.nextInt() > options.length)

采用 2 个有效输入(而不是 1 个)来生成

    answer1 = input.nextInt();

例如,当输入无效输入时,它会正确打印我的错误消息,但是当输入有效输入时,我必须输入两次才能打破循环。但是,如果我使用不带 || 的 while 循环它只需要一个值,就像它应该的那样。

最佳答案

您正在使用该值而不将其分配给变量。您可以在循环条件中分配它,如下所示:

while(!input.hasNextInt() || (answer1 = input.nextInt()) > options.length)

关于java - 使用||在 while 循环中使其需要太多输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47500193/

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