Results 1 to 2 of 2

Thread: output help

  1. #1

    Thread Starter
    New Member
    Join Date
    Dec 2010
    Posts
    1

    output help

    Hi my code does everything I want, I just need to add one thing if someone could please help. I need the program to calculate the average only when at least one number is entered and shows “goodbye” if no numbers are entered (the user enters a negative number for the first input). Right now it calculates the average but I need it to output "goodbye" if the first input is a negative number.


    Code:
    import java.util.Scanner;
    
    public class While {
    
      public static void main(String[] args) {   
        Scanner input = new Scanner(System.in); 
            
        int num; // 
        int numOfAmount = 0; 
        float totalAmout = 0;    float average;     
        System.out.println("Enter a score or a negative number to end the program: "); //prompt the user for an input
        num = input.nextInt();
        
        while(num >= 0)
        {
        numOfAmount++; //
        totalAmount = totalAmount + score; 
                
        System.out.println("Enter a number or a negative number to end the program: "); //
        num = input.nextInt();
        }
            
        average = totalAmount / numOfAmount; //calculate the average score
        System.out.println("The average score is " + average); 
      }

  2. #2
    PowerPoster kfcSmitty's Avatar
    Join Date
    May 2005
    Posts
    2,248

    Re: output help

    If the first value was a negative number then it would never enter your loop and thus 'totalAmout' would remain 0.

    Code:
    if(totalAmout == 0){
      System.out.println("Goodbye");
    }else{
          average = totalAmount / numOfAmount; //calculate the average score
        System.out.println("The average score is " + average); 
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width