Using another class in java to input an option. - java

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.

Related

How would I use user input to prompt the user to play different games in java?

I am creating a program for class; the program needs to be able to play 4 games depending on which one the user chooses. If the user chooses game1; then the user would play game1, if the user chooses game2, then the user would play game2 etc..
I am trying to figure out how to create a method depending on which game the user wants to play. For example, if the user wants to play game1, I would create a playGame1 method that has the instructions to play game1.
If there is a better way to make it happen, please let me know, Thanks!
So far i'm trying to get user input which creates an if statement that leads the user to play.
import java.util.Scanner;
public class Attendant
{
public Attendant()
{
Scanner input = new Scanner(System.in);
String choice = input.next();
System.out.println( " Which game would you like to play? game1 ; game2 ; game3 ; game4 ");
if (choice.equalsIgnoreCase ( "game1"))
{
}
if (choice.equalsIgnoreCase ( "game2"))
{
}
if (choice.equalsIgnoreCase ( "game3"))
{
}
if (choice.equalsIgnoreCase ( "game4"))
{
}
}
}
Consider using switch statements
switch (choice) {
case "game1":
//gameInstructions go here
break;
...
default:
//this will be used when user will provide invalid input (like for ex. "gaem1" (mistype)
}
this code above will handle your user's game selection, remember to put break; to stop code going further than you want.

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

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.

OOP Ticket Price Program

So this one is a bit lengthy. I'm trying to finish off a program where ticket price varies depending on purchase date. I need the Tester.Java to take the info from the objects, and output the proper price depending on the ticket type. I have already set a set of if statements in the Tester, but I am now at an impass on how to finish this program off. I will paste my code below.
Tester (contains the main method):
package tester;
import java.util.Scanner;
public class Tester extends Ticket{
/**
* #param args the command line arguments
*/
public static void main(String[] args){
Scanner db = new Scanner(System.in);
Ticket firstTicket = new Ticket();
System.out.println("The first ticket: "+firstTicket.toString());
int x = 0;
while(x!=2){
if(x==2){
System.out.println("Goodbye.");
}
else{
System.out.println("What type of ticket are you purchasing?");
System.out.println("1.Walk Up");
System.out.println("2.Advance");
System.out.println("3.Student Advance");
int t = db.nextInt();
if(t==1){
}
if(t==2){
}
if(t==3){
}
}
System.out.println("Do you need another ticket?");
x= db.nextInt();
}
}
}
Ticket (Super class):
package tester;
import java.util.Scanner;
public class Ticket {
public int ticket;
public double price;
/**
* holds default values for ticket number and price
*/
public Ticket(){
super();
this.ticket=1;
this.price=15.0;
}
/**
* Stores the values for ticket number and the price, based upon ticket type
* #param ticket
* #param price
*/
public Ticket(int ticket, double price){
this.ticket=ticket;
this.price=price;
}
/**
* returns the value of price
* #return price
*/
public double getPrice(){
return price;
}
#Override
public String toString(){
return "Ticket #" + ticket + " Ticket price: $"+ price;
}
}
Walkup Ticket:
package tester;
/**
*
* #author dylan
*/
public class WalkupTicket extends Ticket{
/**
* holds the price of a walkup ticket 50$
*/
public WalkupTicket(){
this.price=50;
ticket++;
}
}
Advance Ticket:
package tester;
import java.util.Scanner;
public class AdvanceTicket extends Ticket {
/**
* stores the values of an advance ticket, depending on how many days before
* the event it is purchased
*/
public AdvanceTicket(){
Scanner db = new Scanner(System.in);
System.out.println("How many days before the event are you purchasing your ticket?");
int days = db.nextInt();
// days before is 10 or less days
if(days >= 10){
price=30;
ticket++;
}
// days before is more than 10
else{
this.price=40;
ticket++;
}
}
}
Student Advance Ticket:
package tester;
import java.util.Scanner;
public class StudentAdvanceTicket extends AdvanceTicket{
/**
* stores the values of an advance ticket, depending on how many days before
* the event it is purchased, with student discount.
*/
public StudentAdvanceTicket(){
Scanner db = new Scanner(System.in);
System.out.println("How many days before the event are you purchasing your ticket?");
int days = db.nextInt();
System.out.println("Are you a student?");
System.out.println("1. Yes");
System.out.println("2. No");
int stud = db.nextInt();
// days before is 10 or less days
if(days >= 10 && stud == 1){
price=15;
ticket++;
}
// days before is more than 10
if(days <= 10 && stud == 1){
this.price=20;
ticket++;
}
}
}
I feel like I'm making a simple mistake, but I am new to OOP so I'm having bit of trouble with this.
Are you supposed to be saving a total for all tickets bought or just the one ticket at a time total?
For walk-up tickets you don't have to do anything. Its a flat $50 total.
For Advance and StudentAdvance you would create a new object of that type and the way you have it the constructor will display the menu for how many days in advance and what not. You can then get the total from that.
As for the structure of your code it is not ideal. The object's constructor should not have all that code in it. They should have a ShowMenu function that will display the menu to the user and read their input. The constructor should be blank for the most part.
You also don't need three different ticket objects. One ticket object should be able to handle all this by itself. The ticket object can show the menu and handle the different prices based on user input. If you need to save a total or the different tickets you can have an array of ticket objects on the main method. You can then loop through that array to display or sum the tickets.
Hope this helps.
Your question is pretty broad, but well, some thoughts on your input:
Names matter. It is good that you made a first step and that you are using a specific package (instead of the default package); but tester says nothing. You could call it dylan.tickets for example: to make clear A) its your thing and B) it is about that ticket system
It seems that you are serious about your work, thus: do not use a static main to drive testcases. Using JUnit and simple testcases is really easy. And beyond that: driving tests "manually" using a main is cumbersome and error prone. Unit tests are almost automatically automated.
More importantly: tests that just print something are almost useless. If your code behaves unexpectedly, you might only notice when you carefully check that printed output. As said: use unit tests, and Junit assert calls to check expected versus actual results of method calls. Because then you will be told when you make changes that break functionality which was previously working.
You absolutely avoid to ask for user input in so many different places. Meaning: the reasonable thing is that a class has a constructor or setter methods; and that all the arguments required to instantiate the new object are given to that object. If at all, your main uses a scanner and asks the user for input. But all your "business logic" objects do not require any "user interaction" at all. You see, you actually want to start the whole project without using a scanner. You want to hardcode things like AdvancedTicket at = new AdvancedTicket(100); - because now you can easily code all kinds of different objects; and start your program again and again. Your current solution requires you to enter all such data manually ... every time you re-start your program! So: no scanner usage in constructors. Never!
Then: good OO is about behavior, not about state. Meaning: you dont use public fields to spread information. If at all, your fields should be protected; but even that is most often not a good idea. You want to isolate your classes from each other ...
The core problem: it seems that nobody told you yet about FCoI. You should favor composition over inheritance. Meaning: you dont just put A extends B everywhere. There is absolutely no reason that your Tester class extends Ticket. The tester is a Tester, not a ticket!
As said: that last point is the most important one. You are careful about making A a subclass of B; very often, it is more appropriate to maybe have A own a B object, but not to make A a B!

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!

Categories