0
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);

   }
}

Edited by custurd12

3
Contributors
3
Replies
20
Views
3 Years
Discussion Span
Last Post by scudzilla
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.