[英]How am i going to use while loop and if else if user enter the same input twice and it will try again
我想在java中應用這個函數。 在while循環中,您需要輸入要輸入數字的重復次數。 如果您輸入的數字等於您之前輸入的數字,它將重復循環並再次輸入數字。 這段代碼還沒有完成。 我希望你明白我想要達到的目標。 謝謝你
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");
}
}
}
}
讓我們使用一個臨時變量來存儲先前輸入的值。 如果新輸入與先前輸入相同,則迭代器 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;
}
}
該解決方案的問題是僅檢查在當前數字之前剛剛輸入的數字。 我知道您想檢查用戶輸入的號碼是否唯一,並且必須對照他/她之前輸入的每個號碼進行檢查。
請參閱代碼:
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.