简体   繁体   中英

not storing text data into java array using scanner

My code is just printing out the last number from the list I create in a different program. I need help storing the data into an array so I can sort it after. edit: I need to take data from a file which is 'numbers.txt' and store it into an array.

public static void main(String[] args) throws Exception {
    int numberArray = 0;
    int[] list = new int[16];

    File numbers = new File("numbers.txt");
    try (Scanner getText = new Scanner(numbers)) {
        while (getText.hasNext()) {
            numberArray = getText.nextInt();
            list[0] = numberArray;
        }
        getText.close();
    }
    System.out.println(numberArray);
    int sum = 0;
    for (int i = 0; i < list.length; i++) {
        sum = sum + list[i];
    }
    System.out.println(list);
}
}

Correction in the code.

1.) Inside while loop, list[0] = numberArray; , will keep adding elements on the same index 0 , so lat value will override. SO something like list[i] = numberArray; will work, and increement i inside while loop . Take care of ArrayIndexOutOfBound Exception here.

public static void main(String[] args) throws Exception {
    int numberArray = 0;
    int[] list = new int[16];

    File numbers = new File("numbers.txt");
    int i =0;

// Check for arrayIndexOutofBound Exception. SInce size is defined as 16

    try (Scanner getText = new Scanner(numbers)) {
        while (getText.hasNext()) {
            numberArray = getText.nextInt();
            list[i] = numberArray;
             i++;
        }
        getText.close();
    }
    System.out.println(numberArray);
    int sum = 0;
    for (int i = 0; i < list.length; i++) {
        sum = sum + list[i];
    }
    System.out.println(list);
}
}

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