Java refire loop after IF statement is completed - java

I'm trying to make a simple text based adventure as an exercise on beginner java, but I've ran into a problem, and after a long time of searching I decided to just ask it.
I want to know how to refire this loop after IF statement has been answered, eg. user inputs: "Help", help tab shows up and user can enter another command.
I'm clueless as to why this doesn't work, so any help would be much appreciated.
boolean loopone = false;
do {
System.out.println(name + " is standing in a forest, covered in slime goo.");
String cmdone = in.next();
if (cmdone.equals("Help")) {
System.out.println("---------Help---------");
System.out.println("Type: [Help] to view help");
System.out.println("Type: [Turn] to turn, syntax: [Turn (direction)] left, right and backward are the possible directions");
System.out.println("Type: [Enter] to go through an entrance");
System.out.println("Type: [Slay] to kill stuff");
System.out.println("Type: [Take] to take stuff");
System.out.println("Typing: [/rocket smallbrains] has no effect here");
return;
}
else if (cmdone.equals("Enter")){
System.out.println("Enter what?");
String conone = in.next();
if (conone.equals("Forest") || conone.equals("The forest")){
System.out.println("You're already in the forest, dummy!");
}
else{
System.out.println("I don't know where that is");
}
}
else if (cmdone.equals("Turn right")){
System.out.println("You turn right");
}
continue;
}while (loopone = false);

One issue is you need to make this:
}while (loopone = false);
this:
}while (loopone == false);
Otherwise, you just need to make sure that you are setting loopone to false in each of the if statements. When you want to exit, you set loopone to true (loopone = true).

Related

Make a method run in a method java for my game?

I'm struggling with dealing of inventory scan for my game, it basically search for the user inventory if "Flying Broom" if present(it was collected in another method and upload the code is too long), if not it will run the method challengedragon() again; else, it will proceed to the next challenge if the item is present.I was think of inserting method as parameter but it is not possible. This is what I have now. :
public class Main {
String Flyingbroom = "Flying broom";
public static void main(String[] args) {
Player_inventory p = new Player_inventory();
challengedragon();
}
public void challengedragon() {
System.out.println("a Hungarian Horntail dragon! Let's start the battle! You have four options to beat the dragon: ");
System.out.println("1: Fly away with your broom");
System.out.println("2: Fight the dragon");
System.out.println("3: Just run to the egg and get it");
System.out.println("4: Hide behind a rock");
System.out.println("5: Go back to Hogwart");
System.out.println("Your choice is: ");
Scanner in = new Scanner(System.in);
int dragonfightchoice = in .nextInt();
if (dragonfightchoice == 1) {
{
p.Scanitem(Flyingbroom,
"Good choice! You managed to kill the Hungarian Horntail dragon and to get the golden egg",
"You dont have the broom. Try to search for the broom",
playerHP);
proceedtonextchallengelake();
} else if (dragonfightchoice == 2) {
System.out.println("The Hungarian Horntail dragon fired you. - 70HP. ");
playerHP -= 70;
challengedragon();
} else if (dragonfightchoice == 3) {
System.out.println("Bad idea... You lose 100 HP");
playerHP -= 100;
challengedragon();
} else if (dragonfightchoice == 4) {
System.out.println("The dragon found you. You lose 30 HP");
playerHP -= 30;
challengedragon();
} else if (dragonfightchoice == 5) {
Hogwart();
} else {
invalid();
challengedragon();
}
}
For my inventory class:
public void Scanitem(String item, String trueouputext, String textifconditionisnotmet) {
if (inv.contains(item) == true) {
System.out.println(trueouputext);
} else if (inv.contains(item) == false) {
System.out.println(textifconditionisnotmet);
}
public static ArrayList<String> inv = new ArrayList<String>();
Do you guys have any recommendation?
Are there additional steps to populate the inventory (variable inv)?
Also, wouldn't you want ScanItem to answer true or false, depending on whether the item was found? Then you would have something like this:
public boolean scanitem(String item) {
return ( inv.contains(item) );
}
if ( p.scanItem(flyingBroom) ) {
System.out.println("Good choice! You managed to kill the Hungarian Horntail dragon and to get the golden egg");
} else {
System.out.println("You dont have the broom. Try to search for the broom");
}
That will get you closer to what you want. However, there are two other issues which you'll need to put into your code:
You will need a loop of some sort, instead of calling challengeDragon from inside of itself.
Somehow, the return value from scanItem must be used to decide whether to loop.
Currently, you do a nested call of a method each time the player does something, this means that sooner or later you'll run out of the stack. A better idea for the framework for your text-based adventure is to have some kind of a description of the current game's state. The state could be represented as an object that contains the following information:
where's the player currently at (on which step, at which "crossing" etc.)
the player's stats (HP, available skills etc.)
the contents of the player's inventory
some previously made choices affecting the game
Then, the code could be written as a simple loop that does the following:
process player's input
change the state according to the player's input
present the player with available options according to the new state
wait for the next input
repeat

java: loop with switch only works sometimes

I'm really scratching my heard on this one. I'm new at java, and I'm having the strangest thing happen.
It's homework and I'm taking it one step at a time. My issue is the loop just keeps going and stops asking for input, just keeps looping until it terminates. My comments are largely for myself. I tried to extract what was causing my problem and post it here.
Look at the "hatColor" switch, you'll notice the way I'm making sure the user enter only from the options I have allotted. Should I be using a exception handler or something?
Anyway, in short, the problem is that if I enter something with spaces, the loop skips asking for my next input. Like, if I entered "y y y y y " to the scanner when first prompted, the program will terminate and not give me the chance to enter something else.
Please, anyone that understands this, I would really appreciate your help.
import java.util.Scanner;
public class Testing
{
static String hatColor;
public static void main(String[] args) {
gameStart();
}
public static void gameStart()
{
Scanner userInput = new Scanner(System.in);
boolean keepLooping = true;
int loopCounter = 0;
System.out.println("The game begins. You must choose between 3 different colored hats."
+ " You can type white, black, or gray.");
while (keepLooping == true)
{
hatColor = userInput.next();
switch(hatColor)
{
case "white":
System.out.println("You have chosen the path of well intentioned decisions.");
walletDrop();
//the two items below are only there in case the wallet drop somehow completes without calling another method
keepLooping = false; // stops the while loop from looping again.
break; // breaks out of the switch
case "gray":
System.out.println("You have chosen the path of free will.");
walletDrop();
keepLooping = false;
break;
case "black" :
System.out.println("You have chosen the path of personal gain.");
walletDrop();
keepLooping = false;
break;
default : //we could just copy this default chunk for later switch statements
if (loopCounter >= 3)//end program on them
{
System.exit(0);
}
System.out.println("You didn't enter a usable answer. Try again");
loopCounter++;
if (loopCounter == 3)
{
System.out.println("This program will self destruct if you enter another invalid response.");
}
}//end of switch
}//end of while
}//end of game start method
public static void walletDrop()
{
System.out.println("wallet drop successful");
}
}
So I have actually solved this right after posting. In case someone else needs to look here for help:
The issue I was experiencing was due to using the scanner method
variableToAssign = scannerName.next();
instead of
variableToAssign = scannerName.nextLine();

Java! How to display the correct and incorrect answered questions after user finish answering the questions

I have a Java program that asks user questions and totals their scores. I am trying to display the correct total of answered questions at the end of the program. However, I have no idea how to, can some please help me!
Here is an example of how my code looks like l! But this is not my actual code this is from another source!
Import java.util.Scanner;
public class App
{
public static void main(String[] args) {
// The array of questions.
String questions[] = {
"Plants derive most of their dry mass from the air.",
"Aluminium is the most common metal in the Earth's crust.",
"Vitamin C has be shown to prevent colds.",
"We lose the most heat through our heads.",
"Dogs are unable to digest chocolate.",
"Apple pips contain cyanide.",
"Cholesterol is a nat
"When you're on a diet, you lose weight by oxidising fat to a gas and exhaling it.",
"Human beings are unable to sense when the oxygen level of the air is low.",
"Most of the Y chromosome is passed unchanged from father to son" };
// The array of answers. The entries correspond to the questions.
boolean answers[] = { true, true, false, false, false, true, false,
true, true, true };
// Display the opening text.
System.out.println("Answer each of the following questions with 't' (true) or 'f' (false)");
// We'll use this to get user input.
Scanner input = new Scanner(System.in);
// Add up the user's score here as we go along.
int score = 0;
// The is the index into the questions array and the answers array.
int questionNumber = 0;
// Create a blank line.
System.out.println();
// The do-while loop will keep running while questionNumber is less
// than the question array length.
do {
// Display the question
System.out.println(questions[questionNumber]);
// Display a little prompt to make it clearer that the user has to
// enter something.
System.out.print("> ");
// Get the user's answer.
String userAnswer = input.nextLine();
// Check that the user has entered t or f.
if (!userAnswer.equals("t") && !userAnswer.equals("f")) {
System.out.println("Please enter t for true or f for false.\n");
// Invalid input!
// Skip the rest of this loop iteration and ask the same question again.
continue;
}
// Check the answer.
if (userAnswer.equals("t") && answers[questionNumber] == true) {
// If the answer's t and the right answer is "true", the answer was correct.
score++;
System.out.println("correct\n");
} else if (userAnswer.equals("f") && answers[questionNumber] == false) {
// If the answer's f and the correct answer is "false", the answer was correct.
System.out.println("correct\n");
score++;
}
else {
// Wrong answer!
System.out.println("incorrect!\n");
}
// Now we can move to the next question when we go round the loop again.
questionNumber++;
} while (questionNumber < questions.length); // end of do-while.
// This isn't really necessary, but closing the Scanner prevents a warning icon in Eclipse.
input.close();
// Tell the user their score.
System.out.println("You scored: " + score);
// Rank the score! Only one of the alternatives below will execute.
// Java will check them in order from top to bottom.
if(score < 5) {
// Less than 5 -- not so good.
System.out.println("Hmmm, maybe you're the artistic type. Try the test again!");
}
else if(score < 8) {
// The score wasn't less than 5, but it IS less than 8.
System.out.println("Not bad! But have another go.");
}
else if(score <= 9) {
// The score wasn't less than 8, but it IS less than, or equal to, 9.
System.out.println("Pretty good! But no perfect. Try again!");
}
else {
// The score was more than 9 -- must be 10 because we've only got 10 questions.
System.out.println("You're a certified science genius!");
}
}
}
You can use a list and add the question nummer when the user has answered the question correctly.
Before your do-while-loop you have to add
ArrayList<Integer> correctQuestions = new ArrayList<Integer>();
Then in your do-while-loop you have to add when the answer is correct
correctQuestions.add(questionNumber);
At the end of you program (outside the do-while-loop) you can make the output like this:
System.out.println("You answered the following questions correctly");
for (int k : correctQuestions) {
System.out.println(questions[k]);
}
Simply declare a boolean array containing user answers in your class:
public boolean[] userAnswers = new boolean[questions.length]; //remove the access modifier if you want to declare the array inside main instead of the class
Now in your do-while loop, after parsing the user input, do this:
userAnswers[questionNumber] = userAnswer.equals("t");
Outside of your do-while loop (after you close the Scanner), do the following to print all the questions and the user's answer:
for (int i = 0; i < questions.length; i++) {
System.out.println("User answered \"" + userAnswers[i] + "\" on question " + (i + 1) + ": " + questions[i]);
}

Java: Continuing iteration through an arraylist only when the right menu item is selected

I'm trying to create a console app that iterates through an arrayList of meal ideas every time the correct menu item is selected. The problem is that I can't seem to continue the iteration every time the correct menu item is selected, it just restarts the loop.
Scanner in = new Scanner(System.in);
ArrayList<String> meals = new ArrayList<String>();
meals.add("pasta");
meals.add("potatoes");
meals.add("pork");
String select = "";
while(!select.equals("q")){
System.out.println("What would you like to do?");
System.out.println("\t 1. See next suggestion.");
System.out.println("\t 2. <Another option>");
System.out.println("\t 3. <Another option>");
select = in.next();
switch(select){
case "1":
//Here's where the problem is:
int nextIdea = 0;
while(){
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
break;
}
System.in.read();
break;
}
}
After the user selects to show the daily selection, the first item in the list should be displayed then it should go back to the "What would you like to do menu" then next time the user selects option 1 in the menu it should display the next item in the menu but instead it restarts the loop. I understand it's because the counter variable ("nextIdea") is set to zero every time before the loop executes but how can I get it to remember which arrayList index number was last used and then use that next time the user selects to see the daily meal. The list should only reset to 0 once it's gone through all the items in the list.
Any help would be appreciated, thank you!!
You need to move the nextIdea index out of the first loop. Then you also don't have to iterate the list when the user selects "See next suggestion." - You just display the next idea:
int nextIdea = 0;
while(!select.equals("q")){
System.out.println("What would you like to do?");
System.out.println("\t 1. See next suggestion.");
System.out.println("\t 2. <Another option>");
System.out.println("\t 3. <Another option>");
select = in.next();
switch(select){
case "1":
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
System.in.read();
break;
}
}
So, basically, you don't need the inner loop to iterate over the meal ideas. You already do the iteration with the outside loop: Every time the user selects menu item #1, you show her the next idea.
You should also make sure that nextIdea is always a valid index in the array list. Something like:
case "1":
if(nextIdea >= meals.size()) {
nextIdea = 0;
}
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
System.in.read();
break;
Firstly, instantiate nextIdea outside of the while loop like you have mentioned.
Then, includ a simple if statement which checks if the nextIdea has reached the end, like so:
while(true)
{
if (nextIdea < meals.size())
{
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
}
else
{
nextIdea = 0;
}
break;
}
You didn't have a condition in the while loop, so I'm assuming you meant 'true' which means it'll run infinitely until broken out of.
Although, technically, the loop here isn't really doing anything as it just runs once and breaks out, so you can just get rid of it like so:
if (nextIdea < meals.size())
{
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
}
else
{
nextIdea = 0;
}
I think you need to think carefully about what it is you actually want to achieve and what the best way to do this is.
Feel free to ask my further questions.

How to write code that if something happens nothing else happens afterward?

Lets say if the last level of a game is beaten then you dont show a dialog box asking if the player wants to go on to the next level, but rather to the mainmenu. SO basically if something happens the things that are supposed to happen afterward dont.
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
final ImageIcon pokeballIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\pokeball5.gif");
final ImageIcon pokemoneggIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\nidoking.gif");
final ImageIcon pokemonredIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\red.gif");
String userAnswer = answertextArea.getText().trim();
if (userAnswer.equalsIgnoreCase(answers.get(questionNumber))) {
answerLabel.setText("Correct");
levelScore ++;
triviagui.totalScore ++;
} else {
answerLabel.setText("Incorrect");
}
answertextArea.setText("");
questionNumber++;
if(questionNumber == questions.size()){
JOptionPane.showMessageDialog(null, "Your score for this level was : " + levelScore + " out of 10. \n Your total score is " + triviagui.totalScore, "Scores",JOptionPane.INFORMATION_MESSAGE, pokeballIcon );
if(difficulty == 3){
JOptionPane.showMessageDialog(null, "Good job you beat the game! \n Your total score was " + triviagui.totalScore + " out of 30.", "Thanks for playing!", JOptionPane.INFORMATION_MESSAGE, pokemonredIcon);
triviagui.questionFrame.setVisible(false);
triviagui.mainFrame.setVisible(true);
}
int leveloptionPane = JOptionPane.showConfirmDialog(null,"Would you like to go on to the next level?" , "Next Level?", JOptionPane.YES_NO_OPTION, levelScore, pokemoneggIcon);
if(leveloptionPane == JOptionPane.YES_OPTION){
difficulty++;
triviagui.questionFrame.setVisible(false);
triviagui.questionFrame=new QuestionFrame(difficulty);
triviagui.questionFrame.setVisible(true);
}
if(leveloptionPane == JOptionPane.NO_OPTION){
triviagui.questionFrame.setVisible(false);
triviagui.mainFrame.setVisible(true);
}
return;
}
updateQuestionScore();
}
You simply want to do:
if(something happens) {
return;
}
If you want to jump out from method use
return;
example of something like that:
public void myMethod(){
if(mynumber==5){
doThis();
}else{
return;
}
/*
*do something else <- this wont be executed if number doesnt equal 5
*cause we are already out of method.
*/
}
If you dont want to jump out from whole method bud only form part of it for instance loop.
break;
example of that:
public void myMethod(String[] stringArr){
for(String s:stringArr){
if(s.equals("hello")){
break; //get me out of this loop now !
}else{
s+="alriight";
}
}
}
doSomethingElse();//this will be executed even if you go thru break; you are still inside method dont forget.You are just out of loop
}
There are better uses for that maybe examples aint best bud you will understand how to use it form this:).
When you use break or return.In eclipse for instance you will be shown Where you actually exit. it will highlight "}"
There are several ways to do this:
You can return from a method.
You can break to exit a loop or continue to start the next iteration of the loop.
You can use an 'else' to only execute other code if the first section did not execute.
You can set a boolean flag variable and then check for that elsewhere in your code.
Depending on what you are trying to do each of these is sometimes the best way, sometimes not the best way.

Categories