java - calculate average with user input -


i'm writing program calculate average user input.

import java.util.scanner; public class mean {        static scanner input = new scanner (system.in);     public static void main (string[] args)     {     double i;     double sum = 0;     int count = 0;         {         system.out.println("input");         = input.nextdouble();         sum = sum + i;         count++;     }while (i != 0);     system.out.println("sum " + sum + " count " + (count - 1));     system.out.println("average " + sum / (count - 1)); } } 

here if input 0, calculate. if there 0s in list. can guide me great while condition?

you ask scanner whether or not next token scanner reading double , break if isn't. example below:

import java.util.scanner; public class mean {        static scanner input = new scanner (system.in);     public static void main (string[] args)     {     double i;     double sum = 0;     int count = 0;     while(input.hasnextdouble())     {         system.out.println("input");         = input.nextdouble();         sum = sum + i;         count++;     }     system.out.println("sum " + sum + " count " + (count));     system.out.println("average " + sum / (count)); } } 

if user inputs non-digit character (e.g. not '+', '-', 0-9, '.', etc.), loop break because input.hasnextdouble() return false.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -