[英]How am i going to use while loop and if else if user enter the same input twice and it will try again
I want to apply this function in java.我想在java中应用这个函数。 Inside while loop, you need to input number of repetition you want to input a number.
在while循环中,您需要输入要输入数字的重复次数。 if you input a number that equals to the number that you enter previously, it will repeat a loop and enter a number again.
如果您输入的数字等于您之前输入的数字,它将重复循环并再次输入数字。 This code is not finish yet.
这段代码还没有完成。 I hope u understand what i want to achive.
我希望你明白我想要达到的目标。 thank you
谢谢你
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == input){
System.out.println("It is already taken");
}
}
}
} }
Let's use a temp variable to store the value of previous input.让我们使用一个临时变量来存储先前输入的值。 If new input is same as previous input, the iterator i should not increase, so we use i--
如果新输入与先前输入相同,则迭代器 i 不应增加,因此我们使用 i--
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
int temp=0;
int inputArray[] = new int[times];
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == temp){
System.out.println("It is already taken");
i--;
}else {
inputArray[i-2]=input;
}
temp=input;
}
}
The thing with that solution is that is only checks for the number just entered before the current one.该解决方案的问题是仅检查在当前数字之前刚刚输入的数字。 I understood that you want to check that the number the user entered is unique and it has to be checked against every number that he/she has entered before.
我知道您想检查用户输入的号码是否唯一,并且必须对照他/她之前输入的每个号码进行检查。
See the code for that:请参阅代码:
import java.util.Scanner;
import java.util.ArrayList;
public class testMe{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of times: ");
int times = scanner.nextInt();
int i = 0;
ArrayList<Integer> listWithEntries = new ArrayList<Integer>();
while (i < times){
System.out.print("Enter a number : ");
int input = scanner.nextInt();
if(listWithEntries.size() == 0){
listWithEntries.add(input);
i++;
} else {
for(int j = 0; j < listWithEntries.size(); j++){
if(input == listWithEntries.get(j)){
System.out.println("It is already taken!");
break;
}
if(j == listWithEntries.size()-1 && input !=
listWithEntries.get(j)){
listWithEntries.add(input);
i++;
break;
}
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.