-1

I have this piece of code :

import java.util.*;
class HelloWorld {
    public static void main(String args[]) {
        Scanner ob = new Scanner(System.in);
        int t = ob.nextInt(); //no. of Test Cases
                ob.next(); // for next input whether exception occurs or not
        int a = 0, c = 0;
        for (int j = 0; j < t; j++)
        {
            a = 0; c = 0;
            String str = ob.nextLine();
            String [] spstr = str.split("\\s+");
            try
            {
                for (int i=0 ; i<spstr.length ; i++)
                {
                    if(spstr[i].equals("")) {i--;}
                    else {
                        c = c + Integer.parseInt(spstr[i]);
                        }
                }
                System.out.println(c);
            } catch (Exception e) {
                System.out.println("Invalid Input");
                }
        }
    }
}

What this code do is add any no.s of integers in a single line. Before doing this, I have a Test Case int t. This decides how many inputs must be taken. But this results to an infinite loop even when I am entering integer value.

I have seen this post: How to handle infinite loop caused by invalid input using Scanner which have many answers on how to get rid of this. I have followed the answers, but I have not yet solved this issue.

Note: When I use int t=5;, it works fine. But in this case too, if exception is caught twice, same thing happens.

Please tell me how to solve this infinite loop error ?

Thanks in Advance :)

Community
  • 1
  • 1
Somendra Meena
  • 129
  • 3
  • 12

2 Answers2

1

To begin with, proper indentation helps make code easier to read.

class HelloWorld {
    public static void main(String args[]) {
        Scanner ob = new Scanner(System.in);
        int t = ob.nextInt(); //no. of Test Cases
        ob.next(); // for next input whether exception occurs or not
        int a = 0, c = 0;
        for (int j = 0; j < t; j++) {
            a = 0;
            c = 0;
            String str = ob.nextLine();
            String[] spstr = str.split("\\s+");
            try {
                for (int i = 0; i < spstr.length; i++) {
                    if (spstr[i].equals("")) {
                        i--;
                    } else {
                        c = c + Integer.parseInt(spstr[i]);
                    }
                }
                System.out.println(c);
            } catch (Exception e) {
                System.out.println("Invalid Input");
            }
        }
    }
}

There's several problems.

int t = ob.nextInt(); //no. of Test Cases
ob.next(); // for next input whether exception occurs or not

I don't know what you're hoping to accomplish here. That is not what the linked answer has as a solution. The linked answer is referring to cases where the input is invalid and specifically references catching the exception like so:

try {
    int x = ob.nextInt();
} catch (InputMismatchException e) {
    ob.next();
}

Which I seriously doubt has anything to do with your problem unless you're intentionally entering bad data.

Then there's this, the most likely culprit considering it's a potential infinite loop at first blush.

for (int i = 0; i < spstr.length; i++) {
    if (spstr[i].equals("")) {
        i--;
     } else {
         c = c + Integer.parseInt(spstr[i]);
     }
}

If i is 5 and spstr[i].equals("") returns true then i becomes 4, the else is skipped and i is incremented back to 5 ad infinitum.

kab
  • 131
  • 4
  • Actually I forgot to use `trim()` while splitting the input, so I thought if there's any empty space it would count it as data and will store one less integer from input, so whenever it happens I decreased `i` so that i could have my input. But I was doing many mistakes in my code, as you said. Now got what I wanted to achieve. **Thank You so much for your help** @kab – Somendra Meena Jun 04 '16 at 17:41
1

Simply use ob.nextLine() to ignore it. I fixed the code for you and it works as it should. Your code had several issues which I have mentioned.

import java.util.*;
class HelloWorld {
    public static void main(String args[]) {
        Scanner ob = new Scanner(System.in);
        int t = ob.nextInt(); 
        ob.nextLine();
        int a = 0, c = 0;
        for (int j = 0; j < t; j++)
        {
            a = 0; c = 0;
            String str = ob.nextLine();
            if(str.trim().length()>0){
            String [] spstr = str.trim().split("\\s+");
            try
            {
                for (int i=0 ; i<spstr.length ; i++)
                {
                    c = c + Integer.parseInt(spstr[i]);
                }
                System.out.println(c);
            } catch (NumberFormatException e) {
                System.out.println("Invalid Input");
            }
        }
    }
  }
}
  1. if(spstr[i].equals("")) {i--;} is pointless and wrong logic in fact which will throw your program into an infinite loop. Simply trim the String and check if it is empty as I have done.
  2. Do not simply catch Exception superclass. This is bad for debugging. The Exception raised here is NumberFormatException which you should catch.
Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58
  • In the catch block, you have not written the line `ob.nextLine();` and according to the post which I have linked in the question : **When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.** So how did the token passed to the next input ? – Somendra Meena Jun 04 '16 at 17:32
  • Yes, I tried and it worked absolutely fine. Thanks for your help :) – Somendra Meena Jun 04 '16 at 22:24