-1

Here's a part of me code. Well, my question is how can I skip catch block when I enter wrong values? For example, as you can see I need coordinates to be double or Float but when I enter String it starts infinite while looping. How can I prevent it and make program start from the begining until user enters right values?


   main_loop:
        while (true) {
            int i = 3;
            System.out.println("Attemts left: " + i);
            loop_label:
            while (true) {
                try {
                    temp_coords.setX(temp_scn.nextDouble());
                    temp_coords.setY(temp_scn.nextFloat());
                    break main_loop;
                } catch (Exception e) {
                    System.out.println("wrong format!");
                } finally {
                    break loop_label;
                }
            }
            i--;
            if(i == 0){
                break;
            }
        }

This is my code without loops and labels How can I can make this code work until right data coming in

try {
            temp_coords.setX(temp_scn.nextDouble());
            temp_coords.setY(temp_scn.nextFloat());
        } catch (Exception e) {
            System.out.println("wrong format!");
        }
Nikita
  • 29
  • 6
  • 2
    You should really redesign your code. Get rid of your infinite loops and labels. It's impossible to follow the code flow here. – Kayaman Feb 22 '20 at 18:29
  • 3
    At your `i == 0` line, `i` is always 2. – Andy Turner Feb 22 '20 at 18:32
  • @Kayaman editted – Nikita Feb 22 '20 at 18:36
  • 1
    Scanner throws an exception when the input format does not fit. You cannot avoid this. Of course you can read the input as string and then convert (e.g. by ```Integer.parseInt(s)``` but that would throws exceptions as well if the input does not fit. To avoid exceptions you would need to validate the input before parsing it (e.g. by regular expressions) but why? Exceptions are fine in case of errors, they are not forbidden. – Stefan Feb 22 '20 at 18:42

1 Answers1

1
break loop_label

Should be in the catch block. Do not use finally because the code inside it will be run even if no error is thrown.

And as Andy said, it seems i will never be equal to 0

David Alvarez
  • 1,226
  • 11
  • 23