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