有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在输入提示后输入字符串时发生java FileNotFoundException

我不确定输入代码的方式是否正确,或者实际代码中的错误在哪里。我对“try”“catch”比较陌生,当我用Java运行代码的覆盖率时,它显示在输入字符串后,它会直接返回错误。对于这段代码来说,它们的类不止一个,但代码并没有在错误发生之前遍历所有的类。代码的目的是输入有关学生的信息,并通过代码确定他们是否匹配。这个类是这个程序的主要类。当我输入像“Abey”这样的字符串时,问题就出现了,我会得到错误

错误: 请给出学生姓名: 亚比 JAVA伊奥。FileNotFoundException:Abey(系统找不到指定的文件)

我的代码

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.util.NoSuchElementException;

import java.util.Scanner;



public class Match {



 public static void main(String[] args) {



  Student[] arr = new Student[100];



  System.out.println("Please give the student name: ");

  Scanner input = new Scanner(System.in);

  String filename = input.next();


  Scanner nameInput;
  try {
   nameInput = new Scanner(new FileReader(filename));


   int i = 0;



   while (nameInput.hasNextLine()) {



    Scanner ab = new Scanner(nameInput.nextLine());

    ab.useDelimiter("[\t-]");



    String name = ab.next();

    String gender = ab.next();

    String date = ab.next();



    Scanner birthDateReader = new Scanner(date);

    birthDateReader.useDelimiter("-");

    int month = birthDateReader.nextInt();

    int day = birthDateReader.nextInt();

    int year = birthDateReader.nextInt();



    int quietTime = ab.nextInt();

    int music = ab.nextInt();

    int reading = ab.nextInt();

    int chatting = ab.nextInt();



    Date birthdate = new Date(month, day, year);

    Preference pref = new Preference(quietTime, music, reading, chatting);

    Student studentAdd = new Student(name, gender.charAt(0), birthdate, pref);

    arr[i++] = studentAdd;



   }



   int max = i;

   for (i = 0; i < max; i++) {

    if (!arr[i].getMatch()) {

     int bestScore = 0;
     int bestMatch = 0;

     for (int j = i + 1; j < max; j++) {

      if (!arr[j].getMatch()) {

       int tmp = arr[i].compare(arr[j]);

       if (tmp > bestScore) {

        bestScore = tmp;

        bestMatch = j;





       }

      }

     }

     if (bestScore != 0) {

      arr[i].setMatched(true);

      arr[bestMatch].setMatched(true);

      System.out.println(arr[i].getName() + " can match with " + arr[bestMatch].getName() + " with the score " + bestScore);

     } else

     if (!arr[i].getMatch())

      System.out.println(arr[i].getName() + " Does not have any matches.");

    }

   }

   input.close();
  } catch (NoSuchElementException e) {
   System.out.println(e);

  } catch (FileNotFoundException e) {
   System.out.println(e);
  }

 }

}

共 (1) 个答案

  1. # 1 楼答案

    主要问题是,程序正在作为相对路径进行搜索。您需要提供文件的完整路径

    String completePath = "/opt/java/path/"
    Scanner input = new Scanner(System.in);
    
    String filename = input.next();
    
    
    Scanner nameInput;
    try {
    nameInput = new Scanner (new FileReader(completePath+filename));
    

    这将是为您修改的代码

    此处completePath变量包含按学生姓名存储文件的文件夹路径