Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
(Java)试图找出如何读取.txt文件_Java - Fatal编程技术网

(Java)试图找出如何读取.txt文件

(Java)试图找出如何读取.txt文件,java,Java,我对Java非常陌生,我有一个项目,我正在尝试创建自己的文本文件,然后将程序中的数字打印到文本文件中 然后我想让软件再次读取这些数字,并显示其中最大的数字 到目前为止,这就是我所做的: String fil = "C:\\Java\\Test.txt"; BufferedWriter fout = new BufferedWriter(new FileWriter(fil, true)); Scanner in = new Scanner(System.in);

我对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

将转发的字符串拆分为3个整数变量,然后进行比较。

完整的解决方案是:

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;
  }

}

一些信息会很有用。会发生什么?任何错误/异常?基本上,它一直工作到最后。它会打印出我写在文件中的任何内容,但我不知道如何或使用什么来再次读取数字并显示最大的数字。啊,听起来不错!您知道如何将字符串拆分为3个整数吗?您可以添加逗号作为拆分点,只需使用string[]parts=string.split(“,”);分开绳子。您可以通过创建新字符串来访问结果:String part1=parts[0];使用part1.parseInt()可以将这些情况转换为整数;我想。*你可以转换为整数。。。不是这样,对不起。