所以我在我的java作業中遇到了一個問題。其任務是編寫一個讀取十個數字的程序,並只顯示不同的數字以及不同的數值。我已經得到了迄今...讀取並存儲數組中的唯一值(JAVA)
import java.util.Scanner;
import java.util.Collection;
public class Exercise06_05 {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int[] list = new int[10];//create my new 10 slot array
//i really want a variable length array but alas
for (int i = 0; i < 10; i++){//get and check the ten input variables
System.out.println("Enter an Integer");//ask for input
int integer = input.nextInt();//assign the input to a temp variable
if (isUnique(list, integer)){//check if the temp is unique to the array
list[i] = integer;//if so assign it
}
}
String output = "";
int j = 0;
for (j = 0; j < list.length; j++){
if(list[j] != 0){//this is where the error accours
output += (list[j] + " ");
}else
break;//this break ensures J doesn't get any higher
//so that i can plug that in for the number of distinct variables
}
System.out.println("The number of distinct numbers is " + j);
System.out.println(output);//print output, and the number of distinct values
}
public static boolean isUnique(int [] arry, int a){// my masterpiece of a method
for (int i = 0; i < (10);){
if (arry [i] == a){//check box
return false;//not unique
} else if (i == (arry.length - 1)){//we done yet?
return true;//if so, return that it's unique
}else//if we're not done increment the box
i++;//there that is
} return false;//now put this here just to safeguard
}
}
它工作正常,除非用戶再次輸入兩個像1行相同的整數,然後1。發生什麼事是程序不存儲第二個int,該數組保持爲零,然後在創建輸出部分失敗。我如何解決這個問題?
如果您的要求顯示不同的數字,爲什麼還需要顯示唯一數字的數量?這似乎很奇怪,也許是對這個問題的誤解?另外,請看一下sets(http://download.oracle.com/javase/1.5.0/docs/api/index.html?java/util/Set.html),它們基本上是獨特的東西...... – 2011-04-27 17:38:10