By using Java 11, I am trying to find the average value inside the ArrayList. The algorithm i want to develop is ((value inside list/maximum value)*100)/length of list). I got number format runtime error while I run the program. java.lang.NumberFormatException is the error i got.
JavaScript
x
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine()," ");
double[] grades = new double[N];
for(int i = 0; i < N; i++){
grades[i] = Integer.parseInt(st.nextToken());
}
double sum = 0;
Arrays.sort(grades);
for(int i = 0; i < grades.length; i++){
sum += (grades[i]/grades[grades.length-1])*100;
}
System.out.println(sum/grades.length);
}
}
Advertisement
Answer
I find two issues with the code above:
The parsing of
br.readLine()
toint
is the line which throwsNumberFormatException
, sincebr.readLine()
contains both numbers and spaces (at least). Since the line is NOT a valid number, the parsing fails.Example:
- User enters the following when
br.readLine()
is executed: “1 2 3 4” - The next instruction looks like:
int N = Integer.parseInt("1 2 3 4")
- The correct number should not contain spaces: “1234”
- User enters the following when
This one is not really a bug, however, you’re asking the user to input the numbers again on the second appearance of
br.readLine
here:new StringTokenizer(br.readLine()," ");
Solution
JavaScript
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// REMOVE NEXT LINE
// int N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine()," ");
// Read the number of tokens in the string
// The input "1 2 3 4" on the example above should return 4 tokens
int N = st.countTokens();
double[] grades = new double[N];