java - 出现 do-while 错误

标签 java do-while

因此,我提示用户输入变量。如果变量小于 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/

相关文章:

c - While循环只发生一次

在 do-while 循环中输入验证的 C++ 错误

c - fprintf(textFilepointer) 在文件中打印两次

java - 如何访问 Eclipse 中 lib\ext 目录中的 jar?

java - 调用 Object 类的 wait() 方法时出现异常

unsigned int 的 Java SQL 准备语句

java - 使用Java图形在其中绘制带线的圆

java - jersey 2 的 ConstraintAnnotations 不起作用

java - 如何在用户什么都不输入时继续提示用户

c# - 打印从 0 到 10,000 的素数