2016-12-09 7 views
0

입력 파일을 읽고 출력 파일을 만드는 코드를 작성하려고했습니다. 하지만 올바른 입력 파일 이름이 입력 될 때까지 시도를 추가하려고하면 문제가 발생합니다. FileNotFoundException를 던질 수 있습니다 귀하의 try 블록에는 방법이 없습니다java 더 이상 filenotfoundexception이 없을 때까지 계속 시도하십시오.

public static void main(String[] args) throws FileNotFoundException 
{ 

      //prompt for the input file name 
      Scanner in = new Scanner(System.in); 
      //keep trying until there are no more exceptions 
      //boolean done = false; 
      String inputfilename = " "; 
      while (!done) 
      { 
      try 
      { 
       System.out.print("Input file name (from your computer): "); 
       inputfilename = in.next(); 
       done = true; 
      } 
      catch (FileNotFoundException exception) 
      { 
       System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again."); 
      } 
      } 
      //prompt for the output file name 
      System.out.print("What would you like to call your output file: "); 
      //use outputfilename variable to hold input value; 
      String outputfilename = in.next(); 
      //construct the Scanner and PrintWriter objects for reading and writing 
      File inputfile = new File(inputfilename); 
      Scanner infile = new Scanner(inputfile); 
      PrintWriter out = new PrintWriter(outputfilename); 
      //read the input and write the output 
      out.println("Here is the class average for mstu4031:\n"); 
      double totalgrade = 0; 
      double number = 0; 
      while (infile.hasNextDouble()) 
      { 
      double grade = infile.nextDouble(); 
      out.println("\n"); 
      out.printf("%.1f\n",grade); 
      number++; 
      totalgrade = totalgrade + grade; 
      } 
      //print numbers and average in output file 
      out.println("\n\n"); 
      out.printf("\nNumber of grades: %.1f",number); 
      //calculate average 
      double average = totalgrade/number; 
      out.println("\n\n"); 
      out.printf("\nAverage: %.2f",average); 

      finally 
      {  
      in.close(); 
      out.close(); 
      } 
} 
+0

는'내가 문제가있다, 그것은하지 적절한 filenotfound 예외가 try'에 보여줍니다 당신은이 코드가 제대로 작동 try-catch 블록 중 (안)

희망을 입력 부분을 읽어 뒀다. 그게 무슨 뜻인지 설명해 주시겠습니까? – YoungSpice

+0

받고있는 특정 오류 메시지를 추가 할 수 있습니까? – Tophandour

+0

코드에서'done' 변수의 선언이 주석 처리되어 있으므로 코드가 컴파일되지 않지만 오타라고 가정합니다. – aleb2000

답변

1

은 ....하지 적절한 filenotfound 예외는 시도로 보여줍니다.

try 블록에서 스캐너를 인스턴스화하십시오. 잘못된

String inputfilename = null; 
Scanner infile = null; 
while (!done) 
{ 
    try 
    { 
    System.out.print("Input file name (from your computer): "); 
    inputfilename = in.next(); 
    infile = new Scanner(new File(inputfilename)); 
    done = true; 
    } 
    catch (FileNotFoundException exception) 
    { 
    System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again."); 
    } 
} 
+0

sooooo 고맙습니다. 작동합니다! – maymay

0

여기 : 표준 입력에서 읽은 파일 이름이 존재하지 않는 경우는 예상 FileNotFoundException 발생합니다. 파일이 실제로 존재하는지 확인하지 않고 입력 만 받고 있습니다. 모든 유효한 입력을 통해 루프를 빠져 나갈 수 있습니다. try 블록에 뭔가가 예외를 throw 할 경우

 if(new File(inputfilename).exist()){ 
      done = true; 
     }else{ 
      System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again."); 
     } 
0

에만 예외를 잡을 수 있습니다.

그러나 예외를 포착하는 대신 File.exists() 인 파일이 있는지 테스트해야합니다.

File file; 
do { 
    System.out.print("Input file name (from your computer): "); 
    file = new File(in.next()); 
} while (!file.exists()); 
0

파일을 여는 경우 예외가 발생할 수 있습니다. 그것이 왜 당신이 그들을 시험 블록 안에 넣어야하는지입니다.

//prompt for the input file name 
    Scanner in = new Scanner(System.in); 
    //keep trying until there are no more exceptions 
    //boolean done = false; 
    String inputfilename = " "; 
    while (!done) 
    { 
    try 
    { 
     System.out.print("Input file name (from your computer): "); 
     inputfilename = in.next(); 
     done = true; 
     //prompt for the output file name 
     System.out.print("What would you like to call your output file: "); 
     //use outputfilename variable to hold input value; 
     String outputfilename = in.next(); 
     //construct the Scanner and PrintWriter objects for reading and writing 
     File inputfile = new File(inputfilename); 
     Scanner infile = new Scanner(inputfile); 
     PrintWriter out = new PrintWriter(outputfilename); 
     //read the input and write the output 
     out.println("Here is the class average for mstu4031:\n"); 
     double totalgrade = 0; 
    double number = 0; 
    while (infile.hasNextDouble()) 
    { 
    double grade = infile.nextDouble(); 
    out.println("\n"); 
    out.printf("%.1f\n",grade); 
    number++; 
    totalgrade = totalgrade + grade; 
    } 
    //print numbers and average in output file 
    out.println("\n\n"); 
    out.printf("\nNumber of grades: %.1f",number); 
    //calculate average 
    double average = totalgrade/number; 
    out.println("\n\n"); 
    out.printf("\nAverage: %.2f",average); 
    } 
    catch (FileNotFoundException exception) 
    { 
     System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again."); 
    } 
    } 
    finally 
    {  
    in.close(); 
    out.close(); 
    }