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: 3549704 • 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);
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

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

you are trying to convert from a string to an integer and then perform a static cast to a double.

you should use this:

double y = Double.parseDouble(x);   // will return a double or throw NumberFormatException

you could even wrap in a try / catch

try

{

   double y = Double.parseDouble(x);

}catch(NumberFormatException ex)

{

   System.out.println("You did not enter a double");

}