也許它只是需要String
的方法,但我真的需要從Scanner
輸入第二個字的值是這樣獲得:如何從Java掃描儀輸入中獲取第二個單詞?
Scanner in = new Scanner(System.in);
String a;
a = in.nextLine();
也許它只是需要String
的方法,但我真的需要從Scanner
輸入第二個字的值是這樣獲得:如何從Java掃描儀輸入中獲取第二個單詞?
Scanner in = new Scanner(System.in);
String a;
a = in.nextLine();
假設您將「單詞」定義爲由空格分隔的部分,並且輸入了恰好兩個單詞:
Scanner in = new Scanner(System.in);
String a;
a = in.nextLine();
String secondWord = a.substring(a.indexOf(" "));
如果有可能更多,使用分裂:
Scanner in = new Scanner(System.in);
String a;
a = in.nextLine();
String secondWord = a.split("\\s+")[1];
使用http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-
這樣a.split(" ")
結果將是數組大小爲2的第二個元素,其中第二個元素爲results.txt
您可以使用scanner.next()
。甲單元測試用例來證明:
@Test
public void testSecondWordSingleLine() {
Scanner scanner = new Scanner("hello hi there");
scanner.next();
assertEquals("hi", scanner.next());
}
它的工作原理也如果第二字是在新的一行,例如:
@Test
public void testSecondWordMultiLine() {
Scanner scanner = new Scanner("hello\nhi there");
scanner.next();
assertEquals("hi", scanner.next());
}
@Test
public void testSecondWordMultiLineWithNextLineFirst() {
Scanner scanner = new Scanner("hello\nhi there");
scanner.nextLine();
assertEquals("hi", scanner.next());
}
使用'a.split( 「\\ S +」);' ? – 2014-09-24 20:00:34
如果您從命令行運行代碼,則應考慮使用傳遞給'main()'的'args'變量而不是從標準輸入讀取。 – 2014-09-24 20:01:37