0

我是java新手

int nop=o;
BufferedReader scan = new BufferedReader( new InputStreamReader(System.in));
come_here:
System.out.println("Enter length");
try{
    int n=Integer.parseInt(scan.readLine());
nop=n;
}catch(Exception sandy){
    System.out.println("Please Enter Numericals only");
    continue come_here;
}

如果用户输入任何字符串而不是数字发生异常并打印“请仅输入数字”并且编译器执行下一条语句,这里正在丢失用户输入以克服我使用标签(come here:),如果发生异常,它会显示“请仅输入数字” “之后我希望程序再次接受用户输入,我使用了继续come_here; 但它不起作用?

有人告诉我在哪里做错了吗?以及如何解决

谢谢你

4

5 回答 5

1

This is not valid Java. I would instead write the code as follows:

    int nop = 0;
    BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
    for (;;) {
        System.out.println("Enter length");
        try {
            int n = Integer.parseInt(scan.readLine());
            nop = n;
            break;
        } catch (Exception sandy) {
            System.out.println("Please Enter Numericals only");
        }
    }
于 2013-01-05T16:58:13.510 回答
0

I'm not saying this is the optimal way of solving this problem, but perhaps you are looking for something like this. I replaced your goto-statement with a while(true) loop. The while loop quits once the integer has successfully been parsed.

int nop=0;
BufferedReader scan = new BufferedReader( new InputStreamReader(System.in));
while (true) {
    System.out.println("Enter length");
    try {
        int n=Integer.parseInt(scan.readLine());
        nop=n;
        break;
    } catch(Exception sandy){
        System.out.println("Please Enter Numericals only");
    }
}
于 2013-01-05T16:58:11.793 回答
0

You're trying to do a user input loop, but the trick is that Java doesn't allow goto to actually be used - it's a reserved word, but it won't compile.

Here's what you can do in simpler steps:

于 2013-01-05T16:58:15.143 回答
0

参考这里继续使用,用法和你学的不一样

以下代码可用于读取整数值

int nop=o;
BufferedReader scan = new BufferedReader( new InputStreamReader(System.in));
for(;;) {
        System.out.println("Enter length");
        try{
        int n=Integer.parseInt(scan.readLine());
        nop=n;
break;
            }catch(Exception sandy){
                System.out.println("Please Enter Numericals only");
            }
    }
于 2013-01-05T16:53:51.050 回答
0

标签在 Java 中的功能与在 Basic 或 C/C++ 等其他语言中的功能不同。

它们标记了一个循环,而不是您可以跳转到的命令。通常,只有在嵌套循环时才需要它们。像这样:

    loop_i: for (int i = 0; i < 10; i++) {
        loop_j: for (int j = 0; j < 10; j++) {
            System.out.println(i + " " + j);
            if (j == 7) {
                // we want to jump out of the inner loop
                break loop_j; // or just break;
            }
            if (i == 3 && j == 4) {
                // now we want to jump out of both loops
                break loop_i;
            }
        }
    }

该示例使用 break 是因为它们更易于解释。但是在标签问题上继续有相同的规则。

于 2013-01-05T17:19:27.723 回答