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); } }
list[0]! Use thenumberArrayvariable. Increment it inside the loop and use it as the list array index.catchorfinallyblock after yourtryblock. Without it this code won't compileMy code is just printing out the last number from the listbecause you're printingnumberArraywhich contains the last read number. And you don't need to callgetText.close();. Thetry-with-resourcesstatement does that for you.