简体   繁体   中英

No Such Element Exception with Java.util.scanner for nextInt()

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)

I properly allocated scan with Scanner scan = new Scanner(System.in)

Then Scanner reads from System.in (standard input). Not the command line. You could concatenate your arguments into a String and then use that as a source for your Scanner . Like,

Scanner scan = new Scanner(String.join(" ", args));

You will also need to change (at least)

(s+t).trim() != "-s"

because that is not a good way to compare String (s). You need something like

!(s+t).trim().equals("-s")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM