0

There is a 2d array called data that represent a matrix with l lines and c columns. I want to save the matrix numbers with a scanner.

but when the user try to type 1.5 I want to catch the exepction, and ask the user for a new valid number, of course without continue to the next number. I try this code. but when I type for example 1.5 , I got a flood "Please enter a valid integer number".

how Can I make it work right?

thank you for help :)

    for (int l=0;l<data.length;l++) {
        for (int c=0;c<data[0].length;) {
            try {
                int num = scanner.nextInt();

                data[l][c] = num;
                c++;
            }
            catch(RuntimeException e) {
                System.out.println("Please enter a valid integer number");
            }
        }
    }
Alona
  • 27
  • 1
  • 8
  • 1
    I'm not sure, but try writing `scanner.nextLine();` after your printout in the catch-block. – RaminS May 14 '16 at 17:43
  • 1
    The reason you're getting a flood of messages is because your inner loop never ends. – Makoto May 14 '16 at 17:43
  • 1
    @Makoto He has `c++;` in his try-block. – RaminS May 14 '16 at 17:43
  • 1
    @Gendarme: And if the OP enters the *catch* block...what happens? – Makoto May 14 '16 at 17:44
  • @Makoto The try block is executed again, but allegedly it doesn't ask him for a new int, instead it jumps to the catch-block again right away. I am guessing this is because he doesn't start a new line after reading his `nextInt()`. – RaminS May 14 '16 at 17:46
  • 1
    Avoid try-catch if you can. It is better to use `hasNextDouble()` method and if next value is not double, consume it with `next()` and ask for new value. See duplicate (you may need to refresh this page to see it) for more information. – Pshemo May 14 '16 at 17:48
  • I solved it. if I write "Scanner scanner = new Scanner(System.in);" above "int num..." it works fine. ( it was above the entire loop). thank you – Alona May 14 '16 at 17:55

0 Answers0