繁体   English   中英

我想将最大数字从一个文件复制到另一个文件?但是,输入数字时遇到一些问题

[英]I want to Copy the Largest number from one file to another File?But,I get some problems while inputting the numbers

每当我尝试这样写数字时,

(1
2
3
4
56)

它只需要第一个数字。我的代码有什么问题。这是我的代码。

BufferedReader out = new BufferedReader(new FileReader("Nos for finding highest.txt"));
PrintWriter in = new PrintWriter(new FileWriter("third.txt"));
String str = " ";
str = out.readLine();
String[] numbers = str.split("\n");
int[] array = new int[numbers.length];
int count = 0;
for (String strs : numbers) {
    array[count++] = Integer.parseInt(strs);
}
int max = array[0];
for (int c : array) {
    if (c > max)
        max = c;
}

in.println(new Integer(max).toString());

in.close();

out.close();

如果我在上面的代码中使用while((str = out.readLine()) != null) ,那么它将打印出所有数字,而不是打印max(Largest Number)

如果您输入的数字在同一行上,请使用空格分隔输入:

String[] numbers = str.split(" ");

如果文件中的数字都换行,请使用

String[] numbers = str.split("\n"); 

由于格式方面的原因,我将在评论中进行扩展:假设文件每行有一个数字,您首先需要将它们全部读入一个列表:

List<Integer> list = new LinkedList<>();
while((str = out.readLine()) != null) {
  //assuming the line is not empty and contains a valid integer
  list.add( Integer.valueOf(str) ); 
}

然后迭代并寻找最大的数字:

for( Integer i : list ) {
  //check for max here
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM