英文:
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() > 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 ((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() > 21 && nextInt() < 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 > 21 && x < 30)) {
System.out.println("in range");
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论