Java try-catch无法正常工作

时间:2013-02-12 00:24:00

标签: java exception

想知道是否有人可以告诉我为什么我的try-catch不起作用。当我输入一个整数时,我输入一个字符,程序只是以异常退出。它与我在另一个程序中编写的try-catch相同。不知道为什么它不起作用。 :(

import java.io.*;
import java.util.*;

public class Lab8FileIO {
    public static void main(String[] args) throws IOException {

    int menuChoice = 0;
    String filename, userInput, choice;
    boolean playAgain = true;
    char response;
    Scanner keyboard = new Scanner(System.in);

    while (playAgain)
    {
        // Display menu and get user selection
        displayMenu();

        do
        {
            try 
            {
                menuChoice = keyboard.nextInt();

                if ((menuChoice < 1) || (menuChoice > 4)) // Make sure user enters a number within the specified range
                    System.out.print("You must enter a number from 1 to 4!");
            } 

            catch (InputMismatchException e) 
            {
                System.out.print("You must enter a number from 1 to 4!");
                keyboard.nextInt();
            }
        } while (menuChoice < 1 && menuChoice > 4);

        // Get input/output filename from user
        System.out.print("\nEnter filename in the format filename.txt: ");
        filename = keyboard.next();

        switch (menuChoice)
        {
        // Write to file
        case 1:
            PrintWriter outputFile = new PrintWriter(filename);

            userInput = getUserInput(); 
            System.out.println("I am writing your input to filename: " + filename + "\n");
            outputFile.println(userInput);
            outputFile.close();
            break;

        // Read from file
        case 2:
            File file = new File(filename); 
            Scanner inputFile = new Scanner(file);

            System.out.println("I am reading from filename: " + filename + "\n");

            while (inputFile.hasNextLine())
            {
                String line = inputFile.nextLine();
                System.out.println(line);
            }
            inputFile.close();
            break;

        // Append to file   
        case 3:
            FileWriter appendFile = new FileWriter(filename, true);

            userInput = getUserInput(); 
            System.out.println("I am appending your input to filename: " + filename + "\n");
            appendFile.write(userInput);
            appendFile.close();         
            break;

        // Exit 
        case 4:
            System.out.println("Goodbye!");
            System.exit(0);
            break;              
        }

        // Ask user to play again
        do
        {
            System.out.print("\nWould you like to continue (Y/N)? ");
            choice = keyboard.next();
            response = Character.toUpperCase(choice.charAt(0));
        } while (response != 'Y' && response != 'N'); // Keep asking until user enters correct response

        if (response == 'Y') // Play again
        {
            playAgain = true;
            System.out.println();
        }

        else if (response == 'N') // Quit
        {
            playAgain = false;
            System.out.println("\nThanks for playing!");
        }
    } 

}

public static void displayMenu()
    {
        System.out.println("File IO Options:");
        System.out.println("1) Write");
        System.out.println("2) Read");
        System.out.println("3) Append");
        System.out.println("4) Quit");
        System.out.print("What would you like to do: ");
    }

    public static String getUserInput()
    {
        String str;
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Start typing. Hit enter when you're done:");
        str = keyboard.nextLine();

        return str;
    }   
}

这是我得到的错误:

文件IO选项:
1)写上 2)阅读
3)附加
4)退出
你想做什么:a 您必须输入1到4之间的数字!线程“main”中的例外情况
java.util.InputMismatchException
    在java.util.Scanner.throwFor(Scanner.java:840)
    在java.util.Scanner.next(Scanner.java:1461)
    在java.util.Scanner.nextInt(Scanner.java:2091)
    在java.util.Scanner.nextInt(Scanner.java:2050)
    在Lab8FileIO.main(Lab8FileIO.java:41)

1 个答案:

答案 0 :(得分:5)

您的计划失败,因为在您的catch屏蔽中,您有keyboard.nextInt();,这会引发新的未处理的InputMismatchException

catch (InputMismatchException e) 
 {
   System.out.print("You must enter a number from 1 to 4!");
   // You can remove this line, since it will be called anyways in the next loop iteration
   //keyboard.nextInt();

   // You can artificially set menuChoice = 1; for example for the loop to continue
 }