입력 파일을 읽고 출력 파일을 만드는 코드를 작성하려고했습니다. 하지만 올바른 입력 파일 이름이 입력 될 때까지 시도를 추가하려고하면 문제가 발생합니다. 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();
}
}
는'내가 문제가있다, 그것은하지 적절한 filenotfound 예외가 try'에 보여줍니다 당신은이 코드가 제대로 작동 try-catch 블록 중 (안)
희망을 입력 부분을 읽어 뒀다. 그게 무슨 뜻인지 설명해 주시겠습니까? – YoungSpice
받고있는 특정 오류 메시지를 추가 할 수 있습니까? – Tophandour
코드에서'done' 변수의 선언이 주석 처리되어 있으므로 코드가 컴파일되지 않지만 오타라고 가정합니다. – aleb2000