尝试为程序执行一些命令行参数。显然存在下一个int,但Scanner抛出NoSuchElement异常。有无新行/空白跳过,在其前面的字符串上trim()等。
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());
}
我得到输出: 我们有:[B @ 42a57993
因此,无论谁想告诉我,以及其他阅读如何投射任何内容的人,Scanner都认为它正在读入Int。 (Integer.parseInt()无效)
答案 0 :(得分:0)
我使用Scanner scan = new Scanner(System.in)正确分配了扫描
然后Scanner
从System.in
(标准输入)读取。不是命令行。您可以将参数串联到String
中,然后将其用作Scanner
的源。喜欢,
Scanner scan = new Scanner(String.join(" ", args));
您还需要更改(至少)
(s+t).trim() != "-s"
因为这不是比较String
的好方法。您需要类似
!(s+t).trim().equals("-s")