So i am trying to make a text based rpg game and what is supposed to happen here is when you activate a hunt by typing hunt it asks you yes or no. However even when i input yes, the you killed the boar message does not pop up. I am fairly new to java so sorry if the code is bad.
//Branches
if (ins.equals("branches") && loc.equals("forest")) {
System.out.println("You got a branch");
ib++;
} else if (ins.equals("branches") && !"forest".equals(loc)) {
System.out.println("You need to be in the forest to cut branches");
} else if (ins.equals("bcount")) {
System.out.println(ib);
}
//Branches
//Stones
if (ins.equals("stones") && loc.equals("mountains")) {
System.out.println("You got a stone");
is++;
} else if (ins.equals("stones") && !"mountains".equals(loc)) {
System.out.println("You need to be in the mountains to gather stones");
} else if (ins.equals("scount")) {
System.out.println(is);
}
//Stones
//Spears
if (ins.equals("spear") && is >= 1 && ib >= 1) {
System.out.println("+1 spear");
is--;
ib--;
ispear++;
} else if (ins.equals("spear") && is < 1) {
System.out.println("Insufficient resources");
} else if (ins.equals("spear") && ib < 1) {
System.out.println("Insufficient resources");
} else if (ins.equals("spearcount")) {
System.out.println(ispear);
}
//Spears
//Hunt
if (ins.equals("hunt") && ispear >= 1) {
System.out.println("A wild boar comes charging at you! Throw spear? (yes or no)");
if (ins.equals("yes")) {
System.out.println("You killed the boar!");
}
} else if (ins.equals("hunt") && ispear < 1) {
System.out.println("You dont have any spears");
}
}
If the while loop at the top controls the input then it is not possible for the code to get back to that inner if statements because ins cannot equal both "hunt" and "yes" at the same time. You need to do what #Spectric suggested in the comments and read the input again, or you need to use another way.
In the example below, we have used a boolean as a flag Boolean hunting = false;, and an OR condition || to allow us to get back inside the hunting section if (huting == true || ins.equals("hunt")....) then finally we need to make sure we trigger the flag on/off when hunting starts/ends like this hunting = true; or hunting = false;
Then all put together:
//Flag that allows us to trigger hunting
//This needs to be placed outside of the while loop
Boolean hunting = false;
//While loop that gets input and prints the next instruction
while (ins != null)
{
//Your code here to get the input
//...
//ins = scanner.nextLine();
//...
//Hunt
//add an or "||" condition so that if the hunting flag is true then we can get back inside this if statement:
if (hunting == true || ins.equals("hunt") && ispear >= 1)
{
//Set the hunting flag to true, so that we can get back to here in the next loop:
hunting = true;
System.out.println("A wild boar comes charging at you! Throw spear? (yes or no)");
if (ins.equals("yes"))
{
System.out.println("You killed the boar!");
//Reset the hunting flag so future commands don't break:
hunting = false;
}
//Make sure you have an else statement to set the hunting flag back to false
else
{
System.out.println("The boar ran away!");
//Reset the hunting flag so future commands don't break:
hunting = false;
}
}
else if (ins.equals("hunt") && ispear < 1)
{
System.out.println("You dont have any spears");
}
}
Related
This is code for my Tic Tac Toe game. My professor doesn't want us to use while(true) and breaks. I don't know how to change it. Can someone please help me.
public void playerMakeMove()
{
while(true)
{
System.out.println("It is "+username+"'s move");
System.out.println("Give me your best move!");
int move = input.nextInt();
if (validatePlayerMove(move))
{
if (checkPositionAvailability(move))
{
board[move] = 'H'; //'H' for player move
break;
}
else
{
System.out.println("Position not available.\nMake a different choice.");
continue;
}
}
if (move >= 9 || move <= -1)
{
System.out.println("Invalid entry!");
continue;
}
I highly recommend using a boolean that does the job instead of while (true) { code }
Useful link for this : Are "while(true)" loops so bad?
You could write something like this:
while ( gameInLimbo() ) {
makeAnotherMove();
}
where gameInLimbo() is a method that returns true if there is no current winner and there are still open square(s), and false otherwise.
I'm trying to make a short game where the player has to open a treasure chest and buy stuff from a shop, but when i exit the shop, it tells me "Invalid command. Use "shop" or "open."" I added the "end of loop" and found out that after store is finished, it ends the loop and ignores the nextLine() command and goes directly to the if-else ladder. Can anyone help me solve this?
while (win == 0)
{
opt = s.nextLine();
er = 1;
if (opt.equalsIgnoreCase("shop"))
{
store();
er = 0;
}
else if (opt.equalsIgnoreCase("open"))
{
gold += open();
}
else if (opt.equalsIgnoreCase("exit"))
{
return;
}
else if (er == 1)
{
System.out.println("Invalid command. Use \"Shop\" or \"Open.\"");
wait (1);
}
if (gold >= 1000000)
{
win = 1;
}
System.out.println ("End of loop");
I am currently learning java script and attempting new things, for example I wish to see if I can set a boolean expression to end if it detects a starting number through an ending number.
Or in other terms what I'll want is 3 through 8.
I will make it clear I am using netbeans IDE.
Within my last else if statement, I want it to end the asking process. I am hoping it is a simple fix, but I can not think of anything that will accomplish this unless I create a lot more else if statements.
Scanner input = new Scanner(System.in);
int[][] table;
boolean stopasking = true;
while (stopasking = true){
System.out.println("Let's make a magic Square! How big should it be? ");
int size = input.nextInt();
if (size < 0)
{
System.out.println("That would violate the laws of mathematics!");
System.out.println("");
}
else if (size >= 9)
{
System.out.println("That's huge! Please enter a number less than 9.");
System.out.println("");
}
else if (size <= 2)
{
System.out.println("That would violate the laws of mathematics!");
System.out.println("");
}
else if (size == 3)
{
stopasking = false;
}
}
You have used the assignmnent operator =
you should use == instead
also the condition size<=2 holds when size<0 so you can use one if for both
while(stopasking){
if (size <= 2) {
System.out.println("That would violate the laws of mathematics!\n");
} else if (size >= 9){
System.out.println("That's huge! Please enter a number less than 9.\n");
} else if (size == 3){
stopasking = false;
}
}
you can use the boolean expression in this way, as condition to exit from a loop. Some would say it is a more elegant solution than break.
I have to write a Magic 8 ball program that will account for user input errors and I have to use a loop to do that.
boolean okay;
do {
System.out.printf("What is your question?\n");
questionStr = keyboard.nextLine();
int length = questionStr.length();
if (questionStr.length() == 0) {
System.out.println("Not allowed.");
okay = false;
} else if (!(questionStr.charAt(length - 1) == '?')) {
System.out.println("Add question mark.");
okay = false;
} else if (questionStr.length() > 60) {
okay = false;
}
okay = true;
} while (!okay);
When I run the code and make it an empty string, it does print out not allowed however it still runs the rest of the code and does not loop back and ask "What is your question?" The same happens with the question mark; it prints out "Add question mark" but does not loop back like it is supposed to. If I make a question longer than 60 characters, the code still executes and does not loop back and continue asking the user "What is your question?" until the code is less than 60 characters. I am trying to figure out what I am doing wrong here.
Move okay = true; before your if statements that negate it,
okay = true;
if (questionStr.length() == 0) {
System.out.println("Not allowed.");
okay = false;
} else if (!(questionStr.charAt(length - 1) == '?')) {
System.out.println("Add question mark.");
okay = false;
} else if (questionStr.length() > 60) {
okay = false;
}
As posted, you unconditionally set okay to true before your condition while (!okay); and thus the loop always ends.
I'm writing a relatively simple Java program that calculates discounts for shoppers if they have certain vouchers or bonuses. It's working okay, but I have an issue when the program asks the user if they have any vouchers.
If they type "n", they still have to go through the loop as if they responded with "y" once before they can exit. I know it's probably a dumb mistake in there somewhere, but it's been driving me crazy and I'd appreciate a pair of fresh eyes to once it over.
do {
System.out.println("Please enter the total price of the goods");
price = keyboard.nextDouble();
if (price < limits[0] || price > limits[1]) {
System.out.println("Invalid price. Please try again");
validPrice = false;
} else {
validPrice = true;
}
} while (!validPrice);
keyboard.nextLine();
do {
System.out.println("Does the customer have any additional discounts? y/n");
choice = keyboard.nextLine();
if (!choice.matches(inputRegexMatchPattern)) {
System.out.println("Invalid input – please re-enter");
} else if (choice.toLowerCase().charAt(0) == 'y') ;
{
System.out.println(choice);
do {
System.out.println("What type of discount does the customer have? [L]oyalty Card/[D]iscount Voucher");
input = keyboard.nextLine();
if (!input.matches(discountRegexMatchPattern)) {
System.out.println("Invalid input – please re-enter");
}
} while (!input.matches(discountRegexMatchPattern));
if (input.charAt(0) == 'l' || input.charAt(0) == 'L') {
voucherDiscounts += voucherDiscountsArray[0];
System.out.println("Loyalty Card discount accepted");
} else if (input.charAt(0) == 'd' || input.charAt(0) == 'D') {
voucherDiscounts += voucherDiscountsArray[1];
System.out.println("Discount Voucher accepted");
}
}
} while (!(choice.toLowerCase().charAt(0) == 'n'));
You have a semicolon here:
else if (choice.toLowerCase().charAt(0) == 'y') ;
What that means is your loop will continue to execute in spite of the selection you make. Java interprets this if statement as not having any body.
Remove the semicolon and you should be good to go.
The do while construct always performs the content of the loop BEFORE it actually tests the condition.
I guess what you want here is a simple while loop.