gpt4 book ai didi

java - 循环执行3次

转载 作者:行者123 更新时间:2023-12-02 03:45:46 25 4
gpt4 key购买 nike

我正在做一个学校练习,要求我修改 .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 开始的计数器,当它达到 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);
}

另外注意:即使用户输入错误3次,你仍然会打印“Data Correct...”。在 while 循环之后你可以做这样的事情:

if(counter < 3) {
System.out.println("Data correct. You typed " + valorUsari);
} else {
System.out.println("Too many tries. You are bad.");
}

关于java - 循环执行3次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36321626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com