[英]How would I go about using an integer delimiter? (Java)
So I am trying to read a file using a scanner. 因此,我尝试使用扫描仪读取文件。 This file contains data where there are two towns, and the distance between them follows them on each line. 该文件包含两个镇的数据,并且它们之间的距离在每行上都遵循它们。 So like this: 像这样:
Ebor,Guyra,90 埃布尔,圭拉,90岁
I am trying to get each town individual, allowing for duplicates. 我试图让每个城镇的人,允许重复。 This is what I have so far: 这是我到目前为止的内容:
// Create scanner for file for data
Scanner scanner = new Scanner(new File(file)).useDelimiter("(\\p{javaWhitespace}|\\.|,)+");
// First, count total number of elements in data set
int dataCount = 0;
while(scanner.hasNext())
{
System.out.print(scanner.next());
System.out.println();
dataCount++;
}
Right now, the program prints out each piece of information, whether it is a town name, or an integer value. 现在,程序将打印出每条信息,无论它是城镇名称还是整数值。 Like so: 像这样:
Ebor bor
Guyra 盖拉
90 90
How can I make it so I have an output like this for each line: 如何做到这一点,所以每行都有这样的输出:
Ebor bor
Guyra 盖拉
Thank you! 谢谢!
Assuming well-formed input, just modify the loop as: 假设输入格式正确,只需将循环修改为:
while(scanner.hasNext())
{
System.out.print(scanner.next());
System.out.print(scanner.next());
System.out.println();
scanner.next();
dataCount += 3;
}
Otherwise, if the input is not well-formed, check with hasNext()
before each next()
call if you need to break the loop there. 否则,如果没有很好地形成的输入,请与hasNext()
每前next()
调用,如果你需要打破循环出现。
Try it that way: 尝试这种方式:
Scanner scanner = new Scanner(new File(file));
int dataCount = 0;
while(scanner.hasNext())
{
String[] line = scanner.nextLine().split(",");
for(String e : line) {
if (!e.matches("-?\\d+")) System.out.println(e);;
}
System.out.println();
dataCount++;
}
}
We will go line by line, split it to array and check with regular expression if it is integer. 我们将逐行处理,将其拆分为数组,并使用正则表达式检查它是否为整数。
-? stays for negative sign, could have none or one
\\d+ stays for one or more digits
Example input: 输入示例:
Ebor,Guyra,90
Warsaw,Paris,1000
Output: 输出:
Ebor
Guyra
Warsaw
Paris
I wrote a method called intParsable: 我写了一个叫做intParsable的方法:
public static boolean intParsable(String str)
{
int n = -1;
try
{
n = Integer.parseInt(str);
}
catch(Exception e) {}
return n != -1;
}
Then in your while loop I would have: 然后在您的while循环中,我将有:
String input = scanner.next();
if(!intParsable(input))
{
System.out.print(input);
System.out.println();
dataCount++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.