我要輸入 10 到 100 之間的 5 個數字。在讀取每個數字時,程式必須僅在它不是已讀取數字的重復項時才顯示它。我必須提供所有五個數字都不同的“最壞情況”。我使用盡可能小的陣列來解決這個問題,并在用戶輸入每個新值后顯示輸入的完整唯一值集。
我遇到的問題是我不知道如何使數字介于 10 和 100 之間。這是我目前所擁有的。謝謝!
匯入 java.util.Scanner; 匯入 java.util.Arrays;
公共類 IsDuplicate {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int array[] = new int [5];
int size = 0;
int x;
for (int i = 0; i < 5; i ) {
System.out.print("Enter an integer between 10 and 100: ");
x = input.nextInt();
if(size == 0 || newNumber(array, size, x)) {
System.out.println("This is the first time " x " has been entered.");
array[size] = x;
size ;
}
}
System.out.println("The complete set of unique values entered is: ");
for (int i = 0; i<size; i ) {
System.out.println("Unique value" (i 1) ": is " array[i]);
}
}
private static boolean newNumber(int y[], int size, int x) {
for (int i = 0; i <size; i ) {
if (y[i] == x) {
return false;
}
}
return true;
}
}
uj5u.com熱心網友回復:
你可以很容易地實作這一點。您所要做的就是調整您的 for 回圈以獲取輸入,并檢查 x 的值以查看它是否為!(x < 10) && !(x > 100)。
如果您的程式應該在輸入了不可接受的值時要求另一個數字,那么您還需要從中減去 1i以確保您仍然得到總共 5 個數字。
if(size == 0 || newNumber(array, size, x) ) {
if(!(x < 10) && !(x > 100))
{
System.out.println("This is the first time " x " has been entered.");
array[size] = x;
size ;
}
else
{
System.out.println("The number you entered is outside the range of acceptable values.");
i = i - 1;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/368648.html
上一篇:如何使用回圈制作一排三角形?
