为什么我必须先输入两个整数才能进行迭代? hasInt(), nextLine(), nextInt()
Why do I have to enter two integer at first to proceed to the iteration? hasInt(), nextLine(), nextInt()
当我尝试 运行 时,我必须输入 2 个整数并进入循环才能移动到下一次迭代,但第二次循环不会发生这种情况?
这是什么原因,解决这个问题的逻辑是什么?
import java.util.Scanner;
public class MinAndMaxInputChallenge {
public static void main(String[] args) {
int max = 0;
int min = 0;
int number;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter number ");
number = scanner.nextInt();
boolean hasInt = scanner.hasNextInt();
scanner.nextLine();
if (hasInt) {
if (number > max)
max = number;
else if (number < min)
min = number;
} else break;
}
System.out.println("Max = " + max + " Min = " + min);
scanner.close();
}
}
Code & Ouput
你的代码逻辑有点不对劲。首先检查 kb 的缓冲区中是否有 int。如果是,读入,消耗 eol,设置 min 或 max,然后跳出 while 循环
import java.util.Scanner;
public class MinAndMaxInputChallenge {
public static void main(String[] args) {
int max = 0;
int min = 0;
int number;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter number ");
boolean hasInt = scanner.hasNextInt();
if (hasInt) {
number = scanner.nextInt();
scanner.nextLine();
if (number > max)
max = number;
else if (number < min)
min = number;
break;
}
}
System.out.println("Max = " + max + " Min = " + min);
scanner.close();
}
}
当我尝试 运行 时,我必须输入 2 个整数并进入循环才能移动到下一次迭代,但第二次循环不会发生这种情况? 这是什么原因,解决这个问题的逻辑是什么?
import java.util.Scanner;
public class MinAndMaxInputChallenge {
public static void main(String[] args) {
int max = 0;
int min = 0;
int number;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter number ");
number = scanner.nextInt();
boolean hasInt = scanner.hasNextInt();
scanner.nextLine();
if (hasInt) {
if (number > max)
max = number;
else if (number < min)
min = number;
} else break;
}
System.out.println("Max = " + max + " Min = " + min);
scanner.close();
}
}
Code & Ouput
你的代码逻辑有点不对劲。首先检查 kb 的缓冲区中是否有 int。如果是,读入,消耗 eol,设置 min 或 max,然后跳出 while 循环
import java.util.Scanner;
public class MinAndMaxInputChallenge {
public static void main(String[] args) {
int max = 0;
int min = 0;
int number;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter number ");
boolean hasInt = scanner.hasNextInt();
if (hasInt) {
number = scanner.nextInt();
scanner.nextLine();
if (number > max)
max = number;
else if (number < min)
min = number;
break;
}
}
System.out.println("Max = " + max + " Min = " + min);
scanner.close();
}
}