数组和重复输出的问题

时间:2014-04-10 01:01:04

标签: java arrays

我遇到的问题是处理读取文件并将它们放入数组中。 然后将数组减去等于0

这是我到目前为止所得到的:

        Scanner infile2 = new Scanner(new File(fname));
        int [] nums = new int [n];
            for (int i = 0; i<n; i++)
            {
            nums[i] = infile2.nextInt();
            }
                for (int j = 0; j<n-1;j++){
                    for (int k = j+1; k<n;k++){
                        if (nums[j]+nums[k]==0){
                            int val = nums[j]+nums[k];

                        }
                    }
                }
                    }


}

有什么建议吗?

1 个答案:

答案 0 :(得分:5)

尝试这样做

Scanner infile2 = new Scanner(new File(fname));
int [] nums = new int [n];
for (int i = 0; i<n; i++){
    nums[i] = infile2.nextInt();
}

for (int j = 0; j<n;j++){
    for (int k = j+1; k<n;k++){
        if (nums[j]+nums[k]==0){
            int val = nums[j]+nums[k];
            System.out.println("num["+j+"]"+ " + " +"num["+k+"]"+" = " + nums[j] + " + " + nums[k] + " = " + val);
         }
    }
}

取出嵌套循环,然后它应解决重复计数问题

这是我试过的:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try{
        String fname = "PathToFile/a.txt";
        int n = 0;
        Scanner infile = new Scanner(new File(fname));
        while (infile.hasNextInt()){
        n++;
        infile.nextInt();
        }
        Scanner infile2 = new Scanner(new File(fname));
        int [] nums = new int [n];
        for (int i = 0; i<n; i++)
        {
            nums[i] = infile2.nextInt();
        }
        for (int j = 0; j<n-1;j++){
            for (int k = j+1; k<n;k++){
                if (nums[j]+nums[k]==0){
                    int val = nums[j]+nums[k];
                    System.out.println("num["+j+"]"+ " + " +"num["+k+"]"+" = " + nums[j] + " + " + nums[k] + " = " + val);
                }
            }
        }
    }catch(Exception e){
        System.out.println(e);

    }
}

我得到的结果

num[1] + num[4] = -40 + 40 = 0
num[1] + num[7] = -40 + 40 = 0
num[3] + num[6] = -10 + 10 = 0