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!
Related
I'm writing a java program to take a bunch of doubles the user inputs into the command line, add them together, and average them. The user can enter any amount of numbers. When they enter a negative number, the program does the adding/averaging. When i enter a number into cmd line it only lets me enter one. Can anyone help me improve this?
import java.util.Scanner;
public class Average
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Statistics Program, assignment one, program
Two. Sean Kerr");
System.out.println("\nPlease enter a series of numbers. To stop,
enter a negative number.");
//initialize two doubles and an int for our variables: the total numbers,
//the total added together, and the doubles the user enters into cmd line.
int amount = 0;
double totaladded = 0;
double userinput = 0;
userinput = keyboard.nextDouble();
while (userinput >= 0);
{
if(userinput > 0 )
{
totaladded = totaladded+userinput;
amount++;
}
}
System.out.println("Numbers entered: " + amount);
System.out.println("The average is: " + totaladded/amount);
}
}
use a do while loop instead,
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
int amount = 0;
double totaladded = 0;
double userinput = 0;
do {
System.out.println("Statistics Program, assignment one, program Two. Sean Kerr");
System.out.println("\nPlease enter a series of numbers. To stop, enter a negative number.");
//initialize two doubles and an int for our variables: the total numbers,
//the total added together, and the doubles the user enters into cmd line.
userinput = keyboard.nextDouble();
if(userinput > 0 ) {
totaladded += userinput;
amount++;
}
} while (userinput >= 0);
System.out.println("Numbers entered: " + amount);
System.out.println("The average is: " + totaladded/amount);
}
We are supposed to create a loop that repeats for the number of times needed by the student. I am completely lost when it comes to setting up a loop that doesn't run on a predetermined count in the code.
We have to create the loop. I dont really even know where to start since there is nothing in the book that I can see that address that style of condition yet.
Any help is appreciated to get me going in the right direction.
import java.util.*;
public class TestScoreStatistics
{
public static void main (String args[])
{
int score;
int total = 0;
int count = 0;
int highest;
int lowest;
final int QUIT = 999;
final int MIN = 0;
final int MAX = 100;
Scanner input = new Scanner(System.in);
System.out.print("How many scores would you like to enter >> ");
enterCount = input.nextInt();
System.out.print("Enter a score >> ");
score = input.nextInt();
//Create a while statement that will loop for the amount entered
while( count != QUIT )
{
}
System.out.print("Enter another score >> ");
score = input.nextInt();
}
System.out.println(count + " scores were entered");
System.out.println("Highest was " + highest);
System.out.println("Lowest was " + lowest);
System.out.println("Average was " + (total * 1.0 / count));
}
}
So. It seems that you want to request entering scores until the user entered as many scores as defined in enterCount:
List<Integer> scores = new ArrayList<Integer>();
while( count < enterCount ) {
System.out.print("Enter another score >> ");
score = input.nextInt();
scores.add(score);
count++;
}
You probably have to define some kind of List where you put the scores in.
So I have everything working except that once I enter the input required I get input like this:
1 5.0
2 6.0
3 7.0
4 8.0
I don't know what I'm doing wrong as it seems its not increasing in the right increments based on the growthRate that I input which was 50. Also can't get the organism number to increase according to the following day. Any suggestions?
//Purpose of program to predict population of organisms
import java.util.Scanner;
public class Population {
public static void main(String[] args) {
double growthRate = -1;
int population = 0;
int days = -1;
double popResult = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("\nEnter the starting number of organisms:");
population = keyboard.nextInt();
while (population < 2) {
System.out.println("\nError!! Please re-enter number of organisms.");
population = keyboard.nextInt();
}
System.out.println("\nEnter rate of growth as percentage:");
growthRate = keyboard.nextInt() / 100;
while (growthRate < 0) {
System.out.println("\nError!! Growth rate must be a positive number. Please re-enter.");
growthRate = keyboard.nextInt();
}
System.out.println("\nEnter number of days organisms will grow:");
days = keyboard.nextInt();
while (days < 0) {
System.out.println("\nError!! Number of days cannot be less than 1. Please re-enter.");
days = keyboard.nextInt();
}
System.out.println("Days" + "\t" + "Organisms");
System.out.println("------------------");
popResult = population;
growthRate = growthRate / 100;
for (int numberOfDays = 1; numberOfDays < days; numberOfDays++) {
System.out.println(numberOfDays + "\t" + popResult);
popResult = (popResult * growthRate) + popResult;
}
}
}
You are taking input for growthRate as Integer format in line
growthRate=keyboard.nextInt()/100;
If it is less than 0 then you take input without dividing by 100 as
growthRate=keyboard.nextInt();
and finally you are again dividing growthRate as
growthRate=growthRate/100;
So you have to take input outside the while loop only as
growthRate=keyboard.nextInt();
Modified code
import java.util.Scanner;
public class Population
{
public static void main(String[] args)
{
double growthRate=-1;
int population=0;
int days=-1;
double popResult=0;
Scanner keyboard=new Scanner(System.in);
System.out.println("\nEnter the starting number of organisms:");
population=keyboard.nextInt();
while(population<2)
{
System.out.println("\nError!! Please re-enter number of organisms.");
population=keyboard.nextInt();
}
System.out.println("\nEnter rate of growth as percentage:");
growthRate=keyboard.nextInt();
while(growthRate<0)
{
System.out.println("\nError!! Growth rate must be a positive number. Please re-enter.");
growthRate=keyboard.nextInt();
}
System.out.println("\nEnter number of days organisms will grow:");
days=keyboard.nextInt();
while(days<0)
{
System.out.println("\nError!! Number of days cannot be less than 1. Please re-enter.");
days=keyboard.nextInt();
}
System.out.println("Days" + "\t" + "Organisms");
System.out.println("------------------");
popResult=population;
growthRate=growthRate/100;
for(int numberOfDays=1; numberOfDays<days; numberOfDays++)
{
System.out.println(numberOfDays + "\t" + popResult);
popResult=(popResult * growthRate) + popResult;
}}}
So we have to make a mortgage calculation project where we have to ask the user to calculate again and now we have to make it so it prints out a error message every time the user enters a string value for any of the inputs. I thought I did it right but something strange happens every time I run it and I can't figure out why and I know it's something wrong with the Try-Catch blocks.
Here are my outputs: http://imgur.com/cbvwM5v
As you can see the third time i run the program I enter a "two" as the second input and it still did the calculations. Then, the third time I tried it, I entered a negative number then a "two" and everything worked the way I wanted it to. Then, the last time I ran it I put a positive number for the first input and it still did the calculations, anything you guys see that might be doing this? Also, I think I may have used the wrong exception, I'm not uite sure what it means, I just guessed. am I supposed to user NumberFormatException and there is also a line under nfe saying that the value is not being used.
Here's my code:
package MortgageCalculation2c;
import java.text.NumberFormat;
import java.util.Scanner;
/**
*
* #author Akira
*/
public class MortgageCalculation2c {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double loanAmount = 0;
double interestRate = 0;
double numberYears = 0;
double months;
double monthlyPayment;
double numerator;
double denominator;
double formula;
boolean userInput = true;
String answer = ("y");
while (userInput) {
try {
loanAmount = 0;
interestRate = 0;
numberYears = 0;
//prompt user for the loan amount
System.out.print("Enter the loan amount: ");
loanAmount = Double.parseDouble(in.nextLine());
//prompt the user for the interest rate
System.out.print("Enter the rate: ");
interestRate = Double.parseDouble(in.nextLine());
//prompt the user for thenumber of years
System.out.print("Enter the number of years: ");
numberYears = Double.parseDouble(in.nextLine());
} catch (NumberFormatException nfe) {
System.out.println("You must enter positive numerical data!");
}
//if the user enters a negative number print out a error message, if not, continue calculations
if ((loanAmount <= 0) || (interestRate <= 0) || (numberYears <= 0)) {
System.out.println("ALL NUMERICAL VALUES MUST BE POSITIVE!");
} else {
//convert the interest rate
interestRate = interestRate / 100 / 12;
//the number of years must be converted to months
months = numberYears * 12;
//numerator of the monthly payment formula
numerator = (Math.pow(1 + interestRate, months));
//denominator of the monthly payment formula
denominator = ((numerator)-1);
//the formula equals the numerator divided by the denominator
formula = ( numerator / denominator );
//monthly payment calculation
monthlyPayment = (interestRate * loanAmount * formula);
//sytem output
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
System.out.println("The monthly payment is: " + defaultFormat.format(monthlyPayment));
}
//prompt the user if they would like to calculate the program again.
System.out.println("Would you like to calculate again (y/n) : ");
//if the user enters "y" the program will run again and if the user enters anything else it ends
answer = in.nextLine();
answer = answer.toLowerCase();
if ( answer.equals("y")){
userInput = true; //tests the program if it needs to run again
}else{
break; //ends the program
}
}
}
}
Is there anything that you guys can see that might be the problem?
It seems you need continue in your catch block, so the program flow goes back to the loop.
...
} catch (NumberFormatException nfe) {
System.out.println("You must enter positive numerical data!");
continue; // <---------- here
}
...
If this is not a specific exercise in try-catch construct, it be would be better to use Scanner's method hasNextDouble() for validatiing and nextDouble for reading and converting the numbers.
It will look something like this:
//prompt user for the loan amount
loanAmount = enterPositiveDouble("Enter the loan amount: ")
//prompt the user for the interest rate
interestRate = enterPositiveDouble("Enter the rate: ");
//prompt the user for the number of years
numberYears = enterPositiveDouble("Enter the number of years: ");
and you will have a special static method enterPositiveDouble like following:
static void enterPositiveDouble(String prompt) {
Scanner in = new Scanner(System.in);
boolean ok = true;
double result = -1;
do {
System.out.print(prompt);
ok = (in.HasNextDouble() && (result = in.NextDouble()) > 0)
if ! ok
System.out.println("You must enter positive numerical data!");
} while (!ok);
}
The above is not an optimal code but just the illustration of a possible solution.
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()));