26,15,37
我怎样才能从扫描仪中获取数字,(例如我想添加或减去,,,?)
答案 0 :(得分:7)
如果您想使用Scanner
API:
private static final Pattern COMMA_PATTERN = Pattern.compile("\\s*,\\s*");
public List<Integer> getIntegerList() {
// Assumes scanner is positioned at first integer in list.
List<Integer> integers = new ArrayList<Integer>();
for (;;) {
integers.add(scanner.nextInt());
if (scanner.hasNext(COMMA_PATTERN)) {
// Read and discard comma token, and continue parsing list.
scanner.next();
} else {
// Number is not followed by comma, stop parsing.
break;
}
}
return integers;
}
需要更多的错误处理,但希望这个例子说明了这种方法。
您还可以使用Scanner.useDelimiter()
:
private static final Pattern COMMA_PATTERN = Pattern.compile("\\s*,\\s*");
public List<Integer> getIntegerList() {
// Assumes scanner is positioned at first integer in list.
List<Integer> integers = new ArrayList<Integer>();
Pattern oldDelimiter = scanner.delimiter();
scanner.useDelimiter(COMMA_PATTERN);
while (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
// Reset delimiter
scanner.useDelimiter(oldDelimiter);
return integers;
}
答案 1 :(得分:3)
使用Scanner.useDelimiter
。它实际上需要正则表达式,所以你想学习一些基础知识。
String text = "1 , 2 3, 4,5";
Scanner sc = new Scanner(text).useDelimiter("\\s*,?\\s*");
while (sc.hasNextInt()) {
System.out.println(sc.nextInt());
} // prints "1", "2", "3", "4","5"
hasNextInt()
来防止异常比Integer.parseInt
和catch NumberFormatException
答案 2 :(得分:2)
String.split()没问题,但StringTokenizer适用于所有版本的Java。
StringTokenizer st = new StringTokenizer("26, 15, 37", ", ");
int sum = 0;
while (st.hasMoreTokens()) {
sum += Integer.parseInt(st.nextToken());
}
答案 3 :(得分:2)
尝试为扫描仪对象设置分隔符:
Scanner s = new Scanner(System.in).useDelimiter(", *");
int first = s.nextInt();
int second = s.nextInt();
...
更多示例可以在Scanner documentation中找到。
答案 4 :(得分:0)
看看useDelimiter。你需要一个匹配空格或逗号的正则表达式。