I want to force the user to select choice 1 before they can proceed and select choice 2 any help would appreciated.
(note I've only done if,switch,while,for,do....while,methods and arrays in java so far)
Scanner sc = new Scanner(System.in);
int[] ages = new int[3];
int choice;
do {
System.out.println("Average Age program");
System.out.println("Enter 1 to enter ages");
System.out.println("Enter 2 to calculate the average Age");
System.out.println("Enter 0 to Exit");
choice = sc.nextInt();
switch(choice) {
case 1:
acceptAges(ages);
break;
case 2:
averageAge(ages);
break;
default:
System.out.print("invalid option");
}
} while(choice != 0);
}
You could simply not display choice 2 until 1 was chosen at least once.
Scanner sc = new Scanner(System.in);
int[] ages = new int[3];
int choice;
boolean is2Enabled=false,
do{
System.out.println("Average Age program");
System.out.println("Enter 1 to enter ages");
if(is2Enabled)
System.out.println("Enter 2 to calculate the average Age");
System.out.println("Enter 0 to Exit");
choice=sc.nextInt();
switch(choice)
{
case 1:
acceptAges(ages);
is2Enabled=true;
break;
case 2:
if(is2Enabled)
averageAge(ages);
else
System.out.print("invalid option");
break;
default:
System.out.print("invalid option");
}
}while(choice != 0);
}
Related
I am new to Java and learning. I am making a looping menu in Java. But when I select "a" and enter the details it doesn't go back to the menu.
I have done a bit of research and I need to add a Do and While loop here, but I'm confused on how to implement that here. A bit of guidance is extremely appreciated
Heres my code below:
switch(selection) {
case 'A':
case 'a':
System.out.print("Enter a Trip Date: ");
date = input.nextLine();
System.out.print("Enter Trip Point: ");
enter_point = input.nextLine();
System.out.print("Enter Exit Point: ");
exit_point = input.nextLine();
break;
case 'B':
case 'b':
System.out.print("Enter Breakdown Date: ");
breakdown = input.nextLine();
System.out.print("Enter Sector Breakdown Occured in: ");
sector_break = input.nextInt();
System.out.print("Enter Vehicle Recovery Cost: ");
rec_cost = input.nextDouble();
break;
case 'x':
case 'X':
System.out.println("Exiting data entry menu..");
break;
//equivalent to an else
default:
System.out.println("ERROR! - Please Enter a Valid Selection!");
}
while(selection != 'X');
Is this what you needed?
char selection;
do
{
do
{
//Menu
System.out.println("Toll Road Data Entry Menu");
System.out.println("-----------------------------------------");
System.out.println("A - Record Trip");
System.out.println("B - Record Breakdown Incident");
System.out.println("X - Exit");
System.out.print("Enter Your Selection: ");
selection = input.nextChar();
if (selection!='a' || selection!='A' || selection!='b' || selection!='B' || selection!='x' || selection!='X')
{
System.out.println("Selection must be a single character, A,B or X");
continue;
}
else
break;
} while (1);
switch(selection)
{
case 'A':
case 'a':
System.out.print("Enter a Trip Date: ");
date = input.nextLine();
System.out.print("Enter Trip Point: ");
enter_point = input.nextLine();
System.out.print("Enter Exit Point: ");
exit_point = input.nextLine();
break;
case 'B':
case 'b':
System.out.print("Enter Breakdown Date: ");
breakdown = input.nextLine();
System.out.print("Enter Sector Breakdown Occured in: ");
sector_break = input.nextInt();
System.out.print("Enter Vehicle Recovery Cost: ");
rec_cost = input.nextDouble();
break;
case 'x':
case 'X':
System.out.println("Exiting data entry menu..");
break;
//equivalent to an else
default:
System.out.println("ERROR! - Please Enter a Valid Selection!");
}
} while(selection != 'X');
I usually through them in while loops that way it just through me back to main menu when done
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
boolean menu=true;
int selection,sector_break;
String date,enter_point,exit_point,
breakdown;
double rec_cost;
while(true)
{
System.out.print(String.format("\033[2J"));
System.out.print("Your Menu Title \n\n");
System.out.print("1. Selection A\n");
System.out.print("2. Selection B\n");
System.out.print("3. Selection C\n");
System.out.print("4. Selection D\n");
System.out.print("5. Exit Menu D\n");
selection = Integer.parseInt(input.nextLine());
if(selection<1 || selection>4)
return;
switch(selection){
case 1:
System.out.print("Enter a Trip Date: ");
date = input.nextLine();
System.out.print("Enter Trip Point: ");
enter_point = input.nextLine();
System.out.print("Enter Exit Point: ");
exit_point = input.nextLine();
break;
case 2:
System.out.print("Enter Breakdown Date: ");
breakdown = input.nextLine();
System.out.print("Enter Sector Breakdown Occured in: ");
sector_break = input.nextInt();
System.out.print("Enter Vehicle Recovery Cost: ");
rec_cost = input.nextDouble();
break;
case 3:
// your code here
default:
// your code here
}
}
}
}
In this class of Bank ,there are basic functions of Bank , however the real problem is in the switch case loop.
class Bank{
private int Balance;
private int Withdrawal;
private int Deposit;
private int AccountNumber;
void Transaction(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the account number to whose account you want
to transfer money");
AccountNumber = input.nextInt();
System.out.println("Enter your current Balance");
Balance= input.nextInt();
}
void Display(){
System.out.println("Account number "+AccountNumber);
System.out.println("Balance is "+ Balance);
}
void deposit(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount to deposit");
int n =input.nextInt();
Balance+=n;
}
void withdraw(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount to withdraw");
int n =input.nextInt();
try {
if(n>Balance)
throw new Exception("The balance you have is insufficient");
}
catch(Exception e){
System.out.println(e);
}
}//void
I am trying to rerun the switch case loop, after inputing one value , i want it to ask user again all the options, i tried to use continue statement , but it shows error of continue outside the loop.Please help
public static void main(String args[])throws Exception{
Bank b1=new Bank();
Scanner input = new Scanner(System.in);
System.out.println("Enter the number corrosponding to your option ");
System.out.println("1 Set ");
System.out.println("2 Display ");
System.out.println("3 Deposit");
System.out.println("4 Withdraw");
System.out.println("5 Exit");
int num=input.nextInt();
switch(num){
case 1:
b1.Transaction();
//int c =input.nextInt();
//wants user to input value again so switch loop works
//again
break;
case 2:
b1.Display();
break;
case 3:
b1.deposit();
break;
case 4:
b1.withdraw();
break;
case 5:
return;
}
}//psvm
}
You could surround the switch in a
do{
int num=input.nextInt();
switch(num){
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
return;
}
}while(num!=some_value_to_exit_switch);
}
}
I'd place the switch content in a while loop with a boolean flag, then it will re-run until you are satisfied with the input~
For some reason when I run my code on eclipse there is nothing showing on the screen like it should. I'm not sure what it is. I can type input into the console but that is about it. Nothing else happens. Can anyone tell me what it could be? Thanks.
import java.util.Scanner;
public class Test {
public static void main (String [] args) {
Scanner input = new Scanner (System.in);
Flight flight = new Flight (input.nextLine(), input.nextLine(), input.nextLine(), input.nextLine(), 0);
System.out.println("Creating first flight");
System.out.println("What is the name of the flight?");
String flightName = input.nextLine();
System.out.println("What is the destination of the flight?");
String destination = input.nextLine();
System.out.println("What is the departure time of the flight?");
String departureTime = input.nextLine();
System.out.println("What is the departure gate of the flight?");
String departureGate = input.nextLine();
boolean done = false;
while (!done) {
System.out.println("Now what would you like to do?");
System.out.print("1. Print out a flight's info");
System.out.print("2. Print out the number of flights through the static variable.");
System.out.print("3. Change the departure time of a flight.");
System.out.print("4. Change the departure gate of a flight.");
System.out.print("5. Exit");
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Which flight would you like to print the info of (1 or 2)?");
int selection = 0;
selection = input.nextInt();
if (selection == 1 || selection == 2) {
Flight.printFlight();
} else{
System.out.println("Invalid Option");
} break;
case 2:
System.out.println("This is the number of flights" + Flight.getNumFlights());
break;
case 3:
System.out.println("Which flight would you like to change the departure time of (1 or 2)?");
int selection2 = 0;
selection2 = input.nextInt();
if (selection2 == 1 || selection2 == 2){
System.out.println("What is the new departure time for flight " + (Flight.getNumFlights()-1));
String newDeptTime = input.nextLine();
Flight.changeDeptTime(newDeptTime);
} else{
System.out.println("Invalid Option");
} break;
case 4:
System.out.println("Which flight would you like to change the departure gate of?");
int selection3 = input.nextInt();
if (selection3 == 1 || selection3 == 2){
System.out.println("What is the new departure gate for flight " + Flight.getNumFlights());
String newDeptGate = input.nextLine();
Flight.changeDeptGate(newDeptGate);
} else {
System.out.println("Invalid option");
} break;
case 5:
done = true;
break;
default:
System.out.println("Invalid option");
break;
}
}
}
}
its not showing anything because it is waiting for you to enter characters you want in the Flight class constructor.
As you can see here
Flight flight = new Flight (input.nextLine(), input.nextLine(), input.nextLine(), input.nextLine(), 0);
execution stops at the input.nextLine() parts till you enter something and hit enter
P.S : its better to place some System.out.println("enter the value") kind of statement before the input parts to show the user what to do.funny doing this will prevent you from making this mistake you made
when user logs out the user may choose to log back in again. For Logging back in: If the user get the pin code wrong 3 times, the program terminates.
System.out.println("You have logged out");
System.out.print("Please Enter Pin: ");
pin2 = sc.nextInt();
while (pin != pin2){
while (ctr < 2){
System.out.print("Please Enter Pin: ");
pin2 = sc.nextInt();
ctr++;
}
}
If I understand your problem correctly you will want to have something like that:
while (pin == pin2) {
System.out.println("What would you like to do?");
System.out.println("1 - Check Balance");
System.out.println("2 - Deposite");
System.out.println("3 - Withdraw");
System.out.println("4 - Change Pin");
System.out.println("5 - End Transaction");
sel = sc.nextInt();
switch (sel) {
case 1:
System.out.println("Your current balance is " + bal);
break;
case 2:
System.out.println("How much would you want to deposite? ");
dep = sc.nextInt();
bal = dep + bal;
System.out.println("Your new current balance is " + bal);
break;
case 3:
System.out.println("How much would you want to Withdraw? ");
with = sc.nextInt();
if (with > bal) {
System.out.println("You do not have that amount on your account! Please enter again.");
} else {
System.out.println("You withdrew " + with);
bal = bal - with;
System.out.println("Your new current balance is " + (bal));
}
break;
case 4:
System.out.print("Please enter a new pin: ");
pin = sc.nextInt();
System.out.println("Please verify your new pin: ");
pin2 = sc.nextInt();
break;
case 5:
System.out.println("Please Enter Pin: ");
pin = sc.nextInt();
break;
default:
break;
}
}
Basically, I've deleted the loop label, it is not necessary and I consider it a bad style. I've also changed the while condition, so the program runs as long as user enters exactly the same pin as he confirmed at the beginning. Moreover, I think it is better to read the value of sel after printing instructions, not before as you did.
Like what been said in the comments, avoid using Labels and/or goto rep.
Use something like that :
import java.util.Scanner;
public class AtmMachine {
public static void main(String[] args){
int actualPin = -1;
int sel = 0, pin, pin2, check, ctr = 0, dep, with, bal = 10000;
Scanner sc = new Scanner(System.in);
while(actualPin == -1)
{
System.out.print("Please enter a new pin: ");
pin = sc.nextInt();
System.out.print("Please verify your new pin: ");
pin2 = sc.nextInt();
if(pin == pin2) actualPin = pin;
else System.out.println("Error");
}
boolean logged = false;
while (true){
if(logged){
System.out.println("What would you like to do?");
System.out.println("1 - Check Balance");
System.out.println("2 - Deposite");
System.out.println("3 - Withdraw");
System.out.println("4 - Change Pin");
System.out.println("5 - End Transaction");
sel = sc.nextInt();
switch (sel){
case 1:
System.out.println("Your current balance is "+ bal);
break;
case 2:
System.out.println("How much would you want to deposite? ");
dep = sc.nextInt();
bal= dep+bal;
System.out.println("Your new current balance is "+ bal);
break;
case 3:
System.out.println("How much would you want to Withdraw? ");
with = sc.nextInt();
if(with > bal){
System.out.println("You do not have that amount on your account! Please enter again.");
}
else{
System.out.println("You withdrew "+ with);
bal = bal-with;
System.out.println("Your new current balance is "+ (bal));
}
break;
case 4:
System.out.print("Please enter a new pin: ");
pin = sc.nextInt();
System.out.println("Please verify your new pin: ");
pin2 = sc.nextInt();
if(pin == pin2) actualPin = pin;
else System.out.println("Error");
break;
case 5:
logged = false;
break;
default:
break;
}
else{
System.out.println("Please Enter Pin: ");
sel = sc.nextInt();
logged = actualPin == sel;
}
}
}
}
I need to check users input. I have a menu and I need the user to select numbers 0-4 but if the user selects a letter instead of a number then I just get a InputMismatchException. So I am trying to validate that the user entered a number. Here is my code:
public class TestBankAccount {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
ArrayList<BankAccount> list = new ArrayList<BankAccount>();
int choice;
do {
System.out.println("1. Deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.println("4. Create new account");
System.out.print("Your choice, 0 to quit: ");
choice = input.nextInt();
switch (choice) {
case 1:
depositMoney(list);
break;
case 2:
withdrawMoney(list);
break;
case 3:
checkBalance(list);
break;
case 4:
createNewAccount(list);
break;
case 0:
System.out.println("Thank you for trusting us with your banking needs!");
break;
default:
System.out.println("Invalid option is selected!");
}
System.out.println();
} while (choice != 0);
if (list.size() > 0) {
displayResults(list);
}
}
I was thinking to do something like while (choice != 0 && choice != input.hasNextInt()); but I get an error. Any ideas?
You can do somehting like this :
int choice = 0 ;
try{
choice = Integer.parseInt(input.next());
}
catch(NumberFormatException e)
{
System.out.println("invalid value enetered");
}
// Now you can check if option selected is between 1 & 4
// and throw some custom exception
Either catch the exception and handle it, or instead of Scanner use
(char) System.in.read();
to receive characters. In this way you can avoid handling exceptions, which takes a lot of time. You can work on chars instead of integers then or check their validity and convert them to integers in this way:
int x = Character.getNumericValue(choice);
Just wrap it in a try catch
do{
try{
System.out.println(choices)
choice = input.nextInt()
switch(choice){
....
}
}
catch(InputMismatchException){
System.out.println("Please enter a valid input")
}
}
while(whatever)
I found the answer out. This is how I would validate the account number's.
int number;
while(true){
System.out.print("\nEnter account number: ");
try{
number = input.nextInt();
break;
}catch(Exception e){
System.err.println("Error: Invalid Entry! Please try only Integers");
input=new Scanner(System.in);
}
}
and this is how I would validate the menu item selected is a number and not a letter:
int choice = 0;
do {
while(true)
{
System.out.println("1. Deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.println("4. Create new account");
System.out.print("Your choice, 0 to quit: ");
try{
choice = Integer.parseInt(input.next());
break;
}
catch(Exception e){
System.err.println("Error: Invalid entry! Please Try Again!");
input=new Scanner(System.in);
continue;
}
}