do-while loop not continuing - java

I'm having an issue with the code below. It's all working fine, except I want the program to restart if the user types in "Y" at the end, and end if anything else is pressed.
However, whenever I type anything at the "Restart Calculator" prompt, it will stop running, regardless of whether I type in "Y" or "N". Validation with the Y/N is not too important here, I just want it to restart if Y is typed and end if anything else is typed.
Apologies for the noob code, Java beginner here.
import java.util.Scanner;
import java.text.*;
public class Savings {
public static void main(String[] args)
{
//Imports scanner, to read user's input
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
do {
//Asks for and receives user's initial deposit
int initial_Deposit;
do {
System.out.print("Enter initial deposit in dollars (Between $1 - $50000: ");
while (!scan.hasNextInt()) {
System.out.println("Please enter a valid number between '1-50000'");
scan.next();
}
initial_Deposit = scan.nextInt();
} while (initial_Deposit <= 0 || initial_Deposit >= 50001);
//Asks for and receives user's interest rate
double interest_Rate;
do {
System.out.print("Enter interest rate as a percentage between '0.1-100.0' (e.g. 4.0):");
while (!scan.hasNextDouble()) {
System.out.println("Enter interest rate as a percentage between '0.1-100.0' (e.g. 4.0):");
scan.next();
}
interest_Rate = scan.nextDouble();
} while (interest_Rate <= 0.0 || interest_Rate >= 100.1);
//Asks for and receives user's monthly deposit
int monthly_Deposit;
do {
System.out.print("Enter monthly deposit in dollars between '$1 - $5000: ");
while (!scan.hasNextDouble()) {
System.out.println("Enter monthly deposit in dollars between '$1 - $5000: ");
scan.next();
}
monthly_Deposit = scan.nextInt();
} while (monthly_Deposit <= 0 || monthly_Deposit >= 5001);
//Asks for and receives user's investment duration
int monthly_Duration;
do {
System.out.print("Enter investment duration (Between 1 and 12): ");
while (!scan.hasNextDouble()) {
System.out.println("Enter investment duration (Between 1 and 12): ");
scan.next();
}
monthly_Duration = scan.nextInt();
} while (monthly_Duration <= 0 || monthly_Duration >= 13);
//Asks for and receives user's first name
String first_Name;
System.out.print("Enter first name: ");
first_Name = input.next();
//Asks for and receives user's surname
String last_Name;
System.out.print("Enter surname: ");
last_Name = input.next();
//Formats first name to only first letter
char firstLetter = first_Name.charAt(0);
//Changes name to correct format
String formatted_Name;
formatted_Name = "Savings growth over the next six months for " + last_Name + ", " + firstLetter;
System.out.println(formatted_Name);
//Calculates the first balance
double balanceCurrent;
balanceCurrent = initial_Deposit + monthly_Deposit;
//Prepares to format currency
DecimalFormat df = new DecimalFormat("#.##");
//Defining variables
double balanceNew;
double interestEarned;
//Defining counter for while loop
int counter;
counter = monthly_Duration;
int month_Counter;
month_Counter = 1;
//While loop to calculate savings
while (counter > 0) {
balanceNew = balanceCurrent + (balanceCurrent *((interest_Rate /12)/100));
interestEarned = balanceCurrent *((interest_Rate /12)/100);
balanceCurrent = balanceNew + monthly_Deposit;
System.out.println("Balance after month " + month_Counter + ": $" + df.format((balanceNew)));
System.out.println("Interest earned for this month: $" + df.format(interestEarned));
counter = counter - 1;
month_Counter = month_Counter + 1;
}
//Formats data into a table
balanceCurrent = initial_Deposit + monthly_Deposit;
counter = monthly_Duration;
int month;
month = 0;
String dollarSign = "$";
String stringHeadingOne = "Month";
String stringHeadingTwo = "New Balance";
String stringHeadingThree = "Interest Earned";
String dividerOne = "----- ----------- ---------------";
System.out.println("");
System.out.printf("%-9s %s %19s \n", stringHeadingOne, stringHeadingTwo, stringHeadingThree);
System.out.println(dividerOne);
while (counter > 0) {
balanceNew = balanceCurrent + (balanceCurrent *((interest_Rate /12)/100));
interestEarned = balanceCurrent *((interest_Rate /12)/100);
balanceCurrent = balanceNew + monthly_Deposit;
month = month + 1;
System.out.printf("%-11s %s %s %13s %s \n", month, dollarSign, df.format((balanceNew)), dollarSign, df.format(interestEarned));
counter = counter - 1;
}
System.out.print("Restart Calculator? Y/N);");
} while (scan.next() == "Y");
}
}

while (scan.next() == "Y"); // Is checking for reference equality
When doing object comparisons in Java, use equals()
while (scan.next().equals("Y"));
Or, as the previous answer pointed out you can compare characters with the == operator

Try this:
scan.nextLine().charAt(0) == 'Y'

When comparing Strings or anyother object for that matter you need to use the .equals(Object other) method. You can only use == with primatives ( boolean, int, double,...)
scan.nextLine().equals("Y");
//or
scan.next().equals("Y");
There is also an method to take the string to Uppercase that would allow the user to enter "y" or "Y"
scan.next().toUpperCase().equals("Y");

You should be using the Equals method for Strings:
while ("Y".equals(scan.next()));

Related

I have a program where i would like to validate user input in java i want the user to input a double value and only a double value any suggestions?

I did what i could and now the code works however when the user inputs the wrong value and is prompted to try again you have to hit enter and then you are asked to input a value, i cant think of what it is.
i also want to be able to get the program to start again after completing, i tried a do, while loop but it looped infinitely
public static void main(String[] args) {
String nameOfIngredient = null;
Float numberOfCups = null;
Float numberOfCaloriesPerCup = null;
Float totalCalories;
while(nameOfIngredient == null)
{nameOfIngredient = setIngredients(); }// Allows us to loop
while(numberOfCups == null)
{numberOfCups = setNumberOfCups(); }// Allows us too loop
while(numberOfCaloriesPerCup == null)
{numberOfCaloriesPerCup = setNumberOfCalories();} // Allows us to loop
totalCalories = numberOfCups * numberOfCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberOfCups + " cups and this amount contains " + totalCalories + " total calories.");
System.out.print("\n");
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static String setIngredients() {
System.out.println("Please enter the name of the ingredient: ");
Scanner scan = new Scanner(System.in);
try {
String ingredients = scan.nextLine();
System.out.println("\r");
return ingredients;
}
catch (Exception e){
scan.nextLine();
System.out.println("Error taking in input, try again");
}
return null;
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static Float setNumberOfCups() {
System.out.println("Please Enter Number Of Cups: ");
Scanner scan = new Scanner(System.in);
try {
String numberOfCups = scan.nextLine();
Float numberOfCupsFloat = Float.parseFloat(numberOfCups);
System.out.println("\n");
return numberOfCupsFloat;
}
catch (NumberFormatException numberFormatException){
System.out.println("Invalid Input must be a numeric value Please Try Again: ");
System.out.println("\n");
scan.nextLine();
}
catch (Exception e){
scan.nextLine();
System.out.println("Error taking in input, try again.");
}
return null;
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static Float setNumberOfCalories() {
System.out.println("Please Enter Number Of Calories per cup: ");
Scanner scan = new Scanner(System.in);
try {
String numberOfCalories = scan.nextLine();
Float numberOfCaloriesFloat = Float.parseFloat(numberOfCalories);
System.out.println("\n");
return numberOfCaloriesFloat;
}
catch (NumberFormatException numberFormatException){
System.out.println("Invalid value Please enter a numeric value:");// if the input is incorrect the user gets prompted for the proper input
scan.nextLine();// if the input is incorrect the user gets prompted for the proper input
}
catch (Exception e){
scan.nextLine();
System.out.println("Error in input please try again.");
}
return null;
}
You may want to accept it as a string and check if it is numeric or not using String methods. Post that you can either move forward if format is correct or re prompt the user for correct value while showing the error.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); //In case ingredient is more than one word long.
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
String numCups = scnr.next();
while(!numCups.chars().allMatch( Character::isDigit ))
{
System.out.println("Incorrect format for number of cups. Please enter numeric values");
numCups = scnr.next();
}
numberCups = Double.parseDouble(numCups);
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and this amount contains " + totalCalories + " total calories.");
}
Alternatively you could also do this using try catch statements. I believe this would be a better way to parse double values
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); //In case ingredient is more than one word long.
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
String numCups = scnr.next();
while(numberCups==0.0)
{
try {
numberCups = Double.parseDouble(numCups);
} catch (NumberFormatException e) {
System.out.println("Incorrect format for number of cups. Please enter numeric values");
numCups = scnr.next();
}
}
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and this amount contains " + totalCalories + " total calories.");
}
I've taken your code and added support for input of fractional numbers. Comments added on important changes.
parseCups returns an Optional so we can tell if the input was valid or not.
parseIngredientValue does the work of deciding whether or not the input is a fraction and/or attempting to parse the input as a Double.
package SteppingStone;
import java.util.Optional;
import java.util.Scanner;
public class SteppingStone2_IngredientCalculator {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
String cupsStr = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); // In case ingredient is more than one word long.
Optional<Double> cups = Optional.empty();
while (cups.isEmpty()) { // repeat until we've got a value
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
cupsStr = scnr.nextLine();
cups = parseCups(cupsStr);
}
numberCups = cups.get();
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
// Using String.format to allow rounding to 2 decimal places (%2.2f)
System.out.println(String.format("%s uses %2.2f cups and this amount contains %2.2f total calories.",
nameOfIngredient, numberCups, totalCalories));
}
private static double parseIngredientValue(String input) {
if (input.contains("/")) { // it's a fraction, so do the division
String[] parts = input.trim().split("/");
double numerator = (double) Integer.parseInt(parts[0]);
double denomenator = (double) Integer.parseInt(parts[1]);
return numerator / denomenator;
} else { // it's not a fraction, just try to parse it as a double
return Double.parseDouble(input);
}
}
private static Optional<Double> parseCups(String cupsStr) {
double result = 0.0;
String input = cupsStr.trim();
String[] parts = input.split(" +"); // split on any space, so we can support "1 2/3" as an input value
switch (parts.length) {
case 2:
result += parseIngredientValue(parts[1]); // add the 2nd part if it's there note that there's no
// break here, it will always continue into the next case
case 1:
result += parseIngredientValue(parts[0]); // add the 1st part
break;
default:
System.out.println("Unable to parse " + cupsStr);
return Optional.empty();
}
return Optional.of(result);
}
}
Sample run:
Please Enter Ingredient Name:
Special Sauce
Please enter the number of cups of Special Sauce required:
2 2/3
Please enter the number of calories per cup of Special Sauce :
1500
Special Sauce uses 2.67 cups and this amount contains 4000.00 total calories.

A java program that displays weekly payroll for 5 employees (error in desired output)

My coding is based on this question:
screenshot of the question
And this is what I've coded and it's completed but I have an error in the desired output.
package assignment_2;
import java.util.Scanner;
public class Assignment_2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String employeeName[] = new String[5];
int employeeID[] = new int[5];
int payStatus[] = new int[5];
double Grosspay[] = new double [5];
int workHours[] = new int[5];
double payRateperhour[] = new double [5];
double incomeTax[] = new double [5];
double netPay[] = new double [5];
System.out.println("Enter 5 employee details.");
for (int i = 0; i < 5; i++) {
String nextLine = input.nextLine(); //skip whitespace error
System.out.print("Enter Employee " + (i+1) + " name: "); //prompt user input for employee name
employeeName[i] = input.nextLine();
System.out.print("Enter Employee " + (i+1) + " ID: "); //prompt user input for employee ID
employeeID[i] = input.nextInt();
System.out.print("Enter Employee " + (i+1) + " pay status (1 = Salary or 2 = Hourly): "); //prompt user input for employee paid by salary or hourly?
payStatus[i] = input.nextInt();
if (payStatus[i] == 1){ //pay by salary user input
System.out.print("Enter employee gross pay(RM): ");
Grosspay[i] = input.nextDouble();
System.out.print("Enter employee work hours per week: ");
workHours[i] = input.nextInt();
} else { //pay by hourly user input
System.out.print("Enter employee pay rate per hour(RM): ");
payRateperhour[i] = input.nextDouble();
System.out.print("Enter employee work hours per week: ");
workHours[i] = input.nextInt();
//calculate overtime pay
if (workHours[i] > 40) {
Grosspay[i] = (40 * payRateperhour[i]) + 1.5 * (workHours[i] - 40) * payRateperhour[i];
} else Grosspay[i] = workHours[i] * payRateperhour[i];
}
//calculate income tax
if (Grosspay[i] > 0.00 || Grosspay[i] < 999.99) {
incomeTax[i] = (8 /100) * Grosspay[i];
} else if (Grosspay[i] > 500.00 || Grosspay[i] < 999.99) {
incomeTax[i] = (10 /100) * Grosspay[i];
} else if (Grosspay[i] > 1000.00) {
incomeTax[i] = (15 /100) * Grosspay[i];
} else
//calculate net pay
netPay[i] = Grosspay[i] - incomeTax[i];
}
//Display employee details and weekly salary
System.out.print("\n\n\t\tPrint Daily Company (PDC)\n\t\t Weekly Payroll Data\n");
System.out.println("----------------------------------------------------------------");
System.out.println(" Name\t\tID#\tGross Pay\tTax\tNet Pay");
for (int i = 0; i < 5; i++) {
System.out.println(employeeName[i] + "\t" + employeeID[i] + "\t" + Grosspay[i] + "\t" + incomeTax[i] + "\t" + netPay[i]);
}
}
}
My error is that it does not calculate the income tax. In the output it shows 0.00. And the net pay is being outputted the same amount as the gross pay. And one of the outputs from a given sample I keyed in my program showed more than 2 decimal places unlike the rest of the outputs.
P.s: I also didn't know how to fix the error of whitespace os skipping an input line. So I just inserted String nextLine = input.nextLine(); //skip whitespace error before all the user inputs. (If anyone can help me with that or teach/show me a smooth output, that'd be great)
Thank you in advance.
Below is how my output looks like in case anyone was wondering.
screenshot of output
[UPDATE]:
This is the updated output for my program. enter image description here My net pay isn't working and so as the decimal point value. Still in need of help.
Thank you in advance.
So this little "problem" is not that easy to catch.
But in essence, Java tricked you by rounding numbers. Every time you used (8 / 100) or any other of the calculations for the income tax, java just rounded them to 0, because integer / integer is interpreted as integer result. The easiest way to fix it, is just to add .0 to each 100.
if (Grosspay[i] > 0.00 || Grosspay[i] < 999.99) {
incomeTax[i] = (8 / 100.0) * Grosspay[i];
} else if (Grosspay[i] > 500.00 || Grosspay[i] < 999.99) {
incomeTax[i] = (10 / 100.0) * Grosspay[i];
} else if (Grosspay[i] > 1000.00) {
incomeTax[i] = (15 / 100.0) * Grosspay[i];
}
This should work.

Trouble with nested if statements

The project has to do several things with park attendance. The issues that I'm having are that when I ask the user for input and set it with
"entering = kb.nextInt();" or the same for the exit option it seems that the program isn't stepping through conditional logic as I think it should. It Will meet a condition and then some that it shouldn't either. Any help would be greatly appreciated. I've already emailed my professor and my project isn't due for a couple of days I just wanted to finish and polish it early. Screenshot of code running
import java.util.Scanner;//import Scanner
import java.text.DecimalFormat;//import formatter
public class ParkAttendance
{
public static void main(String[] args)
{
//used for user input
Scanner kb = new Scanner(System.in);
//used to format currency
DecimalFormat currency = new DecimalFormat("$#,##0.00");
//used to format average
DecimalFormat decimal = new DecimalFormat("#.0");
//----------------User Input----------------------------------
int menuChoice = 0;//menu choice
int subMenuChoice = 0;//menu choice
//-----------------Calculations-------------------------------
int exitCounter = 0;//number of times exits were entered
int enterCounter = 0;//number of times entries were entered
int highestAttendance = 0;//holds highest attendance
int currentAttendance = 0;//holds current attendance
int entering ;// people entering the park
int exiting ;//people exiting the park
boolean black = false;//boolean for in the black or red check
double avgEnter = 0;//average number of people entering the park
double avgExit = 0;//average number of people exiting the park
double income = 0;// income made for the day
//-----------------------Constants----------------------------
final int CAPACAITY = 250;//capacity of the park
final double TICKET = 7.5;//ticket cost
final int OP_COST = 2250;//operating costs for the park
//prompt for user menu
System.out.println("1. Display Park Attendance"
+"\n2. Update Attendance"
+"\n3. End Attendance Tracker\n");
//The user menu
do
{
menuChoice = kb.nextInt();
//Display currentAttendance
if(menuChoice == 1)
{
System.out.println("Current Attendance:" + currentAttendance );
}
//Attendance updater
if(menuChoice == 2)
{
System.out.println("1. People have entered the park"
+"\n2. People have left the park\n");
subMenuChoice = kb.nextInt();
if(subMenuChoice ==1)
{ //Prompt for input
System.out.println("Enter the number of people entering the park: ");
entering = kb.nextInt();
//change attendance as long as it's less than 250 and adjust currentAttendance
if(entering > 0)
{
currentAttendance += entering;
if(currentAttendance > 250)
{
System.out.println("Please wait until some people have left the park!");
currentAttendance -= entering;
}
else if (currentAttendance <= 250);
{
System.out.println(entering + " People have entered the park!");
enterCounter += 1;
income += (entering * TICKET);
}
}
if(entering < 0);
{
System.out.println("Please enter a positive number!");
entering = 0;
}
}
if(subMenuChoice == 2)
{ //Prompt for input
System.out.println("Enter the number of people exiting the park: ");
exiting = kb.nextInt();
//check to see if user entered a positive value
if(exiting < 0);
{
System.out.println("Please enter a positive number!");
currentAttendance = 0;
exitCounter = 0;
}
if(exiting > 0)
{
System.out.println(exiting + " people have left the park!");
currentAttendance -= exiting;
exitCounter += 1;
}
}
}//end of attendance updater
//re-prompt for menu
System.out.println("1. Display Park Attendance"
+"\n2. Update Attendance"
+"\n3. End Attendance Tracker\n");
}while(menuChoice != 3);//end of do while
//calculate average entries and exits
if(enterCounter >0 && exitCounter >0)
{
avgEnter = currentAttendance/enterCounter;
avgExit = currentAttendance/exitCounter;
}
//calculate if operating costs were met
if(income > OP_COST)
{
black = true;
}
//display calculations and end program
System.out.print("The highest attendance was: " + highestAttendance
+"\n Average number of people entering:" + decimal.format(avgEnter)
+"\n Average number of people exiting: " + decimal.format(avgExit)
+"\n Income earned: " + currency.format(income)
+"\n In the black: " + black);
}//end of main
}//end of Project2
For one thing, you have a semicolon at "if(entering < 0);" so that will always display. Also you have a semicolon at "if(exiting < 0);" so that will always display too. You should also check to make sure that number of people leaving does not exceed the number of people currently in the park. Also you are never doing anything with highestAttendance. Your avgEnter and avgExit are always going to be 0 because of integer division. It is truncating the values (int)/(int). You can easily fix this by typecasting one or both of the ints to doubles, like "avgEnter = currentAttendance/ (double) enterCounter;" Hope this helps, good luck!

Loop not quite working java

I am new to stackoverflow. First I would like the program to loop with a price, then a question(enter another price?), price, then a question and so on. Below is the output.
Please enter a price:
33
Enter another price?
y
Please enter a price:
66
Please enter a price:
99
Please enter a price:
22
However it will keep looping at the end with "Please enter a price:". I want it to do:
Please enter a price:
33
Enter another price?
y
Please enter a price:
66
Enter another price?
y
Please enter a price:
22
Can anyone help me with this? Also, sometimes the average does not update fully. Thanks :)
import java.util.Scanner;
public class ReadInPrice {
public static void main(String[] args) {
int integer = 0;
int count = 0;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
String addPrice;
System.out.println("Please enter a price: ");
integer = input.nextInt();
do {
System.out.println("Enter another price? ");
addPrice = input.next();
while (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
count = count + 1;
sum = sum + integer;
System.out.println("Please enter a price: ");
integer = input.nextInt();
}
}
while (addPrice.equalsIgnoreCase("Y"));
average = sum / count;
System.out.println("Average = " + average);
input.close();
}
}
You need to replace your while with an if
if (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
count = count + 1;
sum = sum + integer;
System.out.println("Please enter a price: ");
integer = input.nextInt();
}
In fact, addPrice is not modified within your second while loop, and so you have an infinite loop.
In order to do the averaged price, you're in the right way but not in the right place :P
count = count +1 and sum = sum + integer should be done after each integer = input.nextInt(). In your current code, you don't increment the counter and don't add the integer for the last input.
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++ ; // count = count +1
sum += integer ; // sum = sum + integer
do {
System.out.println("Enter another price? ");
addPrice = input.next();
while (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++ ; // count = count +1
sum += integer ; // sum = sum + integer
}
}
while (addPrice.equalsIgnoreCase("Y"));
Finally here is a improved version which avoid the use of if.
int sum = 0;
int integer = 0;
String addPrice = "Y";
while( "Y".equalsIgnoreCase(addPrice) ) {
System.out.println("Please enter a price: ");
integer = input.next();
sum += integer ;
count++;
System.out.println("Enter another price? ");
addPrice = input.next();
}
int avg = sum / count ;
What you should do is change your logic a bit. You need to repeat two actions, entering a price and asking if the user wants to enter another price. Only one loop is required for this.
do {
System.out.println("Please enter a price: ");
integer = input.nextInt();
count = count + 1;
sum = sum + integer;
System.out.println("Enter another price? ");
addPrice = input.next();
} while (addPrice.equalsIgnoreCase("Y"));
i think you want something like this:
import java.util.Scanner;
public class ReadInPrice {
public static void main(String[] args) {
int integer = 0;
int count = 0;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
String addPrice = "Y";
while (addPrice.equalsIgnoreCase("Y")){
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++;
sum += integer;
System.out.println("Enter another price? ");
addPrice = input.next();
}
average = sum / count;
System.out.println("Average = " + average);
input.close();
}
}
Try this:
EDIT Added min and max.
public class ReadInPrice {
public static void main(String[] args) {
//better to use 2 scanners when dealing with both string and int
//one for string ; one for ints
Scanner strScanner = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
boolean enter = true;
int sum = 0;
int count = 0;
int min=Integer.MAX_VALUE;
int max=0;
while (enter) { //while user wants to keep adding numbers
System.out.println("Please enter a price: ");
int price = intScanner.nextInt();
if(price < min)
min=price;
if(price > max)
max=price;
sum += price;
count++;
System.out.println("Enter another price? ");
String answer = strScanner.nextLine();
if (!answer.equalsIgnoreCase("Y"))
enter = false; //user doesn't want to keep adding numbers - exit while loop
}
double average = (double)sum / count;
System.out.println("Average = " + average);
System.out.println("Min = " + min);
System.out.println("Max = " + max);
strScanner.close();
intScanner.close();
System.exit(0);
}
}

My scanner skips over my next double and next integer? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 9 years ago.
Whenever I'm running my scanner it skips over the height(double) loop after weight. It also skips over the level(int) loop after age.
Here's my scanner class.
import java.util.Scanner;
public class HowHealthy
{
public static void main(String[] args)
{
String aGender = "";
//New healthy objec tis created
Healthy person = new Healthy();
//Scanner object is created
Scanner in = new Scanner(System.in);
String name = "";
while(!person.setName(name))
{
System.out.print("Person's name: ");
name = in.nextLine();
if(!person.setName(name))
{
System.out.println("Invalid name - must be at least one character!");
}
}
char gender = '\0';
while(!person.setGender(gender))
{
System.out.print(name + ", are you male of female (M/F): ");
gender = in.nextLine().toUpperCase().charAt(0);
if(!person.setGender(gender))
{
System.out.println("Invalid gender - must be M or F (upper or lower case)":
}
}
double weight = 0;
while(!person.setWeight(weight))
{
System.out.print(name + "'s weight (pounds): ");
weight = in.nextDouble();
in.nextLine();
if(!person.setWeight(weight))
{
System.out.println("Invalid weight - must be at least 100 pounds!");
}
}
double height = 0;
while(!person.setHeight(height))
{
System.out.print(name + "'s height (inches): ");
height = in.nextDouble();
if(!person.setHeight(height))
{
System.out.println("Invalid height - must be 60..84, inclusively!");
}
}
int age = 0;
while(!person.setAge(age))
{
System.out.print(name + "'s age (years): ");
age = in.nextInt();
in.nextLine();
if(!person.setAge(age))
{
System.out.println("Invalid age - must be at least 18!");
}
}
System.out.println();
System.out.println("Activity Level: Use these categories:");
System.out.println("\t1 - Sedentary (little or no exercise, desk job)");
System.out.println("\t2 - Lightly active (little exercise / sports 3-5 days/wk");
System.out.println("\t3 - Moderately active(moderate exercise / sports 3-5
System.out.println("\t4 - Very active (hard exercise / sports 6 -7 day/wk)");
System.out.println("\t5 - Extra active (hard daily exercise / sports \n\t physica2X)
int level = 0;
while(!person.setLevel(level))
{
System.out.print("How active are you? ");
level = in.nextInt();
if(!person.setLevel(level))
{
System.out.println("Invalid acitvity level - must be 1..5, inclusively!");
}
}
System.out.println();
//Creates a new Healthy object and prints values based on user's input
System.out.println(person.getName()+ "'s information");
System.out.printf("Weight: %.1f %s \n", person.getWeight(), "pounds");
System.out.printf("Height: %.1f %s \n", person.getHeight(), "inches");
System.out.println("Age: " + person.getAge() + " years");
if (gender == 'M')
{
aGender = "male";
}
else
{
aGender = "female";
}
System.out.println("These are for a " + aGender);
System.out.println();
//Calculates the person's BMR, BMI and TDEE based on user input
System.out.printf("BMR is %.2f \n", person.calcBMR());
System.out.printf("BMI is %.2f \n", person.calcBMI());
System.out.printf("TDEE is %.2f \n", person.calcTDEE());
//Determines person's weight status based on BMI calculated
double BMI = person.calcBMI();
//Displays person's weight status
System.out.println("Your BMI classifies you as " + person.calcWeightStatus());
}
}
Here is my scanner class.
In both cases, you're missing in.nextLine() after you do in.nextInt(). If all of the other lines of code are working using things like in.nextDouble() followed by in.nextLine() my guess is that's what's missing.
Since it is skipping over the loops completely, there is something wrong with your methods for setHeight() and setLevel().
while(!person.setHeight(height))
If it is skipping this loop, it must mean that setHeight(height) is returning true when it should be returning false, or you need to get rid of the '!'

Categories