简体   繁体   English

对于 nextInt(),Java.util.scanner 没有此类元素异常

[英]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. Next int 显然存在,但 Scanner 抛出 NoSuchElement 异常。 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我得到输出:我们有:[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.因此,无论谁想告诉我和其他阅读如何将任何内容转换为 Scanner 的人,都会认为它正在读入 Int。 (Integer.parseInt() wouldn't work) (Integer.parseInt() 不起作用)

I properly allocated scan with Scanner scan = new Scanner(System.in)我使用 Scanner scan = new Scanner(System.in) 正确分配了扫描

Then Scanner reads from System.in (standard input).然后ScannerSystem.in (标准输入)读取。 Not the command line.不是命令行。 You could concatenate your arguments into a String and then use that as a source for your Scanner .您可以将您的参数连接到一个String ,然后将其用作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).因为这不是比较String (s) 的好方法。 You need something like你需要类似的东西

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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