This program is supposed to print an error if you enter too many seats. If i enter an invalid number of seats ex: economy section has 8 seats. but if I enter a number greater than that it, the program doesn't go on to the else statement and print the error message.
Instead it just goes through the if statement and does the calculations with the invalid seat number.
import java.util.Scanner;
public class FlightProfit
{
String location;
int TOLEDO_FARE = 200;
int HOUSTON_FARE = 300;
int BOISE_FARE = 400;
int economySeats;
int businessSeats;
int firstClassSeats;
int economySales;
int businessSales;
int firstClassSales;
//int totalSales = economySales + businessSales + firstClassSales;
Scanner in = new Scanner(System.in);
public int addEconomySeats()
{
System.out.print("Enter number of economy seats 1-8: ");
economySeats = in.nextInt();
if(economySeats > 0 || economySeats < 9)
{
return economySeats;
}
else
{
System.out.println("Error: Only 8 seats available in economy.");
}
return 0;
}
public int addBusinessSeats()
{
System.out.print("Enter number of business seats sold: ");
businessSeats = in.nextInt();
if(businessSeats > 0 || economySeats < 7)
{
return businessSeats;
}
else
{
System.out.println("Error: Only 6 seats available in business.");
}
return 0;
}
public int addFirstClassSeats()
{
System.out.print("Enter number of first class seats sold: ");
firstClassSeats = in.nextInt();
if(firstClassSeats > 0 || firstClassSeats < 5)
{
return firstClassSeats;
}
else
{
System.out.println("Error: Only 4 seats available in first class.");
}
return 0;
}
public void getProfit(String loc)
{
location = loc;
if(location.equalsIgnoreCase("toledo"))
{
economySales = economySeats * TOLEDO_FARE;
businessSales = businessSeats * (2 * TOLEDO_FARE);
firstClassSales = firstClassSeats * (4 * TOLEDO_FARE);
System.out.println("Economy Sales: " + economySeats + " seats: " + economySales);
System.out.println("Business Sales: " + businessSeats + " seats: " + businessSales);
System.out.println("First Class Sales: " + firstClassSeats + " seats: " + firstClassSales);
//System.out.println("Total Sales: " + totalSales);
}
else if(location.equalsIgnoreCase("houston"))
{
economySales = economySeats * HOUSTON_FARE;
businessSales = businessSeats * (2 * HOUSTON_FARE);
firstClassSales = firstClassSeats * (4 * HOUSTON_FARE);
System.out.println("Economy Sales: " + economySeats + " seats: " + economySales);
System.out.println("Business Sales: " + businessSeats + " seats: " + businessSales);
System.out.println("First Class Sales: " + firstClassSeats + " seats: " + firstClassSales);
// System.out.println("Total Sales: " + totalSales);
}
else
{
economySales = economySeats * BOISE_FARE;
businessSales = businessSeats * (2 * BOISE_FARE);
firstClassSales = firstClassSeats * (4 * BOISE_FARE);
System.out.println("Economy Sales: " + economySeats + " seats: " + economySales);
System.out.println("Business Sales: " + businessSeats + " seats: " + businessSales);
System.out.println("First Class Sales: " + firstClassSeats + " seats: " + firstClassSales);
//System.out.println("Total Sales: " + totalSales);
}
}
}
==MAIN==
import java.util.Scanner;
public class Aviation
{
public Aviation()
{
}
public static void main(String[] args)
{
int option;
FlightCost newFlight = new FlightCost();
FlightProfit flight = new FlightProfit();
Scanner in = new Scanner(System.in);
System.out.print("Enter new flight location: ");
String location = in.next();
do{
String menu = "\n Please select an option to perform"
+ "\n1 (1) Get flight costs."
+ "\n2 (2) Get flight profits."
+ "\n3 (3) Enter names/meals."
+ "\n4 (4) Exit.";
System.out.println(menu);
option = in.nextInt();
}while (option < 0 || option > 4);
switch(option)
{
case 1:
newFlight.getCost(location);
break;
case 2:
flight.addEconomySeats();
flight.addBusinessSeats();
flight.addFirstClassSeats();
flight.getProfit(location);
break;
case 3:
//newFlight.flyers();
break;
case 4:
System.out.println("Exit");
break;
default:
System.out.println("Error: must select menu option.");
}
}
}
if (economySeats > 0 || economySeats < 9)
This condition is always true (since any number is either positive or less than 9), so of course you don't reach the else clause.
You probably want the && (and) operator :
if (economySeats > 0 && economySeats < 9)
And your other conditions have the same error.
if (economySeats > 0 && economySeats < 9)
As economySeats should be greater then 0 and smaller then 9. then only the condition will follow to the else statement.
when you use if (economySeats > 0 || economySeats < 9)
it means that economySeat should be greater then 0 (so if you input value greater then 0 then this condition will be true) so, that's why you are thinking that the if statement isnt working.
The reason why your number range check does not work as you intend to was already given. I'd howver like to hint that you could do range checks somewhat more elegant and less error-prone by using Guava's 'Range' type:
Range economySeatsRange = Range.atLeast(1).atMost(8);
//...
boolean inAllowedRange = economySeatsRange.apply(economySeats);
if(inAllowedRange)
// between 1 and 8
else
// signal error
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html
Related
I'm having issues with my loop. I'm trying to have the user input a number selection that repeats if they select an item and exits if they input 5. However, when running it, if I select 2 items, it would require me to enter 5 twice to exit the loop.
I appreciate any help.
public static void coffee() {
double espressoP = 4.50;
double latteP = 4.50;
double cappuccinoP = 6.00;
double coldBrewP = 4.00;
int coffeeChoice = 0;
boolean exit = true;
System.out.println("=== Select Coffee: ===");
System.out.println("1. Espresso $4.50");
System.out.println("2. Latte $4.50");
System.out.println("3. Cappuccino $6.00");
System.out.println("4. Cold Brew $4.00");
System.out.println("5. Quit coffee selection.");
System.out.println("Select a coffee [Enter 1 - 5]:");
while (exit = true) {
coffeeChoice = scnr.nextInt();
if (coffeeChoice == 1) {
System.out.println("Added 1 Espresso.");
C1 += 1;
totPrice = totPrice + espressoP;
System.out.println(C1 + " " + totPrice);
coffee();
}
else if (coffeeChoice == 2) {
System.out.println("Added 1 Latte.");
C2 += 1;
totPrice = totPrice + latteP;
System.out.println(C2 + " " + totPrice);
coffee();
}
else if (coffeeChoice == 3) {
System.out.println("Added 1 Cappuccino.");
C3 += 1;
totPrice = totPrice + cappuccinoP;
System.out.println(C3 + " " + totPrice);
coffee();
}
else if (coffeeChoice == 4) {
System.out.println("Added 1 Cold Brew.");
C4 += 1;
totPrice = totPrice + coldBrewP;
System.out.println(C4 + " " + totPrice);
coffee();
}
else if (coffeeChoice == 5) {
exit = false;
break;
}
else {
System.out.println("Invalid entry. Enter a selection between 1 and 5.");
scnr.next();
}
}
Updated. Agree with comments. exit = true is a typo, break will nullify it. Reason of multiple asking for input "5" is because of recursion.
I want max and min values of salary to display but i get same values for max and min. Here's my code:
import java.util.*;
class Wage {
String employee_name, skill;
int hours;
double sum;
String[] sno = {"1", "2", "3", "4"};
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE;
Scanner s = new Scanner(System.in);
public void getEmployeeDetails() {
System.out.println("Welcome to Use General Wage Record System");
for (String count : sno) {
if (count.equalsIgnoreCase("1")) {
System.out.print("Enter Name of Employee 1: ");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " " + "$" + sum);
}
}
if (count.equalsIgnoreCase("2")) {
System.out.print("Enter Name of Employee 2:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee " + employee_name + "(Level " + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " " + "$" + sum);
}
}
if (count.equalsIgnoreCase("3")) {
System.out.print("Enter Name of Employee 3:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " $" + sum);
}
}
if (count.equalsIgnoreCase("4")) {
System.out.print("Enter Name of Employee 4:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + "$ " + sum);
}
}
}
}
void average() {
System.out.println("\n\n");
System.out.println("stastical information for bar chart");
System.out.println("==================================");
if (sum > max) {
max = sum;
System.out.println("Maximum of wage" + max + ", " + employee_name);
}
if (sum < min) {
min= sum ;
System.out.println("Minimum of Wage" + min + ", " + employee_name);
}
}
}
public class Pay {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Wage wm = new Wage();
wm.getEmployeeDetails();
wm.average();
}
In the loop of the getEmployeeDetails() method, you don't store and update the min wage, the max wage and the employee names that have these wages.
Besides, you should be more specific in the naming. For example, maxWage and minWage are more meaningful than max and min.
So, you should have maxWage, maxWageEmployeeName, minWage and minWageEmployeeName fields in the field declaration of the Wage class.
At each employee inserted in the system, you should update these values by calling a dedicated method:
public void getEmployeeDetails() {
if (count.equalsIgnoreCase("1")) {
....
updateRanking(sum, employee_name);
}
}
public void updateRanking(double actualWage, String employee_name){
if (actualWage > maxWage) {
maxWage = actualWage;
maxWageEmployeeName = employee_name;
}
else if (actualWage < minWage) {
minWage = actualWage;
minWageEmployeeName = employee_name;
}
}
Besides, your average() method called at the end of your program should only display the result and not performing comparison since you should have updated information about max, min wage and who have these as updateRanking() is called at each insertion of employee wage :
void average() {
System.out.println("\n\n");
System.out.println("stastical information for bar chart");
System.out.println("==================================");
System.out.println("Maximum of wage" + maxWage + ", " + maxWageEmployeeName );
System.out.println("Minimum of Wage" + minWage + ", " + minWageEmployeeName );
}
Im learning java with "programmingbydoing" and i have a problem with Nim game, everything works fine apart from one thing, which is that both:
"System.out.print(n1 + ", choose a pile: ");"
and
"System.out.print(n2 + ", choose a pile: ");"
is out printed twice after the first time.
Here is code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Player one, enter your name: ");
String n1 = input.nextLine();
System.out.print("Player two, enter your name: ");
String n2 = input.nextLine();
int a = 3;
int b = 4;
int c = 5;
int count = 1;
System.out.println("A: "+a+" B: "+b+" C: "+c);
nim_loop:while(a > 0 || b > 0 || c > 0) {
while(count % 2 != 0 ) {
System.out.print(n1+", choose a pile: ");
String first = input.nextLine();
if (first.contains("a") || first.contains("A")) {
System.out.print("How many to remove from pile " + first + "? ");
int second = input.nextInt();
count = count + 1;
a = a - second;
System.out.println("A: " + a + " B: " + b + " C: " + c);
if(a <= 0 && b <= 0 && c <= 0){
break nim_loop;
}
}
else if (first.contains("b") || first.contains("B")) {
System.out.print("How many to remove from pile " + first + "? ");
int second = input.nextInt();
count = count + 1;
b = b - second;
System.out.println("A: " + a + " B: " + b + " C: " + c);
if(a <= 0 && b <= 0 && c <= 0){
break nim_loop;
}
}
else if (first.contains("c") || first.contains("C")) {
System.out.print("How many to remove from pile " + first + "? ");
int second = input.nextInt();
count = count + 1;
c = c - second;
System.out.println("A: " + a + " B: " + b + " C: " + c);
if(a <= 0 && b <= 0 && c <= 0){
break nim_loop;
}
}
}
while(count % 2 == 0) {
System.out.print(n2 + ", choose a pile: ");
String third = input.nextLine();
if (third.contains("a") || third.contains("A")) {
System.out.print("How many to remove from pile " + third + "? ");
int fourth = input.nextInt();
count = count + 1;
a = a - fourth;
System.out.println("A: " + a + " B: " + b + " C: " + c);
} else if (third.contains("b") || third.contains("B")) {
System.out.print("How many to remove from pile " + third + "? ");
int fourth = input.nextInt();
count = count + 1;
b = b - fourth;
System.out.println("A: " + a + " B: " + b + " C: " + c);
} else if (third.contains("c") || third.contains("C")) {
System.out.print("How many to remove from pile " + third + "? ");
int fourth = input.nextInt();
count = count + 1;
c = c - fourth;
System.out.println("A: " + a + " B: " + b + " C: " + c);
}
}
}
if (count % 2 != 0) {
System.out.println("Game ended, Player " + n1 + " is a winner.");
} else if (count % 2 == 0){
System.out.println("Game ended, Player " + n2 + " is a winner.");
}
}
}
And here are the pictures of what happens when i run it:
When the first if condition in first inner loop is true and when you get the user input by using nextInt() it only reads the int value and does not consume the last new line character i,e \n. So the subsequent call to nextLine() will be skipped i,e the nextLine() call in second inner while loop will be skipped without any value but System.out.print(n2 + ", choose a pile: "); will be printed as it is before nextLine() call and control goes back to outer while loop.
Now the count value is 2 so first inner while condition will be false and control goes to second inner while loop. And again it prints b, choose a pile:. Hope this clears your question
Workaround is fire a blank nextLine() call after every nextInt() or use nextLine() inside if condition and parse the user input using Integer.parseInt(String) method.
Example code :
if (first.contains("a") || first.contains("A")) {
System.out.print("How many to remove from pile " + first + "? ");
int second = input.nextInt();
input.nextLine(); // firing an blank nextLine call
count = count + 1;
a = a - second;
System.out.println("A: " + a + " B: " + b + " C: " + c);
if(a <= 0 && b <= 0 && c <= 0){
break nim_loop;
}
For more information - Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
My problem is probably ridiculously easy and I'm just missing something. My program crashes due to a null value of cell 1 during its first iteration. i troubleshot a bit myself and realized on iteration 1 the array length is 1 then after all other iterations the length is 2. this initial improper length causes a complete crash. Any ideas?
`import java.util.Scanner;
import java.io.*;
/* Takes in all of users personal information, and weather data. Then proceeds to determine status of day + averages of the data values provided, then reports to user*/
public class ClimateSummary
{
public static void main (String [] args) throws FileNotFoundException
{
Scanner sc = new Scanner (new File(args[0]));
String name = sc.nextLine();
String birthCity = sc.next();
String birthState = sc.next();
String loc = sc.next();
int birthDay = sc.nextInt();
String birthMonth = sc.next();
int birthYear = sc.nextInt();
int highTemp = 0;
double avgTemp;
double avgPrecip;
int coldDays = 0;
int hotDays = 0;
int rainyDays = 0;
int niceDays = 0;
int miserableDays = 0;
double totalTemp = 0;
double totalPrecip = 0;
int i = 0;
while(i <= 5)
{
String storage = sc.nextLine();
String[] inputStorage = storage.split(" "); //couldnt find scanf equiv in c for java so using array to store multiple values.
System.out.println(inputStorage[0]);
int tempTemp = Integer.parseInt(inputStorage[0]);
double tempPrecip = Double.parseDouble(inputStorage[1]);
totalTemp = totalTemp + tempTemp;
totalPrecip = totalPrecip + tempPrecip;
if(highTemp < tempTemp)
{
highTemp = tempTemp;
}
if(tempTemp >= 60.0)
{
hotDays++;
}else{
coldDays++;
}
if(tempPrecip > 0.1)
{
rainyDays++;
}
if(tempTemp >= 60.0 || tempTemp <= 80.0 || tempPrecip == 0.0)
{
niceDays++;
}else if(tempTemp < 32.0 || tempTemp > 90.0 || tempPrecip > 2.0)
{
miserableDays++;
}else{
}
i++;
}
avgTemp = totalTemp/5;
avgPrecip = totalPrecip/5;
System.out.println("Name: " + name);
System.out.println("Place of birth: " + birthCity + "," + birthState);
System.out.println("Data collected at: " + loc);
System.out.println("Date of birth: " + birthMonth + " " + birthDay +", " + birthYear);
System.out.println("");
System.out.println("The highest temperature during this tine was " + highTemp + " degrees Farenheit");
System.out.println("The average temperature was " + avgTemp + " degrees Farenheit");
System.out.println("The average amount of precipitation was " + avgPrecip + " inches");
System.out.println("Number of hots days = " + hotDays);
System.out.println("Number of cold days = " + coldDays);
System.out.println("Number of rainy days = " + rainyDays);
System.out.println("Number of nice days = " + niceDays);
System.out.println("Number of miserable days = " + miserableDays);
System.out.println("Goodbye and have a nice day!");
}
Eric Thomas
Columbus
Nebraska
Columbus
18
February
1990
54 0
44 2.2
64 0.06
26 0.5
34 0.02
If your file contains null values then you should handle it separately.... using something like this:
if (name == null) {
//do something
}
else {
// do something else;
}
A good discussion on nulls can be seen here...How to check for null value in java
Also, after splitting a string, you need to check if the array (which is the output) has values at the indices that you are using.
For example:
String name = "A/B/C";
String[] nameArray = name.split("/");
In the above case, nameArray[3] will throw an error.
My program is not allowing me to enter user input if i do not enter a number and i want to go through the program again, it think its due to a hanging token somewhere but i cannot seem to find it.
import java.util.Scanner;
public class LessonTwo {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
char answer = ' ';
do {
System.out.print("Your favorite number: ");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
userInput.nextLine();
System.out.println("You entered " + numberEntered);
int numEnteredTimes2 = numberEntered + numberEntered;
System.out.println(numberEntered + " + " + numberEntered
+ " = " + numEnteredTimes2);
int numEnteredMinus2 = numberEntered - 2;
System.out.println(numberEntered + " - 2 " + " = "
+ numEnteredMinus2);
int numEnteredTimesSelf = numberEntered * numberEntered;
System.out.println(numberEntered + " * " + numberEntered
+ " = " + numEnteredTimesSelf);
double numEnteredDivide2 = (double) numberEntered / 2;
System.out.println(numberEntered + " / 2 " + " = "
+ numEnteredDivide2);
int numEnteredRemainder = numberEntered % 2;
System.out.println(numberEntered + " % 2 " + " = "
+ numEnteredRemainder);
numberEntered += 2; // *= /= %= Also work
numberEntered -= 2;
numberEntered++;
numberEntered--;
int numEnteredABS = Math.abs(numberEntered); // Returns the
int whichIsBigger = Math.max(5, 7);
int whichIsSmaller = Math.min(5, 7);
double numSqrt = Math.sqrt(5.23);
int numCeiling = (int) Math.ceil(5.23);
System.out.println("Ceiling: " + numCeiling);
int numFloor = (int) Math.floor(5.23);
System.out.println("Floor: " + numFloor);
int numRound = (int) Math.round(5.23);
System.out.println("Rounded: " + numRound);
int randomNumber = (int) (Math.random() * 10);
System.out.println("A random number " + randomNumber);
} else {
System.out.println("Sorry you must enter an integer");
}
System.out.print("Would you like to try again? ");
answer = userInput.next().charAt(0);
}while(Character.toUpperCase(answer) == 'Y');
System.exit(0);
}
}
Yes you are right you need to consume the characters first after the user inputted character in the nextInt before allowing the user to input data again
just add this in your else block and it will work:
else {
System.out.println("Sorry you must enter an integer");
userInput.nextLine(); //will consume the character that was inputted in the `nextInt`
}
EDIT:
change this:
answer = userInput.next().charAt(0);
to:
answer = userInput.nextLine().charAt(0);