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 までの数字を入力する必要があり
ます
。 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 に答える