gpt4 book ai didi

Java数组解析

转载 作者:行者123 更新时间:2023-12-01 15:12:48 25 4
gpt4 key购买 nike

我已将文件读入数组,但想知道如何解析该数组中的某些值。

我的代码:

        ...
try{
...
String strLine;
String delims= "[ ]+";
//parsing it
ArrayList parsedit = new ArrayList();
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
System.out.println(strLine);
parsedit.add(strLine.split(delims));
}
System.out.println("Length:" + parsedit.size());
in.close();
...

我正在读的文件是这样的:

a b c d e f g
1 2 3 4 5 6 7
1 4 5 6 3 5 7
1 4 6 7 3 2 5

这使得输出如下:

How many files will be input? 1
Hey, please write the full path of the input file number1!
/home/User/Da/HA/file.doc
Being read:
a b c d e f g
Being read:
1 2 3 4 5 6 7
...
Length:4

我想解析出这些数据,只保留第一个和第五个值,这样它就会像这样读起来:

a e
1 5

有人有关于如何进行的建议吗?编辑:根据一些建议,我将代码更改为:

public static void main(String[] args) {
System.out.print("How many files will be input? ");
Scanner readIn=new Scanner(System.in);
int input=readIn.nextInt();
int i=1;
while(i<=input){
System.out.println("Hey, please write the full path of the input file number" + i + "! ");
Scanner fIn=new Scanner(System.in);
String fileinput=fIn.nextLine();
try{
FileInputStream fstream=new FileInputStream(fileinput);
DataInputStream in=new DataInputStream(fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String strLine;
String delims= "[ ]+";
ArrayList parsedit = new ArrayList();
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
System.out.println(strLine);
parsedit.add(strLine.split(delims));
}
String[] splits=strLine.split(delims);
System.out.println("Length:" + splits.length);
in.close();
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
i++;
}
}
}

这不会返回任何错误,但似乎并不能完全正常工作。我错过了一些愚蠢的事情吗?输出是这样的:

How many files will be input? 1
Hey, please write the full path of the input file number1!
/home/User/Da/HA/file.doc
Being read:
a b c d e f g
Being read:
1 2 3 4 5 6 7
...

但是,尽管我有一行告诉我数组长度,但它永远不会被打印出来,这告诉我,我最终破坏的内容比我修复的内容还要多。你知道我可能遗漏/忘记了什么吗?

最佳答案

split() 函数返回一个字符串数组,表示从原始字符串获取的标记。

因此,您想要的是仅保留第一个和第五个标记(splits[0] 和 splits[4]):

  String[] splits = strLine.split(delims); 
//use the splits[0] & splits[4] to create the Strings you want

关于您的更新,请将其替换为:

 while((strLine=br.readLine())!=null){
System.out.println("Being read:");
System.out.println(strLine);
parsedit.add(strLine.split(delims));
}

这样:

 while((strLine=br.readLine())!=null){
System.out.println("Being read:");
String splits[] = strLine.split(delims);
System.out.println(splits[0]+" "+splits[4]);
parsedit.add(splits);
}

关于Java数组解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12094338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com