阵列输出循环

时间:2019-09-05 01:18:46

标签: java loops multidimensional-array

我正在完成一个程序,该程序显示文件中给出的数组,然后为您提供某些行的总数,平均值以及特定总数。我遇到的问题是,一旦终止,数组突然开始循环。

我正在Eclipse IDE中工作

    String fileName = "";
    if (args.length == 0) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the file name :");
        fileName = sc.nextLine();
    } else {

        fileName = args[0];
    }
    File file = new File("C:\\Users\\AlaynaC\\Desktop\\2darray.txt");

    try {
        Scanner fin = new Scanner(file);
        int size = fin.nextInt();
        int[][] arr = new int[size][size];
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                arr[i][j] = fin.nextInt();

                Scanner sc = new Scanner(file);

                // The first line of the file contains the number of rows in the array.
                int noOfRows = Integer.parseInt(sc.nextLine());

                // initialize all with -1
                int array[][] = new int[noOfRows][10];
                for (int o = 0; o < noOfRows; o++) {
                    for (int g = 0; g < array[o].length; g++) {
                        array[o][g] = -1;
                    }
                }
                int index = 0;
                while (sc.hasNextLine()) {
                    String line = sc.nextLine();
                    // Each record in the file corresponds to a row in the array.
                    String numbers[] = line.split(" ");
                    // Now feeding the data into the array.
                    for (int o = 0; o < numbers.length; o++) {
                        array[index][o] = Integer.parseInt(numbers[o]);
                    }
                    index++;
                }
                sc.close();
                // This allows the data to be printed to the console.
                System.out.println("~~Array~~");
                for (int o = 0; o < noOfRows; o++) {
                    for (int g = 0; g < array[o].length; g++) {
                        if (array[o][g] != -1)
                            System.out.print(array[o][g] + " ");
                    }
                    System.out.println();
                }
            }
        }

        System.out.println("Total: " + getTotal(arr));
        System.out.println("Average: " + getAverage(arr));
        System.out.println("Row Total: " + getRowTotal(arr, 3));
        System.out.println("Column Total: " + getColumnTotal(arr, 2));
        System.out.println("Highest in Row:" + highestInRow(arr, 2));
        System.out.println("Lowest in Row:" + lowestInRow(arr, 2));

    } catch (FileNotFoundException e) {
        System.out.println(file.getAbsolutePath() + " is not found!");
    }
}

我需要数组仅显示一次。到目前为止,一旦输入文件,它就会显示多次。

0 个答案:

没有答案
相关问题