简体   繁体   中英

need help in java/ file IO

I don't know what it is wrong with my code it doesn't display the list to the user as 10 lines of 10 values?

Write a second program that reads in those 100 numbers from 'values.txt' and places them into an ArrayList.

here is the code:

class Program2 {
    public static void main(String args[]) throws Exception {

        ArrayList<Integer> list = new ArrayList<Integer>();

        int i = 0;
        try {
            Scanner read = new Scanner(new File("values.txt"));
            do {
                String line = read.nextLine();
                list.add(Integer.parseInt(line));
            } while (read.hasNext());
        } catch (FileNotFoundException fnf) {
            System.out.println("file was not found");
        }

        bubbleSort(list);
        for (int s : list) {
            i++;
            if (i == 10) {
                System.out.println();
                i = 0;
            }
            System.out.print(s + " ");
        }
    }

//sorting the values

    public static void bubbleSort(ArrayList<Integer> list) {
        boolean swapped = false;
        do {
            swapped = false;
            for (int i = 0; i < list.size() - 1; i++) {
                if (list.get(i) > list.get(i + 1)) {
                    int swap = list.get(i);
                    list.set(i, list.get(i + 1));
                    list.set(i + 1, swap);
                    swapped = true;
                }
            }
        } while (swapped);

    }
}

You have an error at the iteration, you are printing 9 values per line, not 10. It should be:

for (int s : list) {
    if (i == 10) {
        System.out.println();
        i = 0;
    }
    i++;
    System.out.print(s + " ");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM