Java - Accessing object created in different 'if/else if' statement? - java

I'm currently working on a project (a very simple makeshift bookstore) where I have two classes (one for managing a User Account and one functioning as a driver class), in which a menu is presented to the user via the main method of the driver class. This menu, as per the project specifications, is represented by a while loop in which the user types a single character corresponding to one of several menu options. Within this while loop is a series of if/else if statements, with each of these statements containing the code for one of the menu options. These menu options are as follows:
Main Menu:
N - Create account
L - Load money into your account balance
O - Order a book
S - Print an account summary
X - Quit
The purpose of the while loop, I presume, is to keep cycling back to the main menu after the user works through the various sub-menus, ending only when the user input is "X".
When the user input is "N" and the 'Create account' menu is launched, the following code is executed:
if(menuInput == 'N') {
// Scanner sc has already been declared at top of main method
System.out.println("Enter your desired username:");
in_userName = sc.next();
// String in_userName has already been declared at top of main method
System.out.println("Enter a starting balance:");
in_initBal = sc.nextDouble();
// double in_initBal has already been declared at top of main method
UserAccount user = new UserAccount(in_userName,in_initBal);
accountCheck = true;
/* accountCheck is a boolean that makes sure an account has been
created; it has already been declared/initialized to 'false'
prior to the while loop
*/
}
The only other menu option in the driver class I've programmed so far is 'L - Load money into your account balance'. The code for this menu option is as follows:
else if(menuInput == 'L') {
if(accountCheck == false) {
System.out.println("You must create an account first. Enter N
to create one.");
}
else {
System.out.println("Enter the amount to add:");
in_amountToAdd = sc.nextDouble();
// double in_amountToAdd has already been declared at top of main method
user.addToBalance(in_amountToAdd); /* Method in the User Account class
that takes a double parameter and
adds it to the existing balance.
*/
System.out.println(user.getBalance());
}
The problem is that the user.addToBalance(in_amountToAdd) and System.out.println(user.getBalance()) lines don't compile, because "user cannot be resolved". I created the constructor in the if statement corresponding to the 'Create account' option but don't know how to implement it in other if/else if blocks, so I was wondering if there is a way for me to either:
Get the if statement for the 'Load money into account' sub-menu to recognize the "user" constructor from the 'Create account' sub-menu, so that the code I've included here will compile, or:
Initialize the "user" constructor at the beginning of the main method, and then change/update its argument parameters to the input values from the scanner later on.
My thought process for number two on the above list is that declaring/initializing the constructor before the while loop would allow each if/else if block to see it, whereas it seems only the 'Create account' block can see it as of right now (I'm guessing this is because the constructor was created here and is local to just this particular if statement).
I apologize in advance if any of the terminology I've used is wrong or inaccurate, and if any of my code is confusing/impractical. I am just a beginner, so I'd appreciate it if you guys would point out any mistakes I've made to serve as a learning experience for me.
Thanks!

You need to declare the variable before the while loop and the if-else
e.g.
UserAccount user = null;
while (...) {
if (...) {
user = new UserAccount(in_userName,in_initBal);
}
else {
user.addToBalance(in_amountToAdd);
}
}

You can declare UserAccount user before your While loop.
UserAccount user = null;
// while not "Exit"
while (menuInput != 'X') {
if (menuInput == 'N') {
user = new UserAccount(in_userName,in_initBal);
}
else if(menuInput == 'L') {
// check if UserAccount is created
if (user != null) {
user.addToBalance(in_amountToAdd);
}
}
.....
}
With this, you can eliminate accountCheck boolean variable, as similar check can be done to check whether user is null.

Related

Call upon method from user input

I am currently working on a project and I have been asked to create a puzzle type game based on a 2d array. I have created the methods which all work fine, but I dont quite know how to make it so that the user can call upon the methods via user input whilst the program is running.
I'd prefer not to upload my code as this is quite a big class and I don't want other class members to find this and copy my code.
Thanks :-)
Try a simple menu loop like this:
// scanner created outside the loop because it will be used every iteration
Scanner s = new Scanner(System.in);
while(true) {
System.out.print("Please choose an option: ");
// read some input and trim the trailing/ leading whitespaace
String input = s.nextLine().trim();
// check to see which move was called
if (input.equals("foo")) {
foo();
}
else if (input.equals("bar")) {
bar();
}
// break out of the menu loop
else if (input.equals("exit")) {
break;
}
// if none of the above options were called
// inform user of invalid input
else {
System.out.println("Invalid input");
}
}
// exit program
System.out.println("Goodbye!");
Just add in options as you need them
You can use GUI or console to give your command to your apllication for execution those methods.
offtop
this is quite a big class
I think you should divide one big class to some smaller classes(less them 100 lines).

Looping through Arrays in Java

I am trying to write a program to simulate an airline reservation system. I an supposed to use an array of type boolean to represent the number of seats. First five seats represent first class and last five represent economy. Initially the program must allow the user to make a choice between first class and economy and then his choice is processed as follows:
A user can only be assigned an empty seat in the class he chooses.
Once a class is full, the user is offered the option to move to the next class
If the user agrees to move to the next class a simple boarding pass is printed.
If the user refuses to move to the next class. The time for the next flight is displayed. i would appreciate help on how to loop through the elements of the array to determine whether its true of false. Also i am trying to display the number of seats available in each class before the user makes a selection this is what i've written so far.. My code is far from complete, i acknowledge that, i am a novice programmer please help. Thank you.
import java.util.Scanner;
public class AirlineReservation
{
private boolean[] seats =; // array to hold seating capacity
private String AirlineName; // name of airline
private int[] counter = new int[5]
// constructor to initialize name and seats
public Airline(String name, boolean[] capacity )
{
AirlineName = name;
seats = capacity;
} // end constructor
// method to set the Airline name
public void setName( String name )
{
AirlineName = name; // store the course name
} // end method setCourseName
// method to retreive the course name
public String getName()
{
return AirlineName;
} // end method getName
// display a welcome message to the Airline user
public void displayMessage()
{
// display welcome message to the user
System.out.printf("Welcome to the Self-Service menu for\n%s!\n\n",
getName() );
} // end method displayMessage
// processUserRequest
public void processUserRequest()
{
// output welcome message
displayMessage();
// call methods statusA and StatusB
System.out.printf("\n%s %d:\n%s %d:\n\n",
"Number of available seats in First class category is:", statusA(),
"Number of available seats in Economy is", statusB() );
// call method choice
choice();
// call method determine availability
availability();
// call method boarding pass
boardingPass();
} // end method processUserRequest
public int statusA()
{
for ( int counter = 0; counter <= (seats.length)/2; counter++ )
} // revisit method
// method to ask users choice
public String choice()
{
System.out.printf(" Enter 0 to select First Class or 1 to select Economy:")
Scanner input = new Scanner( System.in );
boolean choice = input.nextBoolean();
} // end method choice
// method to check availability of user request
public String availability()
{
if ( input == 0)
System.out.printf("You have been assigned seat number \t%d", seats[ counter ]);
else
System.out.printf("You have been assigned seat number \t%d", seats[ counter ]);
}
}
#Anthony : As you are novice, hence please look at following comments :
1. Be specific while asking your question. In this case the question was "how to loop through array!". You posted complete problem statement.
2. Please google it or research it properly on internet if similar question has been asked by anybody before. In this case, similar question can be find here :
Iterate through string array in Java
Because of these reasons people are giving your query downvote!
Now just want to provide answer to your question as you look quite new to programming :
boolean flag[] = {true,false,true,false};
for(int i=0;i<flag.length;i++){
System.out.println(flag[i]);
}
I hope it helps!

Using another class in java to input an option.

Please help me with this: I want to create a Library System java program in which in the main class, I will let the user enter a choice.
======= LIBRARY SYSTEM =======
1. BORROW A BOOK
2. RETURN A BOOK
3. BROWSE CATEGORIES
4. EXIT
==============================
ENTER YOUR CHOICE HERE :
then I will create a sub class for each choices above.
For example, inside my class for the choice number 1, I have the same options from the main class.
========= LIBRARY SYSTEM ========
1. ENTER BOOK CODE
2. BACK TO MAIN MENU
=================================
ENTER YOUR CHOICE HERE:
I want my subclass to go back to the main class when the user enters choice number 2.
sorry newbie here. Thank you!
Let's say that your main class is called MainClass and the other class is called BorrowBook. In BorrowBook, create a method that returns an int:
public static int promptUser () {
//you can print some lines here
//get the user input
int input = //however you want to get the input
return input;
}
Now in your main class, check if the user enters 2 using the promptUser method:
int response = BorrowBook.promptUser ();
if (response == 2) {
//call some method to display the main menu
} else if (response == 1) {
//call some method in the BorrowBook do whatever when the user enters 1
}
See? The idea is that you need to create different methods for different stuff. displayMainMenu, promptUser, promptBookCode etc. Don't just put all the stuff in the main method. This decreases maintainability and the level of abstraction.

Validating a user's String type 'menu choice'

An assignment we were given recently had us building a basic, console-based, 'Tax Calculator', as it is something that got us to implement the things we'd learnt so far - variables, constants, loops etc.
One part of it had us present the user with a menu, where they would enter a letter - be it a,b,c,d or x - depending on what they wanted to do next.
That was no drama, as our assignment didn't ask for us to account for what happened if a user entered a choice not on the menu.
Now, for my own personal interest, I went back to it today, wanting to put some validation in there.
I defined the 'menuChoiceRule':
(menuChoice being a String)
boolean menuChoiceRule = (menuChoice.equalsIgnoreCase("A"))
|| (menuChoice.equalsIgnoreCase("B"))
|| (menuChoice.equalsIgnoreCase("C"))
|| (menuChoice.equalsIgnoreCase("D"))
|| (menuChoice.equalsIgnoreCase("X"));
And here is what should happen for as long as the rule is being broken: (The program should keep asking until it gets something that is in keeping with the rule, and then stop asking)
while (menuChoiceRule == false) {
System.out.print(menuChoiceString);
System.out.print("Enter Your Selection");
menuChoice = SCANNER.nextLine();
}
And what happens if the user is doing the right thing:
// As long as the user input is 'A','B','C' or 'D', they'll be able to
// keep doing stuff.
while (menuChoiceRule == true) {
*All the various menu options go here*
}
At the moment the while(menuChoiceRule == true) block (is that the right term?) works fine but while(menuChoiceRule == false) does not; Once the user inputs something that is in violation of the menuChoiceRule, the loop repeats endlessly no matter what is input (inputted?)
If someone could provide some insight as to why I'm having trouble here, it'd be much appreciated.
Regards,
AUS_Doug.
Looks like the boolean test is not being changed within the loop, place the code again at the bottom of the while loop.
Also, boolean tests do not need the ==, while(menuChoiceRule){ ... is the preferred coding style.
I would also consider creating a method to test for your rule:
private boolean testChoice(String menuChoice) {
return ((menuChoice.equalsIgnoreCase("A"))
|| (menuChoice.equalsIgnoreCase("B"))
|| (menuChoice.equalsIgnoreCase("C"))
|| (menuChoice.equalsIgnoreCase("D"))
|| (menuChoice.equalsIgnoreCase("X")));
}
This would give rise to the code:
boolean validChoice = false;
while (!validChoice) {
System.out.print(menuChoiceString);
System.out.print("Enter Your Selection");
menuChoice = SCANNER.nextLine();
validChoice = testChoice(menuChoice);
}

Search for accounts using for loops and if statements

I'm having a problem with my program. Currently, I'm making a billing account system.
Basically, I've got a great deal of the system up and running. As a feature, rather than having a user remember their position in an array, a user could carry out actions for their account by entering their account number. So, in other words, they would be prompted to enter an account number and any actions are attributed to that account.
Here is the code I have so far:
intEntry = input.nextInt();
for (count = 0; count <= ACCLIMIT; count++)
{
if (intEntry == NewAccount[count].getAccRefNo() )
{
intSelectedEntry = count;
}//end of if statement
else
{
System.out.println("Invalid ID!");
}//end of else statement
}//end of loop
System.out.println("*******Please enter the amount you wish to deposit*******") ;
valDeposit = getBalanceValidation();
parDepositAmount = Double.valueOf(valDeposit).doubleValue ();
NewAccount[intSelectedEntry].deposit(parDepositAmount);
When I run it, it crashes once I enter the ID number intEntry. It says the error is in the line of the if statement criteria, if that helps.
Please be aware I'm really new to Java, and I'd really appreciate this help explained in a simple way. (Thanks!)
Here is the error message:
Exception in thread "main" java.lang.NullPointerException
at pkgGasAccount.UsingBusinessAccount.main(UsingBusinessAccount.java:106)
Java Result: 1
Line 106 is the first line of the if statement (the criteria)
NewAccount[count] is null.
You should check that NewAccount[count] != null:
if (NewAccount[count]!= null && intEntry == NewAccount[count].getAccRefNo() )
But if you don't expect null values there, I suggest you to check why this happens.
NullPointerException is being thrown, hence I can say that your code is trying to access an array that is not defined or either pointing to a null value (default)
Since there is just one array NewAccount[], hence I would check the declaration of the same.

Categories