0

想知道是否有人可以告诉我为什么我的 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 的数字!在 java.util 的线程“main”
java.util.InputMismatchException中出现异常
。 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)

4

1 回答 1

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
 }
于 2013-02-12T00:28:22.017 回答