【发布时间】:2014-10-31 17:01:25
【问题描述】:
有一个程序,用户将 10 个 int 值输入到数组中。最后,我需要提取不同的值并显示它们。添加了我的第二个 for 循环,它将确定值是否不同(即,如果数字出现多次,则它只显示一次)。
例如,假设我传入数字:1、2、3、2、1、6、3、4、5、2 不同的数组应该只包含数字 {1、2、3、6、4 , 5}
import java.util.Scanner;
import java.io.*;
public class ArrayDistinct {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
// Create arrays & variables
int arrayLength = 10;
int[] numbers = new int[arrayLength];
int[] distinctArray = new int[arrayLength];
int count = 0;
System.out.println("Program starting...");
System.out.print("Please enter in " + numbers.length + " numbers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
}
for (int i = 0; i < numbers.length; i++) {
int temp = numbers[i];
int tempTwo = numbers[i + 1];
if (tempTwo == temp) {
count++;
distinctArray[i] = temp;
}
}
// Print out results
} // end main
} // end class
【问题讨论】:
-
什么是“不同的”值?我想你是在假设我们有一些先验知识。请更好地解释您的问题。
-
考虑使用只允许唯一值的集合...
-
@brso05 我猜这是作业;他还没有去Sets。