Reputation: 1139
I encountered an error when executing my program.
I execute my program and fed data in an input file.
Contents of the input file
LIMIT
2
ADD 30 60
MUL -60 60
I got an exception error as follows.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Test.doLimit(Test.java:41)
at Test.checkResult(Test.java:24)
at Test.main(Test.java:15)
I googled and I believed that String input = sc.next(); inside the for loop should be causing the error. May I know how to resolve this error?
My code is as attached below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
checkResult(input);
}
public static void checkResult(String input)
{
if(input.equals("LIMIT"))
{
//do stuff
doLimit();
}
else if(input.equals("SENT"))
{
//do stuff
}
else
{
//do stuff
}
}
public static void doLimit()
{
Scanner sc = new Scanner(System.in);
int numOfInput = sc.nextInt();
int x,y;
for(int i = 0; i < numOfInput; i++)
{
String input = sc.next();
x = sc.nextInt();
y = sc.nextInt();
if(input.equals("ADD"))
{
//add
}
else if(input.equals("SUB"))
{
//sub
}
else
{
//multiple
}
}
}
Upvotes: 1
Views: 2045
Reputation: 2555
If you are sending the data through the input file, you have to provide that file
in the Scanner()
constructor.
What you have currently done is provided System.in
.
EDIT :
Also, you have to open the Scanner on the file just once and use it throughout. In this case,
1) You are opening the scanner and reading the first line.
2) Then in the doLimit function, you again open the scanner and read the first line of the input file which is not an integer.
Hence, the error.
Upvotes: 0
Reputation: 1253
The default delimiter of the scanner is the whitespace. However, you plan to use as input for the first 2 lines the new line as delimiter and then either whitespace and new line, as it comes first. Maybe that is the problem. Try writing everything on one line, whitespace separated.
Upvotes: 0
Reputation: 13713
You should check if there is more input. You can see in the stack trace that nextInt
is involved and if you look at the SDK you would see that this exception is thrown when
input is exausted.
anyway you problem is here :
int numOfInput = sc.nextInt();
so make sure you have valid input before asking for it :
if (sc.hasNextInt()) {
.
.
.
}
Upvotes: 1