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

Heres my code: [code] import java.util.Scanner; public class test { public stati

ID: 3549690 • Letter: H

Question

Heres my code:

[code]

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;
         
          for (int i = 0; i < numbers2.length(); i++)
          {
              char x = numbers2.charAt(i);
              add=add+x;
              if (x == ',') continue;
         
          }
        result=(double)(add/numbers2.length());
         System.out.println("The average is: "+result);
         
   }
}

[/code]

It runs but it computes the wrong average please help me

If i add numbers 0,4,3,5

Average is 48.0

Explanation / Answer

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;} int y = Integer.parseInt(x); count++; add=add+y;
} result=(double)(add/count); System.out.println("The average is: "+result+" "+ add); } }

The thng is you were first of all adding x to add which means the ASCII value of the character was added. So what I have done here took a substring out of numbers2 with length =1 by using the function
String x = numbers2.substring(i,i+1);
Then i found whether it is equal to the string ","
if not then I parsed it into an intger and added it after that I incremented count which is a variable that counts the number of numbers present.
Hope this is helpful to you :)