简体   繁体   English

错误处理,引发异常和用户输入

[英]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. 但是,两个println同时显示。 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() . 只需将nextLine()方法更改为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 似乎当您通过nextInt()方法获得第一个整数时, nextLine()函数仍将使用新行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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