【问题标题】:Java Scanner: I have to entry thrice the same valueJava Scanner:我必须输入三次相同的值
【发布时间】:2020-04-11 03:27:13
【问题描述】:

如果我将 if 中的 typedNum 替换为 x ((typedNum.nextInt() > 21 && typedNum.nextInt()< 30)),那么它可以完美运行。为什么会这样?

import java.util.Scanner;

public class Main {
  public static int number(Scanner typedNum) {
    int x = 0;
    int i = 0;
    while (i < 1) {
      x = typedNum.nextInt();
      if ((typedNum.nextInt() > 21 && typedNum.nextInt()< 30)) {
        System.out.println("in range");
        i=1;
      } 
     else {
        System.out.println("Not in range");
      }

    }
    System.out.println(x);
    return (x);
  }

  public static void main(String[] args) {
    Scanner y = new Scanner(System.in);
    number(y);

  }
}

【问题讨论】:

    标签: java


    【解决方案1】:

    调用typedNum.nextInt() 的每个实例都从STDIN 获取单独的输入。当您使用 x 代替函数调用时,它可以完美运行,因为您只需输入一次并在以后多次使用它。

    【讨论】:

      【解决方案2】:

      每次拨打nextInt(),扫描仪都会读取一个新号码。如果你做nextInt() &gt; 21 &amp;&amp; nextInt() &lt; 30,它会读取一个数,与21比较,如果小于,它不会计算and的后半部分。这称为“短路评估”。如果大于,将评估 and 的后半部分,并读取另一个值。相反,您应该每次都比较 x

            x = typedNum.nextInt();
            if ((x > 21 && x < 30)) {
              System.out.println("in range");
              i=1;
            } 
      

      【讨论】:

        猜你喜欢
        • 2022-07-06
        • 1970-01-01
        • 1970-01-01
        • 2018-10-20
        • 1970-01-01
        • 2022-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多