【发布时间】:2015-07-04 06:21:16
【问题描述】:
我正在尝试遍历我的数组并找到所有重复多次的数字:
例如:如果有1 1 2 3 4
它应该打印出“1重复不止一次”
这是我的代码,到目前为止我已经尝试过,但是它会打印所有重复项并继续运行,如果有 4 4 4 4 3 6 5 6 9,它将打印所有 4,但我不希望这样:
class average {
public static void main(String[] args) throws IOException {
int numOfLines = 0;
int sum = 0, mean = 0, median = 0, lq = 0, uq = 0;
int[] buffer;
File myFile = new File("num.txt");
Scanner Scan = new Scanner(myFile);
while(Scan.hasNextLine()) {
Scan.nextLine();
numOfLines++;
}
Scan.close();
Scan = new Scanner(myFile);
System.out.println("Number Of Lines: " + numOfLines);
buffer = new int[numOfLines];
for(int i=0; i<numOfLines; i++) {
buffer[i] = Scan.nextInt();
}
Scan.close();
Scan = new Scanner(myFile);
for(int i=0; i<buffer.length; i++) {
sum = sum+i;
mean = sum/numOfLines;
}
System.out.println("Sum: " + sum);
System.out.println("Mean: " + mean);
for(int i=0; i<buffer.length; i++) {
for(int k=i+1; k<buffer.length; k++) {
if(buffer[k] == buffer[i]) {
System.out.println(buffer[k]);
}
}
}
【问题讨论】:
-
你可以对数组进行排序吗?
-
我正在尝试不排序 @Makoto
-
你能用
Set吗? -
这很公平。在这种情况下,您是否知道您在读入它们后所拥有的值的范围?也就是说,你知道最小值和最大值吗?在这种情况下,这可以为您提供帮助。
-
@Kon - 没有集合,只是简单的数组
标签: java arrays file for-loop duplicates