Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

import java.util.Scanner; public class test{ public static void main(String[] ar

ID: 3549710 • Letter: I

Question

import java.util.Scanner;
                    
                    
                    
                    public class test{
                    public static void main(String[] args){
                    System.out.println("Enter some numbers");
                    Scanner in=new Scanner(System.in);
                    String numbers2=in.nextLine();
                    
                    double result = 0;
                    double add=0;
                    int count=0;
                    for (int i = 0; i < numbers2.length(); i++)
                    {
                    String x = numbers2.substring(i,i+1);
                    if (x.equals(","))
                    {
                    continue;
                    }
                    
                    double y = (double)Integer.parseInt(x);

//double y = Double.parseDouble(x);
                    count++;
                    add=add+y;
                    
                    }
                    result=(double)(add/count);
                    
                    System.out.println("The average is: "+result);
                    }
                    
                    }                                  

                    This code works so long as the user inputs integers but I need to input real numbers for ex:) 1.0,2.0,3.0

Also the code in the comments doesnt work either

                

                    I get the following error:                 

                                     Exception in thread "main" java.lang.NumberFormatException: For input string: "."
                    at java.lang.NumberFormatException.forInputString(Unknown Source)
                    at java.lang.Integer.parseInt(Unknown Source)
                    at java.lang.Integer.parseInt(Unknown Source)
                    at test.main(test.java:23)

Explanation / Answer

This is not the way to read decimal values from keyboard


In your for loop you are taking substring of which length is 1

but for example "1.0" the length is 3, so here is the problem


And the Exception is due to it is unable parse if we give double value because we are calling Integer.parseInt() method.


public class test{
public static void main(String[] args){
System.out.println("Enter some numbers");
Scanner in=new Scanner(System.in);
String numbers2=in.nextLine();

double result = 0;
double add=0;
int count=0;


// you enter the double values line by line.. and to stop entering enter "q"

while(!numbers2.equals("q")){

double y = Double.parseDouble(numbers2);
count++;
add=add+y;

numbers2 = in.nextLine();

}

result= add/count;

System.out.println("The average is: "+result);

}
}



Ask if you have any doubts :)