我正在尝试打印一个数组,但只打印出该数组中不同的数字。例如:如果数组有{5,5,3,6,3,5,2,1},那么它将打印{5,3,6,2,1}
每次我这样做时,要么只打印不重复的数字,在本例中为{6,2,1},要么全部打印。然后我没有按照作业建议的方式做
赋值要求我在将一个值放入数组之前检查数组,看看它是否在那里。如果不是,则添加它,但如果是,请不要添加。
现在,我只是不断得到超出边界的错误,或者它只是打印所有的东西。
我该怎么做有什么建议吗?
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
发布于 2018-09-16 07:39:40
如果顺序不重要,可以使用长度为10的help数组来实现。
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(i + " ");
}
}
https://stackoverflow.com/questions/52349636
复制相似问题