在java中从文件中读取包含逗号和空格的行
我正在读取一个文件,该文件有一行,其中一对数字由逗号分隔:在java中从文件中读取包含逗号和空格的行,java,arrays,string,file,parsing,Java,Arrays,String,File,Parsing,我正在读取一个文件,该文件有一行,其中一对数字由逗号分隔: 1 2, 2 3, 3 1, 4 1, 2 4, S 其结果是: ValueOne - 1 -- ValueTwo - 2 ValueOne - 2 -- ValueTwo - 3 ValueOne - 3 -- ValueTwo - 1 ValueOne - 4 -- ValueTwo - 1 ValueOne - 2 -- ValueTwo - 4 Break 这是我当前的代码: try{ Scanner
1 2, 2 3, 3 1, 4 1, 2 4, S
其结果是:
ValueOne - 1 -- ValueTwo - 2
ValueOne - 2 -- ValueTwo - 3
ValueOne - 3 -- ValueTwo - 1
ValueOne - 4 -- ValueTwo - 1
ValueOne - 2 -- ValueTwo - 4
Break
这是我当前的代码:
try{
Scanner scanner = new Scanner(new File("graph.txt"));
while(scanner.hasNextLine()){
String value = scanner.next();
String[] values = value.split(" |,");
if(value.equals("S")){
System.out.println("Break");
break;
}
int v1 = Integer.parseInt(values[0]);
int v2 = Integer.parseInt(values[1]);
System.out.println("ValueOne - " + v1 + " -- " + "ValueTwo - "+ v2);
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
我在“int v2=Integer.parseInt(values[1]);”处得到了一个数组索引outofboundsException
我肯定我错过了一些愚蠢的东西,但我只是需要一些新鲜的眼睛来看看它。谢谢。您没有正确拆分字符串。您需要执行以下操作:
String[] values = value.split(",");
但即使这样,您也无法获得预期的输出。这将把这些值分成几对。然后你必须像这样再次吐痰:
for(String value : values){
String[] pairs = value.split(" ");
int v1 = Integer.parseInt(pairs[0]);
int v2 = Integer.parseInt(pairs[1]);
System.out.println("ValueOne - " + v1 + " -- " + "ValueTwo - "+ v2);
}
这只是从您的文件中获取第一个令牌。您需要将其替换为以下内容,以便阅读整行内容:
String value = scanner.nextLine();
此外,您还需要进行两次单独的拆分。一次在逗号上拆分,这样您就有了元素[1 2]、[2 3]等,另一次在您的空格上拆分,这样您就可以具体引用每个值并根据需要打印出来。您的扫描仪。next()
一次只读取一个标记(直到空格),所以您不能直接使用拆分(“,”
),相反,您需要编写逻辑,如下代码所示,并附上注释:
String v1 = null;
String v2 = null;
Scanner scanner = new Scanner(new File("graph.txt"));
while(scanner.hasNextLine()){
String value = scanner.next();
if(value.equals("S")){
System.out.println("Break");
break;
}
//Check if token ends with ','
if(value.endsWith(",")) {
v1 = v2;//swap v1 and v2
v2 = value.substring(0, value.length());//substring till ','
//Since ',' one pair consumed, so print the values
System.out.println("ValueOne - " + v1 + " -- " + "ValueTwo - "+ v2);
} else {
//If token does not end with ',' just consume value, don't print
v2 = value;
}
}
String v1 = null;
String v2 = null;
Scanner scanner = new Scanner(new File("graph.txt"));
while(scanner.hasNextLine()){
String value = scanner.next();
if(value.equals("S")){
System.out.println("Break");
break;
}
//Check if token ends with ','
if(value.endsWith(",")) {
v1 = v2;//swap v1 and v2
v2 = value.substring(0, value.length());//substring till ','
//Since ',' one pair consumed, so print the values
System.out.println("ValueOne - " + v1 + " -- " + "ValueTwo - "+ v2);
} else {
//If token does not end with ',' just consume value, don't print
v2 = value;
}
}