Problems with if/else statements nested in a while loop - java

The program is a standard flight database using OOP. In this main method there are 5 options that execute different tasks. Options 1 and 2 work without a problem, but for some reason options 3-5 don't execute. The code inside the if/else if's of options 3-5 do not run, and the program just outputs the main menu again.
boolean exit = false;
while (exit == false)
{
System.out.println("Now what would you like to do?");
System.out.println("1. Print out a flight's info");
System.out.println("2. Print out the number of flights through the static variable");
System.out.println("3. Change the departure time of a flight");
System.out.println("4. Change the departure gate of a flight");
System.out.println("5. Exit");
int choice = sc.nextInt();
if (choice == 1)
{
System.out.println("Which flight would you like to print (1 or 2)?");
int choice2 = sc.nextInt();
if (choice2 == 1)
{
f1.printFlight();
}
else if (choice2 == 2)
{
f2.printFlight();
}
else
{
System.out.println("Invalid choice");
}
}
else if (choice == 2)
{
System.out.println("This is the number of flights: ");
int numFlights = f1.getNumFlights();
System.out.println(numFlights);
}
else if (choice == 3)
{
System.out.println("Which flight would you like to change the departure time of (1 or 2)?");
int choice3 = sc.nextInt();
System.out.println(choice3);
if (choice3 == 1)
{
System.out.println("What is the new departure time for flight " + choice3);
int newTime = sc.nextInt();
f1.changeDeptTime(newTime);
}
else if (choice3 == 2)
{
f2.changeDeptTime();
}
else
{
System.out.println("Invalid choice");
}
}
else if (choice == 4)
{
System.out.println("Which flight would you like to change the departure gate of (1 or 2)?");
int choice4 = sc.nextInt();
if (choice4 == 1)
{
f1.changeDeptGate();
}
else if (choice4 == 2)
{
f2.changeDeptGate();
}
else
{
System.out.println("Invalid choice");
}
}
else if (choice == 5)
{
System.out.println("Exit Reached");
exit = true;
}
}

Use switch() statement for the choices for each case. Like
switch(x) {
case 1:
doSomething1();
case 2:
doSomething2();
case 3:
doSomething3();
}

Related

Output Problems of program

I would like to ask why the program prints already the answer? Even if I select on different Difficulty it is still the same.
import java.util.Scanner;
import java.util.Random;
public class GuessigGame {
public static int level(int y) {
Random ans = new Random();
int easy = 20, medium = 50, hard = 10, x;
Scanner in = new Scanner(System.in);
System.out.println("Choose Difficulty");
System.out.println("1. easy ");
System.out.println("2. medium ");
System.out.println("3. hard ");
x = in.nextInt();
switch (x) {
case 1:
System.out.println("Easy");
y = easy;
break;
case 2:
System.out.println("Medium");
y = medium;
break;
case 3:
System.out.println("Hard");
y = hard;
break;
default:
break;
}
return y;
}
public static void main(String[] args) {
int choice, difficulty = 0, answer = -1;
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.println("\n\n1. Play Game");
System.out.println("2. Exit");
System.out.println("");
choice = in.nextInt();
int diff = 0, tries = 0, triesbot = 0, trieshu = 0;
diff = level(difficulty);
difficulty = 1 + rand.nextInt(diff);
boolean win = false;
switch (choice) {
case 1:
while (win != true) {
System.out.println(difficulty);
System.out.println("Tries: " + tries);
answer = in.nextInt();
if (answer == difficulty + 1 || answer == difficulty - 1) {
System.out.println("so close");
} else if (answer == difficulty + 2 || answer == difficulty + 2) {
System.out.println("youre answer was close");
} else if (answer == difficulty + 3 || answer == difficulty - 3) {
System.out.println("try more youre close");
} else if (answer == difficulty + 4 || answer == difficulty - 4) {
System.out.println("try youre best buddy!");
} else if (answer > difficulty + 4 || answer < difficulty - 4) {
System.out.println("so far!");
} else if (tries == 0) {
System.out.print("Game Over!");
win = true;
} else if (answer == difficulty) {
System.out.println("You got the correct answer!!!!");
win = true;
} else {
}
tries++;
}
break;
default:
System.exit(0);
break;
}
}
}
This is the output of the program:
Because you told the computer to print out the difficulty. I suggest having better names.
difficulty = 1 + rand.nextInt(diff);
boolean win = false;
switch(choice) {
case 1:
while(win != true) {
System.out.println(difficulty);
System.out.println("Tries: " + tries);

Q : Doing multiple loops and multiple if-statements and if-else-statements || RENTAL CAR CALCULATOR PROJECT

my instructions on the project were as followed:
Instructions: Use a sentinel value loop. To create a basic Rental Car Calculator
Ask each user for:
Type of vehicle (May use something other than strings, such as: 1 for an economy, 2 for a sedan, etc.)
Days rented
Calculate the (For each customer):
Rental cost,
Taxes,
Total Due.
There are three different rental options with separate rates: Economy # 31.76, sedan # 40.32, SUV # 47.56. [Note: only whole day units to be considered (no hourly rates)].
Sales tax is = to 6% on the TOTAL.
Create summary data with:
Number of customers
Total money collected.
Also, Include IPO, algorithm, and desk check values (design documents).
{WHAT I HAVE GOING AND MY QUESTION(S)}
package tests;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Tester {
public static void main(String []args){
int count=0;
int days;
int cus = 10;
double DailyFee=0, NontaxTotal, CarType, Total,FullTotal=0;
boolean F1 = false, F2 = false, F3 = false;
Scanner in=new Scanner(System.in);
while (F3 == false) {
F3 = true;
System.out.print("Press 1 to enter Rental Calculator or else press 0 to quit\n");
System.out.println("Please only enter 1 or 0. Also, please only enter number(s) not letter(s)");
try {
cus=in.nextInt();
if (cus == 0 || cus == 1) {
F3 = true;
} else {
F3 = false;
System.out.println("Number must be either 1 or 0");
}
} catch (InputMismatchException ex) {
F3 = false;
System.out.println("Invalid entry");
in.next();
}
}
if(cus == 1) {
while(F1 == false) {
F1 = true;
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
//
try {
CarType = in.nextInt();
if (CarType <= 0 || CarType >= 4) {
System.out.print("Number must be 1-3\n");
System.out.println("Please enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
F1 = false;
} else {
if (CarType == 1) {
F1 = true;
DailyFee=31.76;
} else if(CarType == 2) {
F1 = true;
DailyFee=40.32;
} else if(CarType == 3) {
F1 = true;
DailyFee=47.56;
}
while (F2 == false) {
F2 = true;
try {
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = in.nextInt();
if (days <= 0) {
System.out.println("Number of days must be more than zero");
F2 = false;
} else {
double x=days;
NontaxTotal = (DailyFee * x);
Total = (NontaxTotal * 1.06);
FullTotal+=Total;
F3 = true;
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be a number");
F2 = false;
in.next();
}
}
}
} catch (InputMismatchException ex) {
F1 = false;
System.out.println("Answer must be a number");
}
}
}
in.close();
System.out.println("Count of customers : " + count);
System.out.printf("Total of the Day : $ %.2f", FullTotal);
}
}
{MY QUESTIONS}
When a letter is entered to the prompt "Press 1 to enter Rental Calculator or else press 0 to quit" it displays, an error prompt then the console asks for input again. Similarly, when a letter is inputted at the prompt "What vehicle would you like to rent?" the console continues to print lines with no stop? I do not know how to fix this?
I want my program to allow multiple calculation inputs to be made. However, after full calculation input (Days * Tax * Car Type) the console post summary data rather than looping?
2a. After the prompt "Please enter the number of days rented. (Example; 3) : " and following user input. How would I get my program to loop back to asking "Press 1 to enter Rental Calculator or else press 0 to quit"? with still making 0 prompt my summary data?
I have just "refactored" your code a bit, removed some obsolete code and placed some other code on other locations.
I've also used more clear naming for variables, and followed the naming conventions.
The problem you had, was that you did not in each catch block had a in.next(); meaning that while iterating, the variable kept using the same variable (which was invalid) so kept looping over the error messages.
Now this code is far from perfect, it can easily be improved still, but this should get you started.
package tests;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Tester {
public static void main(String []args){
int count=0;
int days;
int cus;
int carType;
double dailyFee=0, nonTaxTotal, total,fullTotal=0;
boolean checkRunOrQuit = false, chooseTypeVehicle = false, numberOfDAysChosen = false;
Scanner in=new Scanner(System.in);
while ( !checkRunOrQuit ) {
System.out.print("Press 1 to enter Rental Calculator or else press 0 to quit\n");
System.out.println("Please only enter 1 or 0. Also, please only enter number(s) not letter(s)");
try {
cus=in.nextInt();
switch ( cus ) {
case 0: System.out.println("End of application");
System.exit(0); // This will actually end your application if the user enters 0, no need to verify later on
break;
case 1: checkRunOrQuit = true;
break;
default:
System.out.println("Number must be either 1 or 0");
}
} catch (InputMismatchException ex) {
System.out.println("Invalid entry: ");
in.next();
}
}
while( !chooseTypeVehicle ) { // --> simplified comparison
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
try {
carType = in.nextInt();
chooseTypeVehicle = true;
switch ( carType ) {
case 1: dailyFee = 31.76;
break;
case 2: dailyFee = 40.32;
break;
case 3: dailyFee = 47.56;
break;
default:
System.out.print("Number must be 1-3\n");
System.out.println("Please enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
chooseTypeVehicle = false;
break;
}
} catch (InputMismatchException ex) {
System.out.println("Answer must be a number");
in.next(); // -> you forgot this one.
}
}
while ( !numberOfDAysChosen ) {
try {
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = in.nextInt();
if (days <= 0) {
System.out.println("Number of days must be more than zero");
} else {
nonTaxTotal = (dailyFee * days);
total = (nonTaxTotal * 1.06);
fullTotal+=total;
numberOfDAysChosen = true;
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be a number");
in.next();
}
}
in.close();
System.out.println("Count of customers : " + count);
System.out.printf("total of the Day : $ %.2f", fullTotal);
}
}
Here you go, i modified it a bit and put the whole thing in a while loop (while (cus != 0)) now it is working perfectly, try this code and do let me know if you have questions
package inter;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Inter {
public static void main(String []args){
int count=0;
int days;
int cus = 10; // added
double DailyFee=0, NontaxTotal, CarType, Total,FullTotal=0;
boolean F1 = false, F2 = false;
Scanner in=new Scanner(System.in);
while (cus != 0) {
while (true) {
System.out.println("If there are any customer press 1 else press 0");
try {
cus=in.nextInt();
if (cus == 0 || cus == 1) {
break;
} else {
System.out.println("Number must be either 1 or 0");
}
} catch (InputMismatchException ex) {
System.out.println("Invalid entry");
in.next();
}
}
if(cus == 1) {
while(F1 == false) {
F1 = true;
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
try {
CarType = in.nextInt();
if (CarType <= 0 || CarType >= 4) {
System.out.print("Number must be 1-3\n");
System.out.println("Please enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
F1 = false;
} else {
if (CarType == 1) {
F1 = true;
DailyFee=31.76;
} else if(CarType == 2) {
F1 = true;
DailyFee=40.32;
} else if(CarType == 3) {
F1 = true;
DailyFee=47.56;
}
while (F2 == false) {
F2 = true;
try {
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = in.nextInt();
if (days <= 0) {
System.out.println("Number of days must be more than zero");
F2 = false;
} else {
//days = in.nextInt();
double x=days;
NontaxTotal = (DailyFee * x);
Total = (NontaxTotal * 1.06);
FullTotal+=Total;
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be a number");
F2 = false;
in.next();
}
}
F2 = false;
}
} catch (InputMismatchException ex) {
F1 = false;
System.out.println("Answer must be a number");
in.next();
}
}
F1 = false;
}
}
System.out.println("Count of customers : " + count);
System.out.printf("Total of the Day : $ %.2f", FullTotal);
}
}

excess the limit of random numbers in java?

I am actually working on a jackpot game where it generates random numbers and asks user to guess the random number, if it meets the criteria it prints win and if not it moves to other conditional statements.
I have almost finished writing my code and just I got confused on this step. My query is:
I have set a limit a on randInt(max) i.e random numbers but I want to know that if it exceeds its limit, it must show a message which I can't help myself out.
Please share your ideas if anyone can.
public class Jackpot {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int mode;
System.out.println("Choose the difficulty level mode");
System.out.println("1: Easy (0-15)");
System.out.println("2: Medium (0-30)");
System.out.println("3: Difficult (0-50)");
System.out.println("or type another number to quit");
mode = input.nextInt();
if(mode == 1){
Start_Game(randInt(15));
}else if(mode == 2){
Start_Game(randInt(30));
}else if(mode == 3){
Start_Game(randInt(50));
}else if(mode <= 4 || mode >= 0){
System.out.println("Quit");
Restart_Game();
}
}
public static int randInt(int max){
int randomNum = (int) (Math.random() * ((max) + 1));
return randomNum;
}
public static int Start_Game(int max){
System.out.println("Please enter your guessed number");
int GuessNum , life = 5;;
do{
GuessNum = input.nextInt();
if(GuessNum == max){
System.out.println("You WIN");
break;
}else if(GuessNum > max){
System.out.println("BIG");
life--;
System.out.println("life: " + life);
}else if(GuessNum < max){
System.out.println("SMALL");
life--;
System.out.println("life: " + life);
}
}while(life != 0);
Restart_Game();
return 0;
}
public static void Restart_Game(){
System.out.println("if you want to restart the game \nPress Y to continue or N to exit");
char restart = input.next().charAt(0);
if(restart == 'Y' || restart == 'y'){
//Start_Game(randInt(10));
int mode;
System.out.println("Choose the difficulty level mode");
System.out.println("1: Easy (0-15)");
System.out.println("2: Medium (0-30)");
System.out.println("3: Difficult (0-50)");
System.out.println("or type another number to quit");
mode = input.nextInt();
if(mode == 1){
Start_Game(randInt(15));
}else if(mode == 2){
Start_Game(randInt(30));
}else if(mode == 3){
Start_Game(randInt(50));
}else if(mode <= 4 || mode >= 0){
System.out.println("Quit");
Restart_Game();
}
} else if(restart == 'n'|| restart == 'N'){
System.out.println("Thank you for playing");
System.exit(0);
}
}
private static int randIt(int max) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Your "Game" don't have a clue of the actual range, even if you have a parameter call "max", it is only the value to found, you could renamed it or you could really send the maximum value accepted :
Start_Game(15);
And let the game generate a random value based on that. You have the max value and the random value to found. Easy to check your case now.
public static int Start_Game(int max){
int toFind = randInt(max);
do{
GuessNum = input.nextInt();
if(GuessNum > max){
System.out.println("Out of range");
} else if(GuessNum == toFind ){
System.out.println("You WIN");
break;
}else if(GuessNum > toFind ){
System.out.println("BIG");
life--;
System.out.println("life: " + life);
}else if(GuessNum < toFind ){
System.out.println("SMALL");
life--;
System.out.println("life: " + life);
}
}while(life != 0);
}
Note : You should rename your method and variable, JAVA has a convention (like other language), don't name a variable starting with a uppercase for instance.
public static int startGame(int max){
or
int guessNum;

Java- Using if statement inside a loop

I wrote a small code :
System.out.println("Please enter a number");
int number = scan.nextInt();
if(number == 1) {
System.out.println("Number is 1");
} else if(number == 2) {
System.out.println("Number is 2");
} else {
System.out.println("Invalid selection");
}
When the user enters a number different than 1 and 2, user gets "Invalid selection" message and then code terminates. I don't want it to terminate, I want it to run again until user writes 1 or 2. I tried do-while loop but it become an infinite loop. What are your suggestions?
You can use while loop here
Scanner scanner = new Scanner(System.in);
boolean status = true;
while (status) { // this runs if status is true
System.out.println("Please enter a number");
int number = scanner.nextInt();
if (number == 1) {
System.out.println("Number is 1");
status=false; // when your condition match stop the loop
} else if (number == 2) {
System.out.println("Number is 2");
status=false;// when your condition match stop the loop
} else{
System.out.println("Invalid selection");
}
}
Try this...
int number;
do{
System.out.println("Please enter a number");
number = scan.nextInt();
if(number == 1)
{
System.out.println("Number is 1") ;
}
else if(number == 2)
{
System.out.println("Number is 2") ;
}
else
{
System.out.println("Invalid selection") ;
}
}while(number!=1 && number!=2);
I recommend you check if there is an int with Scanner.hasNextInt() before you call Scanner.nextInt(). And, that makes a nice loop test condition if you use it in a while loop.
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number");
while (scan.hasNextInt()) {
int number = scan.nextInt();
if (number == 1) {
System.out.println("Number is 1");
break;
} else if (number == 2) {
System.out.println("Number is 2");
break;
} else {
System.out.println("Invalid selection");
}
}
// ...
#Dosher, reposting #Raj_89's answer with correction in while loop condition. Please notice While loop condition
int number = 0;
do{
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
number = scan.nextInt();
if(number == 1)
{
System.out.println("Number is 1") ;
}
else if(number == 2)
{
System.out.println("Number is 2") ;
}
else
{
System.out.println("Invalid selection") ;
}
}while(number==1 || number==2);

Exception in thread "main" after program runs

My program is a game to determine how many legs a certain animal (dog/chicken/fish) has.
Every time I run the program, I get an error message:
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at AnimalGame.main(AnimalGame.java:67)".
I can't find the problem. Also, I want the program to end after it says "You win!" or "You lose!", but each time it says one of those outputs, it then says
"I don't know that animal. Do you want to try again? (y/n)"
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char n = 0;
char y = 0;
char gameAnswer = 'n';
do
{
System.out.println("Choose an animal: ");
String text = input.nextLine();
switch (text) {
case "dog":
System.out.println("How many legs does a dog have?");
int dg = input.nextInt();
if(dg == 4)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
case "chicken":
System.out.println("How many legs does a chicken have?");
int chkn = input.nextInt();
if(chkn == 2)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
case "fish":
System.out.println("How many legs does a fish have?");
int fsh = input.nextInt();
if(fsh == 0)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
default:
break;
}
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
gameAnswer = input.nextLine().charAt (0);
}while(gameAnswer == 'y');
}
There were a few problems, main one was that when the user enters the number of legs he presses "enter" which adds a newline character right after the int, but since only the int is being read, the newline is being buffered and used on the next read which messes up everything.
The solution to that is to add a readLine() at the end of each case just before the break.
Another issue was that the line:
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
was always printed regardless if the animal was known or not. For that - an addition of a known boolean parameter fixed the issue:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char gameAnswer = 'y';
do {
System.out.println("Choose an animal: ");
String text = input.nextLine();
boolean known = false;
switch (text) {
case "dog":
System.out.println("How many legs does a dog have?");
int dg = input.nextInt();
if (dg == 4) {
System.out.println("You win!");
} else {
System.out.println("You lose!");
}
known = true;
input.nextLine();
break;
case "chicken":
System.out.println("How many legs does a chicken have?");
int chkn = input.nextInt();
if (chkn == 2) {
System.out.println("You win!");
} else {
System.out.println("You lose!");
}
known = true;
input.nextLine();
break;
case "fish":
System.out.println("How many legs does a fish have?");
int fsh = input.nextInt();
if (fsh == 0) {
System.out.println("You win!");
} else {
System.out.println("You lose!");
}
known = true;
input.nextLine();
break;
default:
break;
}
if (!known) {
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
String tmp = input.nextLine().trim();
if (!tmp.isEmpty()) {
gameAnswer = tmp.charAt(0);
}
}
} while (gameAnswer == 'y');
}
Now that we have the code working, it might be a good idea to do some refactoring. I took a few steps and it could probably be improved even further:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char gameAnswer = 'y';
do {
System.out.println("Choose an animal: ");
String text = input.nextLine();
boolean known = getLegs(input, text);
if (!known) {
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
String tmp = input.nextLine().trim();
if (!tmp.isEmpty()) {
gameAnswer = tmp.charAt(0);
}
}
} while (gameAnswer == 'y');
}
private static boolean getLegs(Scanner input, String animal) {
boolean known = identifyAnimal(animal);
if (known) {
System.out.printf("How many legs does a %s have?\n", animal);
int legs = input.nextInt();
if (checkDog(animal, legs) || checkChicken(animal, legs) || checkFish(animal, legs)) {
System.out.println("You win!");
} else {
System.out.println("You lose!");
}
/*
known = true;
input.nextLine();
*/
return; // since the OP stated in the comments that he wants the code to exit here.
}
return known;
}
private static boolean identifyAnimal(String animal) {
return "dog".equals(animal) || "chicken".equals(animal) || "fish".equals(animal);
}
private static boolean checkDog(String animal, int legs) {
return legs == 4 && "dog".equals(animal);
}
private static boolean checkChicken(String animal, int legs) {
return legs == 2 && "chicken".equals(animal);
}
private static boolean checkFish(String animal, int legs) {
return legs == 0 && "fish".equals(animal);
}

Categories

Resources