Java中的Scanner添加可选的用户输入提示

huangapple go评论87阅读模式
英文:

Java Scanner add optional user input prompts

问题

以下是你的代码的翻译部分:

public class MainApplication {

    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        
        System.out.println("以逗号分隔的格式输入ordertypes(必填):");
        String orderOrActionTypes = in.next();

        System.out.println("输入orderAttributes(可选):");
        String orderAttributes = in.next();

        System.out.println("输入ActionAttributes(可选):");
        String actionAttributes = in.next();
    }
}
英文:

What is the way to take some parameters as optional user input using java util Scanner? Below is my code. But, for all the parameters it's blocked till the user input is entered.

I want it to continue for second parameter in cases 'when the user input is entered and then pressed enter key' "OR" 'when just pressed enter key without entering any input'.

public class MainApplication {

    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        
        System.out.println("Enter ordertypes in comma separated format (mandatory): " );
        String orderOrActionTypes = in.next();

        System.out.println("Enter orderAttributes (optional): " );
        String orderAttributes = in.next();

        System.out.println("Enter ActionAttributes (optional): " );
        String actionAttributes = in.next();
    }
}

</details>


# 答案1
**得分**: 1

你仍然可以保留输入,但将其保留为空。
当需要输入时,用户可以按下`Enter`键(导致为空字符串),然后您可以测试用户是否输入了内容`orderAttributes.isEmpty()`,并根据结果执行相应操作。

<details>
<summary>英文:</summary>

You can still let the input but leave it empty.
When an input is required, the user can press `Enter` (which results on an empty string), and then you can test, whether the user typed something or not `orderAttributes.isEmpty()` and you do what you need based on the results.

</details>



# 答案2
**得分**: 0

尝试使用 `in.nextLine();`,这可能会有所帮助。

<details>
<summary>英文:</summary>

Try using `in.nextLine();`, it may help. 

</details>



huangapple
  • 本文由 发表于 2020年10月20日 21:10:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64445893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定