2016-02-12 96 views
1

我正在試着製作一個計算器來幫助我完成物理作業。爲此,我試圖將輸入分成兩部分,所以輸入「波長18」將把它分成「波長」和「18」作爲數字值。在輸入中輸入第二個字

我明白讓我可以使用

String variable = input.next(); 

但是,有沒有辦法閱讀空間後,隨之而來的第一個字?

謝謝。

+0

您可以使用輸入.nextLine()並使用空格作爲分隔符來分割字符串 –

回答

0
String entireLine = input.nextLine(); 
String [] splitEntireLine = entireLine.split(" "); 
String secondString = splitEntireLine[1]; 
1
String[] parts = variable.split(" "); 
string first = parts[0]; 
string second = parts[1]; 
0

假設你可能也有三個詞或只有一個,最好是不要依靠陣列。所以,我建議在這裏使用List:

final String inputData = input.next(); 
//Allows to split input by white space regardless whether you have 
//"first second" or "first second" 
final Pattern whiteSpacePattern = Pattern.compile("\\s+"); 
final List<String> currentLine = whiteSpacePattern.splitAsStream(inputData) 
.collect(Collectors.toList()); 

然後你就可以做各種檢查,以確保您在列表中值的正確數量,讓您的數據:

//for example, only two args 
if(currentLine.size() > 1){ 
    //do get(index) on your currentLine list 
} 
相關問題