Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 错误处理、抛出异常和用户输入_Java_Exception Handling_User Input_Throw_Println - Fatal编程技术网

Java 错误处理、抛出异常和用户输入

Java 错误处理、抛出异常和用户输入,java,exception-handling,user-input,throw,println,Java,Exception Handling,User Input,Throw,Println,我试图获取用户输入(例如文件名),并将它们作为参数存储在另一个函数中。但是,两个println同时显示。这会妨碍我正确输入参数。我认为这与抛出异常有关。但是,如果不添加异常,则无法运行该程序 public class demon { static Scanner input = new Scanner(System.in); public static void main(String [] args) throws Exception { MainMenu(); }//end

我试图获取用户输入(例如文件名),并将它们作为参数存储在另一个函数中。但是,两个println同时显示。这会妨碍我正确输入参数。我认为这与抛出异常有关。但是,如果不添加异常,则无法运行该程序

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:

只需将
nextLine()
方法更改为
next()


当你通过
nextLine()
方法得到第一个整数时,仍然有一行新的整数将被
nextLine()
函数使用,请包括你创建
扫描仪的代码,当然,刚刚做了。非常感谢!我在为这事发愁。我在我的课本上读到了这一点,然后就忘了。它回来咬了我一口:'(