Java扫描器:我必须三次输入相同的值

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

Java Scanner: I have to entry thrice the same value

问题

if I replace typedNum in if with x
```((typedNum.nextInt() > 21 && typedNum.nextInt() < 30))```, then it works perfectly. Why is that so?

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 ((x > 21 && x < 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);

}
}


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

if I replace typedNum in if with x
```((typedNum.nextInt() &gt; 21 &amp;&amp; typedNum.nextInt()&lt; 30))```, then it works perfectly. Why is that so?

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);

}
}


</details>


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

每次调用 `nextInt()` 时,扫描器将会读入一个新的数字。如果你执行 `nextInt() > 21 && nextInt() < 30`,它会读取一个数字,将其与 21 进行比较,如果小于 21,则不会评估与运算符的第二部分。这被称为 "短路评估"。如果大于 21,则会评估与运算符的第二部分,并且会再读取另一个值。你应该在每次比较时都使用变量 `x`。

```java
      x = typedNum.nextInt();
      if ((x > 21 && x < 30)) {
        System.out.println("在范围内");
        i=1;
      } 
英文:

Each time you call nextInt(), scanner will read in a new number. If you do nextInt() &gt; 21 &amp;&amp; nextInt() &lt; 30, it will read one number, compare it to 21, and if it is less, it will not evaluate the second half of the and. This is called "short-circuit evaluation". If it is more, the second half of the and will be evaluated, and another value will be read. You should instead be comparing x each time.

      x = typedNum.nextInt();
      if ((x &gt; 21 &amp;&amp; x &lt; 30)) {
        System.out.println(&quot;in range&quot;);
        i=1;
      } 

答案2

得分: 0

每次调用typedNum.nextInt()都会从STDIN获取一个单独的输入。当你在函数调用的位置使用x时,它会正常工作,因为你只需要获取一次输入,然后稍后多次使用它。

英文:

Every instance of a call to typedNum.nextInt() takes a separate input from STDIN. It works perfectly when you use x in the place of the function call because you need to take the input only once and use it multiple times later.

huangapple
  • 本文由 发表于 2020年4月11日 01:31:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/61145531.html
匿名

发表评论

匿名网友

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

确定