我正在进行学校练习,要求我修改.java
代码,以便要求用户输入正确的数字仅 3次。
我得到的代码就是:
public static void main (String[] args) {
Scanner lector = new Scanner(System.in);
int valorUsuari = 0;
boolean valorNOk=true;
while (valorNOk){
System.out.print("Insert a number between 0 and 5: ");
valorUsuari = lector.nextInt();
lector.nextLine();
if((valorUsuari >= 0)&&(valorUsuari <= 5)){
valorNOk=false;
}
}
System.out.println("Data correct. You typed " + valorUsuari);
}
}
我尝试在while条件之前执行此操作,但它似乎不起作用:
for (valorUsuari = 0; valorUsuari <= 3 ; valorUsuari++)
你知道我哪里出错吗?
提前谢谢!
答案 0 :(得分:2)
只需添加一个从0开始的计数器,当它达到3时,不再允许用户输入数字。每次用户写入非法内容时,请向计数器添加一个。
public static void main (String[] args) {
Scanner lector = new Scanner(System.in);
int valorUsuari = 0;
int counter = 0; //this is your counter, it starts at 0 because the user has failed 0 times at this point
boolean valorNOk=true;
while (valorNOk && counter < 3){
System.out.print("Insert a number between 0 and 5: ");
valorUsuari = lector.nextInt();
lector.nextLine();
if((valorUsuari >= 0)&&(valorUsuari <= 5)){
valorNOk=false;
} else {
counter++; //this is added to keep track of failed tries
}
}
System.out.println("Data correct. You typed " + valorUsuari);
}
注意:此时此问题与您无关,但您的valorNOk
非常多余。你可以简单地使用break
代替:
public static void main (String[] args) {
Scanner lector = new Scanner(System.in);
int valorUsuari = 0;
int counter = 0; //this is your counter, it starts at 0 because the user has failed 0 times at this point
while (counter < 3){
System.out.print("Insert a number between 0 and 5: ");
valorUsuari = lector.nextInt();
lector.nextLine();
if((valorUsuari >= 0)&&(valorUsuari <= 5)){
break;
} else {
counter++; //this is added to keep track of failed tries
}
}
System.out.println("Data correct. You typed " + valorUsuari);
}
另一个注意事项:即使用户错误地输入了三次,您仍然会打印"Data correct..."
。在你的while循环之后,你可以做的是这样的事情:
if(counter < 3) {
System.out.println("Data correct. You typed " + valorUsari);
} else {
System.out.println("Too many tries. You are bad.");
}
答案 1 :(得分:0)
稍微修改了一下,我使用了一个计数器int tries
来跟踪尝试。
public static void main(String[] args) throws Exception {
Scanner lector = new Scanner(System.in);
int valorUsuari = 0;
boolean valorNOk = true;
int tries = 0;
while (valorNOk && tries < 3) {
System.out.print("Insert a number between 0 and 5: ");
valorUsuari = lector.nextInt();
lector.nextLine();
if ((valorUsuari >= 0) && (valorUsuari <= 5)) {
valorNOk = false;
} else {
tries++;
}
System.out.println("Data correct. You typed " + valorUsuari);
}