[英]I want to Copy the Largest number from one file to another File?But,I get some problems while inputting the numbers
Whenever I try to write the Numbers like this- 每当我尝试这样写数字时,
(1
2
3
4
56)
It takes only the first number.What is wrong with my code.This is my code. 它只需要第一个数字。我的代码有什么问题。这是我的代码。
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();
If I take while((str = out.readLine()) != null)
in the above code then it printouts all the numbers instead of printing max(Largest Number)
. 如果我在上面的代码中使用
while((str = out.readLine()) != null)
,那么它将打印出所有数字,而不是打印max(Largest Number)
。
If you input the numbers are on on the same line then split the input using space: 如果您输入的数字在同一行上,请使用空格分隔输入:
String[] numbers = str.split(" ");
If your numbers in the file are each in new line then use 如果文件中的数字都换行,请使用
String[] numbers = str.split("\n");
I'll expand on my comment for formatting reasons: Assuming your file has one number per line you'll want to first read them all into a list: 由于格式方面的原因,我将在评论中进行扩展:假设文件每行有一个数字,您首先需要将它们全部读入一个列表:
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) );
}
Then iterate and look for the highest number: 然后迭代并寻找最大的数字:
for( Integer i : list ) {
//check for max here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.