gpt4 book ai didi

java - 从文本文件中读取两列并在 java 中对两列进行排序

转载 作者:行者123 更新时间:2023-12-02 06:46:35 25 4
gpt4 key购买 nike

18 14
19 15
20 16
21 17
22 18
23 19
24 20
25 20
25 21

47 44
48 44
48 45
49 44

49 43
49 42
50 42
50 43
51 43
53 40
53 39
53 38
54 38
54 39

我的工作是我应该读取这个输入文件,删除空白行并对两列进行排序这里是我的java代码,它尝试读取文件并打印出它的值:这里我将整数存储在不同的数组中代码是:

import java.io.*;
import java.lang.*;
import java.util.*;

public class read
{
public static void main(String[] args) throws Exception
{
System.out.println("Enter file name");
DataInputStream dis=new DataInputStream(System.in);
String dir1=dis.readLine();
File infile = new File(dir1);
System.out.println("Enter output file name");
DataInputStream dis2=new DataInputStream(System.in);
String dir3=dis.readLine();
String path="E:/photos";
String newpath=path + "/" +dir3;
File outfile = new File(newpath);
int newcount=0,newcount1=0;
FileReader fr=new FileReader(infile);
BufferedReader fr11= new BufferedReader(fr);
FileWriter fw = new FileWriter(outfile);
BufferedWriter bufferFileWriter = new BufferedWriter(fw);
Scanner input = new Scanner(infile);
String[] outputArray1 = new String[31];
String[] outputArray2 = new String[31];
int i = 0;
while (input.hasNextLine())
{
String line = input.nextLine();
if(line.length() > 0)
{
String[] columns = line.split(" ");
System.out.println("my first column : "+ columns[0] );
System.out.println("my second column : "+ columns[1] );
outputArray1[i] = columns[0];
outputArray2[i] = columns[1];
i++;
}
}
String[][] temp = new String[2][];
temp[0]= outputArray1;
temp[1]= outputArray2;
for (int k=0;k<2;k++)
for (int j=0;j<i;j++)
{
System.out.println("new row"+k+"new col"+j+"value="+temp[k][j]);
}
if (temp.length > 0) {
for (int m = 0; m< temp[0].length; m++) {
for (int n = 0; n< temp.length; n++) {
System.out.print(temp[n][m] + " ");
}
System.out.print("\n");
}
}
fr.close();
fw.close();
bufferFileWriter.close();
}
}

最佳答案

You can go for this approach, Create a List<Item> where Item is a type containing 2 Column values. (x1 and x2)

Then write a compareTo(Item o) which compares the x1 values of the two Item objects presented to it in compare, and if that gave a definite answer, returned that answer.

public class Item implements Comparable<Item> {
private Integer int1;
private Integer int2;

@Override
public int compareTo(Item o) {
return int1 > (o.int1);
}
}

希望这有帮助。

关于java - 从文本文件中读取两列并在 java 中对两列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18579357/

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