我的for
循环遇到了问题。
我的目标是
使用我当前的代码,我得到了这个输出:
Enter integer:
a
invalid input
Enter integer:
invalid input
Enter integer:
invalid input
Enter integer:
invalid input
Enter integer:
invalid input
Enter integer:
invalid input
BUILD SUCCESSFUL (total time: 3 seconds)
我能够检查整数的用户输入。但是,我的for
循环似乎无法正常工作。我可以请求协助吗?
以下是我的代码:
String a = "";
int count;
for (count = 0; count < 6; count++) {
System.out.println("Enter integer: ");
if (keyboard.hasNextInt()) {
System.out.println(a + "is correct integer");
}
else {
System.out.println("invalid input");
}
}
答案 0 :(得分:4)
您不会使用任何用户输入,a
如果您要阅读int
(s),则int
应为for (int count = 0; count < 6; count++) {
System.out.println("Enter integer: ");
if (keyboard.hasNextInt()) {
int a = keyboard.nextInt();
System.out.printf("%d is an integer%n", a);
} else {
System.out.println("invalid input " + keyboard.nextLine());
}
}
。我想你想要像
{{1}}
答案 1 :(得分:2)
试试这个:
它会消耗错误的一行并再次消耗你。
String a = "";
int count;
Scanner keyboard = new Scanner(System.in);
for (count = 0; count < 6; count++) {
System.out.println("Enter integer: ");
if (keyboard.hasNextInt()) {
a = String.valueOf(keyboard.nextInt());
System.out.println(a + "is correct integer");
} else {
System.out.println("invalid input");
keyboard.nextLine();
}
}
答案 2 :(得分:2)
您必须使用键盘输入,否则它将在后续循环迭代中保留。
if(keyboard.hasNextInt())
{
// consume the input by calling nextInt()
System.out.println(keyboard.nextInt() + " is correct integer");
}
else
{
// consume the input by calling next()
System.out.println("invalid input " + keyboard.next());
}
答案 3 :(得分:1)
您的代码需要进行以下更改:
使用输入值分配字符串a:
if (keyboard.hasNextInt()) {
a = keyboard.next();
System.out.println(a + "is correct integer");
} else {
a = keyboard.next();
System.out.println("invalid input");
}
正确初始化键盘变量:
Scanner keyboard = new Scanner(System.in);
这个问题可能会有所帮助 Java: using hasNextInt with do-while loop, it ignores integer inputs at even times
答案 4 :(得分:0)
for (int i = 0; i < 6; i++){
Scanner input = new Scanner(System.in);
System.out.println("Enter integer:");
char value = input.nextLine().charAt(0);
if(Character.isDigit(value)){
System.out.println(value + " is correct integer");
}else{
System.out.println(value + " invalid input");
}
}
答案 5 :(得分:-3)
**
**
Scanner s = new Scanner(System.in);
int i;
String a = "";
int count;
for (count = 0; count<6; count++)
{
System.out.println("Enter integer: ");
if(s.hasNextInt())
{
System.out.println(a + "is correct integer");
}
else
{
System.out.println("invalid input");
}
}