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 :)