gpt4 book ai didi

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

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

每当我尝试像这样写数字时 -

(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).

最佳答案

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

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
}

关于java - 我想将最大数字从一个文件复制到另一个文件?但是,我在输入数字时遇到一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37120398/

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