簡體   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