简体   繁体   中英

Error handling, throw exceptions, and user inputs

I'm trying to to get user inputs(eg. file names) and store them as arguments in another function. However, both println's are displayed simultaneously. This blocks me from entering the arguments properly. I think it has to do with throwing exceptions. However I cannot run the program if I don't add exceptions.

public class demon {
    static Scanner input = new Scanner(System.in);

public static void main(String [] args) throws Exception {
    MainMenu();
}//end main

public static void MainMenu() throws Exception {
    System.out.println("Welcome to Demon. Please select an option from below:");
    System.out.println("1: Encrypt a File");
    System.out.println("2: Decrypt a File");
    System.out.println("3: Exit");
    int userOption = input.nextInt();
    if (userOption == 1) {
        optionEncrypt();
    } else if (userOption == 2) {
        optionDecrypt();
    } else if (userOption == 3) {
        System.exit(0);
    }else {
        System.out.println("Invalid Entry");
        System.exit(0);
    }
}

public static void optionEncrypt() throws Exception {
    System.out.println("Enter the file name to encrypt:");
    String inputFileName = input.nextLine();
    System.out.println("Enter the file name to output:");
    String outputFileName = input.nextLine();
    createEncryptionFile("test.txt", "demon.txt");
}

Output:
1: Encrypt a File
2: Decrypt a File
3: Exit
1
Enter the file name to encrypt:
Enter the file name to output:

just change the nextLine() method to next() .

seems like the when you get the first integer via nextInt() method, there is still a new line that will be taken by the nextLine() function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM