lundi 7 décembre 2015

asking the user to input numbers and then counting them and finding the average

I need to write a code that takes the users input of numbers and adds them, displays the amount of positives, negatives, zeroes, and the count of the amount of numbers inputted once the user enters the letter 'e'.

When i enter 'e' though, the program terminates without printing the count or average.

Also, the average doesn't work because it says i cannot divide by zero.

    public static void main (String[] args){
        Scanner input = new Scanner(System.in);
        int negative = 0;
        int positive = 0;
        int zeroes = 0;
        int sum = 0;
        int count = 1;
        int average = sum / (count - 1);

         do{
                System.out.print("Enter a float or 'e' to exit");
                String entered = input.nextLine();
                if("e".equals(entered)){
                    //print stuff
                    break;
                }else{
                    int num;
                    try {
                        num = Integer.parseInt(entered);
                    } catch (NumberFormatException e) {
                        System.out.print(negative + positive + 
                    zeroes + sum + (count - 1) + average);
                        continue; // re-do the loop
                    }
                    if(num  < 0){ 
                        sum += num;
                        count++;
                        negative++;
                    }else if (num > 0){ 
                        sum += num;
                        count++;
                        positive++;
                    }else{//similar to comment above
                        sum += num;
                        count++;
                        zeroes++;
                    }

                }
            } while(true);   
    }
}

Aucun commentaire:

Enregistrer un commentaire