问题:编写一个读取实数列表的程序。程序结束后,它应该只打印出唯一的数字。也就是说,仅在列表中出现一次的数字。如果列表中的唯一号码超过 50 个,则您应该只打印前 50 个。
import java.util.*;
import java.io.*;
import java.util.Arrays;
public class Hmwk {
public static void main(String[] args) throws FileNotFoundException {
Scanner input=new Scanner (new File ("input.txt"));
int n = 0;
final int MAX_SIZE = 50;
double[] numbersArray = new double[MAX_SIZE];
while (input.hasNextDouble() && n<MAX_SIZE){
double in = input.nextDouble();
if (inList(in,numbersArray))
numbersArray[n]=in;
n++;
}
printReport(numbersArray);
}
public static boolean inList(double number, double[] list){
for (double i : list)
{
if (i == number){
return false;
}
}
return true;
}
public static void printReport(double[] list)
{
System.out.println("The unique numbers were");
System.out.println(Arrays.toString(list));
}
}
输入.txt文件=
5.0 6.0 7.0 8.9 3.0 2.0 8.9 8.9 9.0 7.0 6.0 5.0 4.0 3.0 2.0 1.0
结果- 唯一的数字是 [5.0、6.0、7.0、8.9、3.0、2.0、0.0、0.0、9.0、0.0、0.0、0.0、4.0、0.0、0.0、1.0、0.0、0.0、0.0、0.0、0.0、0.0、0.0、0.0、0 .0 , 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ]
不知道我哪里出错了,我认为这是我的 inlist 方法?非常感谢任何和所有的帮助。谢谢!
最佳答案
为 IF
条件添加括号
if (inList(in,numbersArray))
{
numbersArray[n]=in;
n++;
}
关于java - 第一个Java程序: Random data in my Array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21562192/