[英]Parse different types of data from input java
在命令行上將輸入不同的數據列表。
"J,A,V,A"
"4,H,11,V,3,H"
我需要將第一個列表存儲在char數組中。 我還想在char數組“ H,V,H”和int數組“ 4,11,3”中包含下一行。 這樣做的最佳方法是什么? 我不願意在逗號上進行拆分,因為我不知道輸入是否將僅由逗號或逗號和空格分隔。 我遇到了困難,因為當我使用掃描儀時,所有內容都保留在字符串中,而當我嘗試對其進行拆分時,字符串變成了字符串數組。
我遇到了困難,因為當我使用掃描儀時,所有內容都保留在字符串中,而當我嘗試對其進行拆分時,字符串變成了字符串數組。
以下內容似乎對我有用。.僅在調試器中運行它,但在您提供的兩行輸入中起作用。
import java.lang.System;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> ints = new ArrayList<Integer>();
ArrayList<Character> chars = new ArrayList<Character>();
Scanner console = new Scanner(System.in);
while (console.hasNext()) {
String line = console.next();
String[] tokens = line.split("\\s*,\\s*");
for (int i = 0; i < tokens.length; i++) {
if (isInteger(tokens[i])) {
ints.add(Integer.parseInt(tokens[i]));
} else if (isChar(tokens[i])) {
chars.add((char) tokens[i].indexOf(0));
}
}
}
console.close();
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
private static boolean isChar(String s) {
if (s.length() != 1) {
return false;
}
return true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.