Im trying to average the user input by a string of numbers, It prints out without a problem but the output is very wrong

Enter some numbers:
0,4,3,5
48.0





import java.util.Scanner;

public class avg {

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

         double ress = 0; 
         double add=0;

          for (int i = 0; i < nums.length(); i++)
          {
              char x = nums.charAt(i);
              add=add+x;
              if (x == ',') continue;

          }
        ress=(double)(add/nums.length());
         System.out.println(ress);

   }
}
Member Avatar for iamthwee

What is the value of nums.length()?

How many values were inputted I believe

Incorrect. nums.length() gives the number of characters inputted namely: 0 3 4 5 3xcomma; 7 characters in all. You might wanna use the string's Split method to get rid of the commas. Additionally, when you're adding a char to a number type, you're essentially adding the character's ascii value. Look here for ascii values of different characters.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.