(Java)试图弄清楚如何从.txt文件中读取

时间:2015-10-11 19:27:42

标签: java

我是Java新手,我有一个项目,我正在尝试创建自己的文本文件,然后将程序中的数字打印到文本文件中。

然后我希望软件再次读取数字并显示最大数字。

到目前为止,这就是我所做的:

    String fil = "C:\\Java\\Test.txt";
    BufferedWriter fout = new BufferedWriter(new FileWriter(fil, true));
    Scanner in = new Scanner(System.in);
    System.out.print("Skriv in tre tal: ");
    int x = in.nextInt();
    int y = in.nextInt();
    int z = in.nextInt();
    fout.write(x + " " + y + " " + z);
    fout.newLine();
    fout.flush();

    BufferedReader fin = new BufferedReader(new FileReader(fil));
    String s = fin.readLine();
    System.out.println(s);

我只是不知道如何让我的软件找到代码中最大的数字,然后打印出来。

提前致谢 / Fsociety1337

2 个答案:

答案 0 :(得分:0)

将被响应的String拆分为3个整数变量,然后进行比较。

答案 1 :(得分:0)

完整的解决方案是:

public class LargestNumberFinder {

  public static final String FILENAME = "C:\\Java\\Test.txt";

  public static void main(String[] args) throws IOException {
      BufferedWriter fout = new BufferedWriter(new FileWriter(FILENAME, true));
      Scanner in = new Scanner(System.in);
      System.out.print("Skriv in tre tal: ");
      int x = in.nextInt();
      int y = in.nextInt();
      int z = in.nextInt();
      fout.write(x + " " + y + " " + z);
      fout.newLine();
      fout.flush();

      BufferedReader fin = new BufferedReader(new FileReader(FILENAME));
      String s = fin.readLine();
      System.out.println(s);

      int largest = getLargestNumberFromFile(FILENAME);
      System.out.println("The largest number is: " + largest);
  }

  private static int getLargestNumberFromFile(String filename) throws FileNotFoundException {
      int largest = -1;
      Scanner scanner = new Scanner(new File(filename));
      scanner.useDelimiter(" |[\\r\\n]+");
      while(scanner.hasNext()) {
          int currentNumber = scanner.nextInt();
          if (currentNumber > largest) {
              largest = currentNumber;
          }
      }
      scanner.close();

      return largest;
  }

}