Java程序:Java:解析輸入,用逗號分隔
下面的輸入只是我的頭頂。我正在尋找的是如何根據它們是字符串還是基本類型來獲取輸入數據的特定部分...在這裏我認爲使用以某種方式將它們分開的逗號可能會很有用。
/* Given input:
*
* Massachusetts, Ma, Boston, 10000, 20000
* California, CA, Los Angeles, 30000, 40000
* How would you print:
* Massachusetts 20000
* California 40000
*/
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in) ;
while (userInput.hasNextLine()) {
String state = userInput.nextLine() ;
Double population = userInput.nextDouble() ;
String temp = userInput.nextLine() ; // for the new line
System.out.printf("%s %2f" , state , population) ;
}
}
我也見過一個叫useDelimiter()方法,我在想,如果這可能有助於從我的掃描儀分手的輸入。
如果你問代碼的問題,它總是有幫助的添加標籤爲您所使用的語言。您可能想要[編輯]這樣做。 –
只需閱讀整行內容並將其拆分爲「,」。然後你可以輕鬆獲得你的價值觀。 – ManoDestra
只是在ManoDestras的評論頭上。如果您希望數據正確(例如,第一個數據是城市名稱,第二個數據是狀態數據,第三個數據總是相同等等),那麼使用'String.split()'...... – Bonatti