Do not store text data in java array using scanner

My code simply prints the last number from the list that I create in another program. I need help storing data in an array, so I can sort it after. edit: I need to take data from a file that is "number.txt" and store it in 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); } } 
+1
source share
1 answer

Correction in the code.

1.) Inside the loop while list[0] = numberArray; will continue to add elements to the same index 0 , so the lat value will be overridden. 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); } } 
0
source

Source: https://habr.com/ru/post/1238700/


All Articles