0

我有一个 do while 循环。检查 x 在两个值之间。现在我应该接受一个 int 值,但是如果用户键入一个 double,我会得到异常。如何在相同的 if 语句中加入检查,以便如果用户键入双精度,它将打印类似“x 必须是 10 到 150 之间的 int:”之类的内容

            do {
            x = sc.nextInt();
            if ( x < 10 || x > 150 ) {
                System.out.print("x between 10 and 150: ");
            } else {
                break;
            }
4

3 回答 3

4

您不需要额外的检查。例外就在那里,因此您可以在程序中采取相应的行动。毕竟,输入的错误程度并不重要。只需捕获异常(我猜是 NumberFormatException 吗?)并在捕获它时打印一条错误消息:

while (true) try {
    // here goes your code that pretends only valid inputs can occur
    break;   // or better yet, put this in a method and return
} catch (NumberFormatException nfex) {  // or whatever is appropriate
    System.err.println("You're supposed to enter integral values.");
    // will repeat due to while above
}
于 2013-11-06T15:38:46.170 回答
3

您可以捕获异常并处理它,使用 awhile (true)允许用户重试。

这是我的代码:

Scanner sc = new Scanner(System.in);
do {
    System.out.print("\nInsert a number >>> ");
    try {
        int x = sc.nextInt();
        System.out.println("You inserted " + x);
        if (x > 10 && x < 150) {
            System.out.print("x between 10 and 150: ");
        } else {
            break;
        }
    } catch (InputMismatchException e) {
        System.out.println("x must be an int between 10 and 150");
        sc.nextLine(); //This line is really important, without it you'll have an endless loop as the sc.nextInt() would be skipped. For more infos, see this answer http://stackoverflow.com/a/8043307/1094430
    }
} while (true);
于 2013-11-06T15:46:32.327 回答
0
public class SomeClass {                                                         
    public static void main(String args[]) {                                     
        double x = 150.999; // 1
        /* int x = (int) 150.999; */ // 2                                          
        if ( x >= 10 && x <= 150 ) { // The comparison will still work                                             
            System.out.print("x between 10 and 150: " + x + "\n");               
        }                                                                        
    }                                                                            
}
  1. 将 x 声明为 double,double 和 int 之间的比较仍然有效。
  2. 或者,转换数字和任何十进制值都将被丢弃。
于 2013-11-06T15:44:47.710 回答