Trying to do some Command Line Arguments for a program. Next int is clearly present but Scanner throws NoSuchElement exception. With or without new line/whitespace skip, trim() on string before it, etc.
try {
String s = String.valueOf(scan.next().charAt(0));
String t = String.valueOf(scan.next().charAt(0));
if ((s+t).trim() != "-s") {
throw new IOException ("Size must be allocated with “-s”.");
}
System.out.println("Got ''-s'' successfully.");
} catch (IOException SizeFormatIncorrect) {
}
try {
//scan.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); - with or
//without, gives same problem
size = scan.nextInt();
System.out.println("Got " + size);
} catch (NumberFormatException NotInt)
{ }
Input:
-s 200 or -s 2
OR
-s\n200 or -s\n2
Output:
Enter variables to test call:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at HelloWorld.main(HelloWorld.java:28)
//(Line 28 is size = scan.nextInt())
//If I add
if (!scan.hasNextInt()){
System.out.println("We have :" + scan.nextLine().getBytes());
}
I get output: We have :[B@42a57993
So whoever wants to tell me and everyone else reading how to cast whatever it is Scanner thinks it's reading in to an Int. (Integer.parseInt() wouldn't work)