I'm trying to write a program that asks the user if they want to enter a real number. If yes, then prompt the user to enter a number. Keep prompting for number inputs until user says "no." Once this happens, output the average of the numbers entered.
I think I'm stuck trying to implement a string for the sentinel value. I want the sentinel value to be "no." But with this last attempt I have here, when I enter "yes" I get an InputMismatchException. Also, not sure if this is a job for do/while or just while. Kind of new to all this and not sure how to go about this, as we don't have examples of using strings for sentinels.
public static void main(String[] args) {
int count = 0;
float total = 0;
float inputNumber;
Scanner scan = new Scanner ( System.in );
System.out.println("Want to enter a number?");
String reply = "";
inputNumber = scan.nextFloat();
do {
reply = scan.nextLine();
if (reply.equalsIgnoreCase("yes")) {
System.out.println("Enter a number > ");
total+= inputNumber ;
count++ ;
System.out.println("Enter another number, or " +
"enter \"no\" to terminate > " );
inputNumber = scan.nextFloat();
}
}
while (! reply.equalsIgnoreCase("no")) ;
if (count != 0) {
System.out.println("The average of the numbers is " +
(total / count));
}
}
}