有没有办法返回到上一行代码(没有 while 循环)

Is there a way to return to a previous line of code (without a while loop)

提问人:gooooodmorning 提问时间:8/19/2022 最后编辑:gooooodmorning 更新时间:8/20/2022 访问量:270

问:

我正在尝试创建包含一个接收输入的部分并检查相应文件是否存在(以及输入是否为数字)的东西,如下所示:

short x = 0;
Scanner scan = new Scanner(System.in);
try {
                    x = scan.nextShort(); 
                    Path path = Paths.get(x + ".ics");
                    if(!Files.exists(path)) {
                        System.out.println("Sorry, file does not exist");
                        System.exit(0);
                    }
                }       catch(InputMismatchException e) { 
                    System.out.println("Sorry, please enter a number");
                    System.exit(0);
                    }   
 File f = new File(x + ".ics");  
                try (Scanner classScan = new Scanner(f)) { 
                    byte i = 1; 
                    for(; i <=6; i++ ) { 
                        if(classScan.findWithinHorizon(i, 0) != null) {
                            break; 
                            
                        }
                    }
                    System.out.println(i); 
                }
            }       

在两个 System.exit 行中,我想创建返回到 scan.nextShort() 的东西 - 我想过一个 while 循环,但我想不出一个合理的方法来做到这一点(尤其是在异常捕获的情况下)。

如果 if 语句和 catch 都没有发生,我还想在 try-catch 下运行代码。

标题在一定程度上具有误导性,如果实际上有一种方法可以用 while 循环来做到这一点,我将不胜感激。

java 文件 java.util.scanner

评论

0赞 Elliott Frisch 8/19/2022
将整个 try-catch 放在一个循环中。 您可能需要删除这些调用。因为那只是完全结束了程序。whilewhile (true) { try { /* ... */ } }System.exit(0)
0赞 Bohemian 8/20/2022
文件的布局是什么?如果没有可读的,还有什么short
0赞 gooooodmorning 8/20/2022
我不确定这是否有帮助,但我在下面添加了所有内容。这也是为什么一段时间 true 不起作用的原因

答:

0赞 nixon 8/19/2022 #1

也许在尝试块之外。while (scan.hasMoreElements())

评论

0赞 mymiracl 8/24/2022
它可以是评论
0赞 Computable 8/20/2022 #2

A可以在这里应用,如下所示。只需添加一个布尔标志 initial 并设置为找到正确输入时。do { .. } while;falsetrue

请注意,您需要在处理中,否则它将继续扫描相同的无效输入:scan.next()InputMismatchException

// assume test created a file named '3.ics'

short x = 0;
Scanner scan = new Scanner(System.in);
boolean valid = false;
do {
    try {
        x = scan.nextShort(); 
        Path path = Paths.get(x + ".ics");
        if(!Files.exists(path)) {
            System.out.println("Sorry, file does not exist");
        } else {
            valid = true;
        }
    } catch(InputMismatchException e) { 
        System.out.println("Sorry, please enter a number");
        scan.next();
    }   
} while (!valid);

System.out.println(x + ".ics"); 
// ... and on we go ...

和输出

abc
Sorry, please enter a number
2
Sorry, file does not exist
3
3.ics

评论

0赞 gooooodmorning 8/20/2022
哦,我没想过要用 do while,谢谢。就捕获中的 scan.next 而言,如果 x 是一个字符串并且原始字符串也是 scan.next,那岂不是让一切变得更容易?老实说,我不知道这种方法的存在