[英]Java: Parsing Input separated by commas
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()的方法,我想知道這是否有助於打破我的掃描儀的輸入。
給定字符串Massachusetts, Ma, Boston, 10000, 20000
,您可以使用split獲得數組[Massachusetts, Ma, Boston, 10000, 20000]
(請注意,這不再是字符串)
String input = "Massachusetts, Ma, Boston, 10000, 20000";
String[] fields = input.split(", ?");
String state = fields[0];
String xx = fields[4];
System.out.println(state+", "+xx); // Massachusetts, 20000
注意正則表達式, ?
表示逗號,后接空格或不接空格 。 另外,由於這是用戶輸入的內容,因此您應該檢查fields
數組是否具有所需的長度(在這種情況下,由於要訪問第四個字段,因此長度至少應為5)
我想您可以從此示例輕松修改您的代碼;)
一種解決方案是使用Regex。
Pattern p = Pattern.compile("([A-z]+), ([A-z]{2}), ([A-z]+), (\\d+), (\\d+)");
String line = userInput.nextLine();
Matcher lineMatcher = p.matcher(line);
if (lineMatcher.matches()) {
System.out.println(lineMatcher.group(0)); //prints Massachusetts
System.out.println(lineMatcher.group(1)); //prints Ma
System.out.println(lineMatcher.group(2)); //prints Boston
System.out.println(lineMatcher.group(3)); //prints 10000
System.out.println(lineMatcher.group(4)); //prints 20000
}
如果我正確理解了您的問題,並且您的輸入為String類型,則可以使用以下方法:
public String [] split(String regex),其中您的正則表達式為“,”。
它將返回一個String []。 您可以使用索引單獨打印每個值,然后使用Float.parseFloat(String value)將字符串轉換為浮點類型。
String userInput = "Massachusetts, Ma, Boston, 10000, 20000";
userInput = userInput.replaceAll("\\s+", ""); //replaces whitespace
String[] values = userInput.split(",");
System.out.println(values[0]);
System.out.println(values[4]);
String state = values[0];
// you probably do not want a float for population
float population = Float.parseFloat(values[4]);
System.out.printf( "%s %2f" , state , population );
// you probably want an integer, so try this
int integerPopulation = Integer.parseInt(values[4]);
System.out.printf( "%s %2d" , state , integerPopulation);
輸入您的代碼,您可以進行以下更改:
String[] temp = new String[5];
while (userInput.hasNextLine()) {
String input = userInput.nextLine();
temp[] = input.split(",");
System.out.printf( "%s %s" ,temp[0] , temp[4] ) ;
}
調用nextLine()時,您可以獲取該輸入的整行。 從逗號中拆分()並將其存儲到臨時數組中。 然后根據您的要求打印這些值。 如果需要進行任何計算,則可以從temp數組轉換該值的數據類型。
您可以使用此行將字符串值轉換為float:
Float.valueOf(temp[4]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.