gpt4 book ai didi

java - 出现 do-while 错误

转载 作者:行者123 更新时间:2023-11-29 04:39:20 28 4
gpt4 key购买 nike

因此,我提示用户输入变量。如果变量小于 0 且大于 10。如果用户输入 <0 和 >10,我想要求用户再次输入数字。我问时间的时候输入4,它说你输入错误。但在第二次尝试时效果很好。例如:如果我输入 25,它会打印出“您输入错误”的消息。为什么即使我的输入在第一次尝试时就适合条件,我也会收到此消息?

import java.util.*;
import java.io.*;


public class abc{
public static void main(String args[]) throws Exception{


int velocity;
int time;

System.out.print("Enter the velocity");

Scanner sn = new Scanner(System.in);

velocity = sn.nextInt();


System.out.println("Enter the time");

time=sn.nextInt();


do{

System.out.println("you entered wrong format/d Please Try Again");

time=sn.nextInt();

}while(time<0 || time>10);

}
}

最佳答案

请考虑以下实现(请参阅评论)。

do-while 循环

// Assuming the time value is not valid.
boolean isValidTime = false;

do {
System.out.println("Enter the time: ");
time = sn.nextInt();

if (time < 0 || time > 10) {
System.out.println("You have entered invalid time value!");
} else {
// The time value is valid now!
isValidTime = true;
}
// While the time value is not valid…
} while (!isValidTime);

while-do 循环

// Assuming the time value is not valid.
boolean isValidTime = false;

// While the time value is not valid…
while (!isValidTime) {
System.out.println("Enter the time: ");
time = sn.nextInt();

if (time < 0 || time > 10) {
System.out.println("You have entered invalid time value!");
} else {
// The time value is valid now!
isValidTime = true;
}
}

关于java - 出现 do-while 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39927346/

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