麻烦设置一个参数。

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

Trouble setting a Parameter

问题

我对如何只允许输入1至4的数字感到困惑。我不确定是否有一个术语来描述这个,我认为这是一个参数。

我要询问的代码是倒数第三行

private void validatePositiveNumber() {
    Scanner scanner = new Scanner(System.in);

    int number;
    do {
        System.out.print("Please enter a positive number: ");
        while (!scanner.hasNextInt()) {
            String input = scanner.next();
            System.out.printf("\"%s\" is not a valid number.\n", input);
        }
        number = scanner.nextInt();
    } while (number < 4);

    System.out.printf("You have entered a positive number %d.\n", number);
}
英文:

Im confused as to how I allow only numbers 1-4? Im not sure if there is a term for this, i think its parameter

THE CODE IM QUESTIONING IS THE 3RD TO LAST LINE

private void validatePositiveNumber() {
    Scanner scanner = new Scanner(System.in);

    int number;
    do {
        System.out.print(&quot;Please enter a positive number: &quot;);
        while (!scanner.hasNextInt()) {
            String input = scanner.next();
            System.out.printf(&quot;\&quot;%s\&quot; is not a valid number.\n&quot;, input);
        }
        number = scanner.nextInt();
    } while (number &lt; 4);

    System.out.printf(&quot;You have entered a positive number %d.\n&quot;, number);
}

答案1

得分: 1

Use while (number > 4 || number < 1); This disallows anything outside of the range.

英文:

Use while (number &gt; 4 || number &lt; 1); This disallows anything outside of the range.

答案2

得分: 0

Scanner scanner = new Scanner(System.in);

int number;
do {
    System.out.print("请输入一个正数:");
    while (!scanner.hasNextInt()) {
        String input = scanner.next();
        System.out.printf("\"%s\" 不是一个有效的数字。\n", input);
    }
    number = scanner.nextInt();
} while (number > 4 || number < 1);

System.out.printf("您输入了一个正数 %d。\n", number);
英文:
Scanner scanner = new Scanner(System.in);

        int number;
        do {
            System.out.print(&quot;Please enter a positive number: &quot;);
            while (!scanner.hasNextInt()) {
                String input = scanner.next();
                System.out.printf(&quot;\&quot;%s\&quot; is not a valid number.\n&quot;, input);
            }
            number = scanner.nextInt();
        } while (number &gt; 4 || number &lt; 1);

        System.out.printf(&quot;You have entered a positive number %d.\n&quot;, number);

huangapple
  • 本文由 发表于 2020年9月25日 00:59:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64051073.html
  • java
  • validation

如何检查Class是否可转换为类。 go 83
匿名

发表评论

匿名网友

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

确定

  • 开发者交流平台

    本页二维码