2014-09-24 63 views
1

也許它只是需要String的方法,但我真的需要從Scanner輸入第二個字的值是這樣獲得:如何從Java掃描儀輸入中獲取第二個單詞?

Scanner in = new Scanner(System.in); 
String a; 
a = in.nextLine(); 
+1

使用'a.split( 「\\ S +」);' ? – 2014-09-24 20:00:34

+1

如果您從命令行運行代碼,則應考慮使用傳遞給'main()'的'args'變量而不是從標準輸入讀取。 – 2014-09-24 20:01:37

回答

2

假設您將「單詞」定義爲由空格分隔的部分,並且輸入了恰好兩個單詞:

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]; 
1

您可以使用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()); 
}