Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/382.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:如何在一个程序中多次使用System.in?_Java_System.in - Fatal编程技术网

Java:如何在一个程序中多次使用System.in?

Java:如何在一个程序中多次使用System.in?,java,system.in,Java,System.in,在上一篇文章中,我学到了不应该关闭系统。在中,我还学到了同时使用多个扫描仪可能会导致问题。 问题是我需要一些递归的方法来使用扫描器来扫描来自用户的一些输入 示例 public void usersChoice(){ int choice = 0; while(true){ try{ Scanner scan = new Scanner(System.in); System.out.print("Choose an o

在上一篇文章中,我学到了不应该关闭
系统。在
中,我还学到了同时使用多个
扫描仪
可能会导致问题。 问题是我需要一些递归的方法来使用
扫描器
来扫描来自用户的一些输入

示例

public void usersChoice(){
    int choice = 0;
    while(true){
        try{
            Scanner scan = new Scanner(System.in);
            System.out.print("Choose an option: ");
            choice = scan.nextInt();
            break;
        }
        catch(Exception e){
            System.out.println("Invalid Input!\n");
            }
        }

    switch (choice){
        case 1:
            choiceNewAccount();
            break;
        case 2:
            choiceLogin();
            break;
        case 3:
            choiceRemoveAccount();
            break;
        case 4:
            exit();
            break;
        default:
            System.out.println("Invalid Input!\n");
            break;     
   }
案例1:

public void createAccount(){
    try{
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter Your Username: ");
        String username = scan.next();       
        if(!isValidUsername(username)) System.out.println("Username Already Exists!");
        else{
            while(true){
                System.out.print("Enter Your Password: ");
                String pass1 = scan.next();
                System.out.print("Re-Enter Your Passowrd: ");
                String pass2 = scan.next();
                if(!arePasswordsMatch(pass1,pass2)) System.out.println("Passowrds Don't Match!");
                else {
                    addToAccountsList(username,pass1);
                    createTheUsersFile(username);
                    System.out.println("The Account Has Been Successfully Created!");
                    break;
                }
            }
        }
        } catch(Exception e){
            System.out.println("Could Not Create Account!");
        }

我需要创建一个System.in对象并在整个程序中使用它吗?或者是否有其他方法处理System.in对象?

只需将扫描仪作为参数发送,然后从System.in硬编码中重新创建它,这是非常糟糕的做法amit说的。另外,您不需要“创建一个
系统。在
对象”中,您只需引用它。我已经编辑了标题,我不知道为什么要写上一个问题的标题@只发送扫描程序作为参数,从系统中重新创建它。在硬编码中,这是非常糟糕的做法amit所说的。另外,您不需要“创建一个
系统。在
对象”中,您只需引用它。我已经编辑了标题,我不知道为什么要写上一个问题的标题@汤姆