Search code examples
javafilejava.util.scanner

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


I'm trying to create something that includes a part which receives an input and checks if a respective file exists(and if the input was a number) like so:

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); 
                }
            }       

At the two System.exit lines I want to create something that returns to scan.nextShort() - I thought about a while loop but I can't think of a plausible way to do that here (especially with an exception catch).

I also want to run code under the try-catch if neither the if statement or catch happens.

Title is partly misleading if there's actually a way to do this with a while loop I would appreciate it.


Solution

  • A do { .. } while; can be applied here as in below. Just add a boolean flag initial false and set to true when correct input is found.

    And note you need a scan.next() in the InputMismatchException processing otherwise it will continue to scan the same invalid input:

    // 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 ...
    

    And output

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