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).
Related
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.
I have two different classes: TextBasedGame and IntroductionChoices.
IntroductionChoices makes all the decisions while TextBasedGame basically just prints the story (it's the one with the main method).
What I want to know is how to make the game END if the user makes a wrong choice.
In this case, if the user types in "Take down the group.", a message is displayed and the game ends. In my case, in the main method, it just keeps on going. How do I stop the game from running?
I was thinking I could somehow, in the main method, check if return from IntroductionChoicesis "GAME OVER" and end the game there.
//Snippet from the main method
System.out.println("What do you do?");
System.out.println(choice.choice1());
System.out.println("Next part...");
//Method choice1 from IntroductionChoices
public static String choice1()
{
Scanner scan = new Scanner(System.in);
System.out.println("Warn her of her shadows.");
System.out.println("Take down the group.");
String decision = scan.next();
if (decision.equalsIgnoreCase("right decision"))
{
System.out.println("some text");
return "some more text in continuation to continue story in main";
}
else if (decision.equalsIgnoreCase("wrong decision"))
{
System.out.println("You creep towards the men, hoping to surprise them from behind.");
System.out.println("Consequence");
return "GAME OVER";
}
else
{
return "That is not a valid response.";
}
}
System.exit(0)
else if (decision.equalsIgnoreCase("wrong decision"))
{
System.out.println("You creep towards the men, hoping to surprise them from behind.");
System.out.println("Consequence");
System.exit(0);
You won't need to return anything, it will end the program.
OR
Give the user an option:
Start new game-> start a new game
Quit -> System.exit(0)
I'd also use a switch to check through the user options, you're less liekly to make mistakes and it can be neater and quicker when the options start accumulating.
You can create an enum of options or use final ints with meaningful names so your code is easier to navigate and then match with user options.
From java the docs.
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.
I need to write a program for Java that "rolls" two 6-sided die and that keeps track of how many tries it took to roll a 7. The program also needs to run this process N number of times, determined by the user. After the Nth trial, the program needs to compute the average amount of trials it takes to roll a 7.
I'm pretty confident that I should use a while loop inside of a for loop but I'm unsure of exactly how to do it. I already have written the code to a program that "rolls the dice," and is shown below.
import java.util.*;
public class RollDice {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
String input = "";
do {
System.out.println("Rolling the dice...");
System.out.println("You rolled a"+((rand.nextInt(6)+1)+(rand.nextInt(6)+1)));
System.out.println("Roll again? (y/n)");
input = keyboard.next();
} while (input.equalsIgnoreCase("y"));
}
}
Yes, I know it's a do-while loop, but it's all I have so far.
https://codereview.stackexchange.com/questions/31980/a-simple-dice-roll-game
This would be a great place for you to start. Then just add a second die, and a variable for the average. But please do not copy this code directly. Use it as a template/guideline. I want no part in plagiarism.
quite new to Java so trying to understand it can be difficult.
Anyways the problem, as part of a task I have to code a theatre tickets console application. I've almost finished I'm just trying to add the last part
As part of the task we have to ask the user if they want the tickets to be posted, if yes this incurs a charge which will be applied to the total charge. Currently I'm unsure of how to do this. At the moment I am currently working with If and else statements and.. Well you'll see below.
System.out.println ("Do you require the tickets to be posted?\n(£2.34 for post and packing for the entire order)\n(please enter 'Yes' on the next line if you require postage)");
String postinp = scanner.next();
if ("Yes".equals(postinp)){
System.out.println("Postage will be added to your cost" );
}
else
System.out.println("Postage will not be added to your cost");
Well I'm trying to code, if the user enters 'yes' then it adds on the postage charge to the total, but in this section of code I'm unsure how to do that.
Any help would be appreciated. Thanks!
Inside the if-statement all we need to do is add your £2.34 to the total sum being calculated by the program.
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double total = 10.00;
System.out.println("Do you require the tickets to be posted?\n(£2.34 for post and packing for the entire order)\n(please enter 'Yes' on the next line if you require postage)");
if ("Yes".equalsIgnoreCase(input.next())) {
System.out.println("Postage will be added to your cost");
total = total + 2.34;
} else
System.out.println("Postage will not be added to your cost");
}
use scanner.nextLine() insead of scanner.next();
and use "Yes" instead of "Ye"
What I would do is change
if ("Ye".equals(postinp)) {
to
if ("yes".equals(postinp.toLowerCase())) {
That way it won't be case sensitive to what the user inputs, because otherwise they'd have to input Yes exactly.
You can add more code within the then-else blocks of an if statement
if ( "Yes".equals(postinp) )
{
this.cost += 2.34 ; // or whatever it is you need to do
System.out.println("Postage will be added to your cost" );
}
else
{
System.out.println("Postage will not be added to your cost");
}
You seem to need to resolve two things--evaluating the answer and then acting accordingly.
Try this:
String postinp = scanner.next();
if ("Yes".equalsIgnoreCase(postinp)) {
cost += postage;
System.out.println("Postage will be added to your cost" );
}
else {
System.out.println("Postage will not be added to your cost");
}
The if block checks if the result is some form of "yes" without regard to case. Then it assumes that cost and postage variables (floats) are available and initialized from somewhere. In the "yes" case, cost is augmented by postage.
Also, since you are just learning it isn't a big deal, but at some point you might want to consider your postage to be a value consumed from a constant or from a configuration file. Maybe the initial cost can be too.