该字符串例如为 "r1"
我需要 1
在 int
表格
Scanner sc = new Scanner("r1");
int result = sc.nextInt(); // should be 1
编译正确,但出现运行时错误,我应该使用分隔符吗?我不确定分隔符的作用。
最佳答案
嗯,有几个选择。由于您确实想跳过“r”然后读取数字,因此您可以使用 Scanner#skip
。例如,要跳过所有非数字,然后读取数字:
Scanner sc = new Scanner("r1");
sc.skip("[^0-9]*");
int n = sc.nextInt();
如果没有前导非数字,这也将起作用。
正如您提到的,另一种选择是使用非数字作为分隔符。例如:
Scanner sc = new Scanner("x1 r2kk3 4 x56y 7g");
sc.useDelimiter("[^0-9]+"); // note we use + not *
while (sc.hasNextInt())
System.out.println(sc.nextInt());
输出六个数字:1、2、3、4、56、7。
还有另一种选择,根据输入的性质,通过提前用空格替换所有非数字来预处理字符串,然后使用默认配置的扫描仪,例如:
String input = "r1";
input = input.replaceAll("[^0-9]+", " ");
当然,如果您知道字符串采用这种形式,您始终可以预处理字符串以删除第一个字符,然后使用扫描仪(或只是 Integer#parseInt
):
String input = "r1";
input = input.substring(1);
您的操作取决于最适合您输入的内容。将“非数字”替换为您想要跳过的任何内容。
<小时/>顺便说一句,我相信一盏灯scolding is in order for this :
Im unsure what the delimiter does.
扫描仪文档 explains this quite clearly在介绍文本中,甚至还展示了一个示例。
此外,“分隔符”一词本身的定义是 readily available .
关于Java Scanner 从字符串中获取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39944772/