我想将最大的数字从一个文件复制到另一个文件?但是,我找不到最大的数字

时间:2016-05-08 16:03:05

标签: java arrays

我尝试从文件中获取数据,将其转换为字符数组,从文件first.txt中找到最大数字,然后将结果复制到文件second.txt。但是,当我编译并运行程序时,会出现以下问题:

  1. 不使用两位数阵列。
  2. 文本文件中的数字不超过5个
  3. 每当我编译程序时,它会在第二个文件中写下最后一个数字。
  4. 这是我正在使用的代码。

    BufferedReader out = new BufferedReader(new  FileReader("first.txt"));
    PrintWriter in = new PrintWriter(new FileWriter("second.txt"));
    char[] array = null;
    String str = " ";
    str = out.readLine();
    array = str.toCharArray();
    char max = array[0];
    
    for (char c : array) {
        if(c > max);
        max = c;
        in.write(max);
    

2 个答案:

答案 0 :(得分:1)

如果没有必要使用char数组,最好不要。使用String,因为它更容易处理。 String.split()是一种分割first.txt的好方法,Integer.parseInt()可以帮助你将String转换为整数。您可以将它们存储在一个数组上,然后对该数组进行排序。

答案 1 :(得分:0)

(但是,如果我试图把数字放在下面 - 1 2 3 4 然后它只需要一个1的数字。)

BufferedReader out = new BufferedReader(new FileReader(" Nos for fnding highest.txt"));         BufferedWriter in = new BufferedWriter(new FileWriter(" third.txt"));         String str =" &#34 ;;         str = out.readLine();         String [] numbers = str.split("");         // array = str.toCharArray();         // char max = array [0];         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.write(new Integer(max).toString());
        out.close();
        in.close();