k.next statement [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Here is my choose your own adventure project. There are no issues, apart after choosing this set of options (you don't have to read the whole thing):
1.name
2.no
3.hide, it asks you to input another answer.
It does not matter what you put in, the second time, as it will still run the program according to "hide". Just wondering why this is showing up. Also, feel free to enjoy my game.
import java.util.Scanner;
public class BEproject1V2 {
public static void main(String[] args) {
Scanner k = new Scanner(System. in );
String C1, C2, C2a, C3, C3a, C3b, C3c;
System.out.println("Ya arr a captain pirate on these high seas! Aboard the ship that yar father made, the M.M. Big Boy.");
System.out.println("First order of business, is choosing your Pirate Name! What is yarr real name?");
String name = k.nextLine();
String Pn = "Capn Cornelious Coxswain, The Hatless";
///Start of story
System.out.println("Scupper that sailor! We'll call you " + Pn);
System.out.println("Arr ye wondering why yer called Hatless? You have NO hats. So little amounts of hats. Literally 0 hats.");
System.out.println("Yee and yer crew be lookin for any booty to steal, as well as gold and treasure!");
System.out.println("'Look smartly Sir!' yells one of yer sailors. 'A darkness approaches starboard!'.");
System.out.println("You look round the deck as yer biggest fear comes to life. A giant squid begins to wrestle the ship!");
System.out.println("The crew starts to panic as the ship gets dragged into the water. 'Show a leg boys!' is the last thing you say before being dragged into the darkness.");
System.out.println("She be lookin like the end for ol' " + Pn + ", until a giant sea turtle swims up to ye.");
System.out.println("'I am King Randy Myrtle, The Friendly Sea Turtle.' Says Randy. 'I can take you to an island, climb aboard!'");
System.out.println("Do you climb aboard King Randy Myrtle, The Friendly Sea Turtle? (Yes or No)");
////First choice "Yes"
C1 = k.next();
if (C1.equalsIgnoreCase("yes")) {
System.out.println("King Randy takes you to the surface. 'I know of two Islands, the first being the Island of the screaming crabs,");
System.out.println("or the Island of the Pun Telling Trees. which would you like to go to?' (Crab or Tree)");
////Second choice "Crab"
C2 = k.next();
if (C2.equalsIgnoreCase("Crab")) {
System.out.println("'Okay! Here we go!'. King Randy takes off towards a distant land. You come about to a crab staring you dead in the face.");
System.out.println("'Blast', you think to yourself. Ye see the crab take a lung of breath, waiting for the worst screamin crab ever recorded.");
System.out.println("'CAPN CORNELIOUS COXSWAIN, THE HATLESS!'. The crab repeats, as it starts pinching your nose. Angered and afraid, you pick up a nearby rock.");
System.out.println("Do you 'throw' the rock, or 'wait' for the crab to scream again?");
////Third choice "Throw"
C3 = k.next();
if (C3.equalsIgnoreCase("Throw")) {
System.out.println("You throw the rock somewhere in the distance. Why wouldn't you you aim it at the crab?");
System.out.println("Now you're defenseless, and an idiot in the eyes of crabs. GAME OVER.");
System.out.println("Thank you for playing my adventure, press run to play again.");
}
////Third Choice else "Wait"
else if (C3.equalsIgnoreCase("Wait")) {
System.out.println("You wait, and the crab starts screaming again. You notice that the tones ");
System.out.println("are in a pattern, so you sing along. The beautiful harmonies intrigue ");
System.out.println("the rest of the crabs, who then celebrate your presence. You win the island!");
System.out.println("Thank you for playing my adventure, press run to play again.");
}
}
////Second Choice else "Tree"
else if (C2.equalsIgnoreCase("Tree")) {
System.out.println("'Fantastic choice!' says Randy. He takes you to the island, where you hear lots of moans and small chuckles. You reach the sand, and walk up to a line of trees.");
System.out.println("'Is that a pirate over there?' asks one of the trees. 'Yes I think so! Hey I heard they were really good singers!' incorrectly states another.");
System.out.println("'Why is that?' you ask. 'Because they can always hit the HIGH C'S!!' says the tree, bursting with laughter. 'I guess that's a little funny' you mumble to yourself.");
System.out.println("'Oh you're in for a real TREEt then Cap'n! I have one for you.'Why should you pull your plate closer while eating spaghetti?' asks the tree. Do you answer? (Yes or no)");
////Third Choice 2 "Yes"
C3a = k.next();
if (C3a.equalsIgnoreCase("yes")) {
System.out.println("'So you don't spill any of it?' you say, immediately regretting your answer. You know that the tree is staring at you, even if it doesn't have eyes.");
System.out.println("'That was MY PUN.' exclaims the tree. 'NOW YOU WILL NEVER KNOW THE ANSWER, and are BANISHED from my PUNS, STINKy pirate.' Knowing you will never hear the pun, fills you with sadness. ");
System.out.println("Your eyes begin to sting, and you start shedding tears of soy. GAME OVER.");
System.out.println("Thank you for playing my adventure, press run to play again.");
}
////Third Choice 2 else "No"
else if (C3a.equalsIgnoreCase("no")) {
System.out.println("'Hm I'm not sure!' you say. The tree chuckles harmoniously. 'So you'll get less-on-ya! HAHAHAHA!'. After contemplating your death from this joke, you decide to laugh with the tree.");
System.out.println("Knowing that you will be great friends, fills you with determination. YOU WIN!");
System.out.println("Thank you for playing my adventure, press run to play again.");
} else {
System.out.println("That is not an option. Please hit \"run\" to try again.");
}
}
}
////First Choice else "No"
else if (C1.equalsIgnoreCase("no")) {
System.out.println("'Well, SORRY for asking then.' says Randy. He swims away. Now you are sinking into the abyss. It doesn't look too good. When you look up, there is ");
System.out.println("a shark and it's eating your mates! You look up and see a raft, you look down and see a little cave you could hide in. Do you 'swim', or 'hide'?");
////Second Choice 2 "Raft"
C2a = k.next();
if (C2a.equalsIgnoreCase("swim")) {
System.out.println("You begin to swim, and the shark chases right after you! You are able to avoid it, and make it to the raft. You look down and see that the shark is not chasing you, ");
System.out.println("but being chased himself! A blue whale swallows the shark whole as he screams for his wife. You see a paddle out in the water, do you try to 'grab' it before Moby Dick himself ");
System.out.println("consumes you? Or do you 'stay' on the raft?");
}
////Third Choice 3 "Grab"
C3b = k.next();
if (C3b.equalsIgnoreCase("grab")) {
System.out.println("You lunge for the paddle! Now is your time, and you start swimming faster and harder than ever before. You reach for it and - you got it! As you start to swim towards ");
System.out.println("the raft. You make it, and start paddling to a nearby island. From where you are, you think you can hear a mixture of screaming and laughing... YOU WIN!");
System.out.println("Thank you for playing my adventure, press run to play again.");
}
////Third Choice 3 "Stay"
else if (C3b.equalsIgnoreCase("stay")) {
System.out.println("You decide to stay on the raft. Good choice, that paddle looked real dangerous. The whale can not get close enough due to the wreckage to attack you.");
System.out.println("In a fit of fury, the whale breaches the water and says 'Caw! Caw!'. The whale then starts to fly! He is getting a LOT of air, but he is coming your way. ");
System.out.println("You realize that there is nothing you can do but watch the beauty of the whale come crashing down onto you. 'Take me as I am' are the last words to leave " + Pn + "'s mouth. THE END.");
System.out.println("Thank you for playing my adventure, press run to play again.");
}
////Third Choice 4 "Swim"
else if (C2a.equalsIgnoreCase("hide")) {
System.out.println("You swim to the nearby cave. Inside is a beautiful mermaid. 'Hello' says the mermaid. You lean in to say hi, but you trip on a big, glossy, wet stack of the movie ");
System.out.println("'The Ocean of Trumpets'. There is at least sixty of them. 'Sorry!' you exclaim. 'Oh, that's okay. You've just stepped on my big, glossy, wet stack of my favorite movie, ");
System.out.println("'The Ocean of Trumpets'. Say, how many do you think I have?'. The wetness of the DVD's entice you. You read the layout of the cave, and realize ");
System.out.println("that you could EASILY run away and STEAL a DVD. So, would you like to take a 'guess', or take a 'DVD'?");
//// Third Choice 5 "60"
C3c = k.next();
if (C3c.equalsIgnoreCase("DVD")) {
System.out.println("You start screaming the tune of 'We Are The Champions' to distract the mermaid. It serenades her into a deep slumber. You STEAL a DVD, Indiana Jones style. However, ");
System.out.println("you have not brought anything to replace the DVD with. The entire cave begins to rumble, and you are suddenly about to be crushed by a rolling boulder, also ");
System.out.println("Indiana Jones style! The only difference is you get crushed by the boulder, THE END.");
System.out.println("Thank you for playing my adventure, press run to play again.");
}
////Third Choice 6 "guess"
else if (C3c.equalsIgnoreCase("guess")) {
System.out.println("Please insert your guess into me! (Number)");
int num = k.nextInt();
double bignum = Math.PI * Math.pow(num, 2);
System.out.println("'Hmmm my guess is " + num + "!'. 'So close!' says the mermaid. But the answer is actually " + bignum + "! I'm sorry but you aren't qualified to touch my DVD's.'");
System.out.println(" You gaze at the wet pile of DVD's and cry tears of soy. When it hits the water, you realize what your life has become. Seeing that murky reflection fills ");
System.out.println("you with sadness. GAME OVER.");
System.out.println("Thank you for playing my adventure, press run to play again.");
} else {
System.out.println("That is not an option. Please run again.");
}
}
}
}
}

I believe this is how you wanted it to run:
Ya arr a captain pirate on these high seas! Aboard the ship that yar father made, the M.M. Big Boy.
First order of business, is choosing your Pirate Name! What is yarr real name?
:me me big boy
Scupper that sailor! We'll call you Capn Cornelious Coxswain, The Hatless
Arr ye wondering why yer called Hatless? You have NO hats. So little amounts of hats. Literally 0 hats.
Yee and yer crew be lookin for any booty to steal, as well as gold and treasure!
'Look smartly Sir!' yells one of yer sailors. 'A darkness approaches starboard!'.
You look round the deck as yer biggest fear comes to life. A giant squid begins to wrestle the ship!
The crew starts to panic as the ship gets dragged into the water. 'Show a leg boys!' is the last thing you say before being dragged into the darkness.
She be lookin like the end for ol' Capn Cornelious Coxswain, The Hatless, until a giant sea turtle swims up to ye.
'I am King Randy Myrtle, The Friendly Sea Turtle.' Says Randy. 'I can take you to an island, climb aboard!'
Do you climb aboard King Randy Myrtle, The Friendly Sea Turtle? (Yes or No)
:no
'Well, SORRY for asking then.' says Randy. He swims away. Now you are sinking into the abyss. It doesn't look too good. When you look up, there is
a shark and it's eating your mates! You look up and see a raft, you look down and see a little cave you could hide in. Do you 'swim', or 'hide'?
:hide
You swim to the nearby cave. Inside is a beautiful mermaid. 'Hello' says the mermaid. You lean in to say hi, but you trip on a big, glossy, wet stack of the movie
'The Ocean of Trumpets'. There is at least sixty of them. 'Sorry!' you exclaim. 'Oh, that's okay. You've just stepped on my big, glossy, wet stack of my favorite movie,
'The Ocean of Trumpets'. Say, how many do you think I have?'. The wetness of the DVD's entice you. You read the layout of the cave, and realize
that you could EASILY run away and STEAL a DVD. So, would you like to take a 'guess', or take a 'DVD'?
If yes, your problem was that you had your Third choice outside your check for the Second choice C2a.equalsIgnoreCase("swim"), and you put your else after C3b.equalsIgnoreCase("stay"). This caused your program to check if the second choice is swim, if yes print your text, else just take the third choice without printing. By placing the third choice into the second choice swim block, and fixing the else (C2a.equalsIgnoreCase("hide")) it runs correctly.
Scanner k = new Scanner(System.in);
String C1, C2, C2a, C3, C3a, C3b, C3c;
System.out.println("Ya arr a captain pirate on these high seas! Aboard the ship that yar father made, the M.M. Big Boy.");
System.out.println("First order of business, is choosing your Pirate Name! What is yarr real name?");
String name = k.nextLine();
String Pn = "Capn Cornelious Coxswain, The Hatless";
///Start of story
System.out.println("Scupper that sailor! We'll call you " + Pn);
System.out.println("Arr ye wondering why yer called Hatless? You have NO hats. So little amounts of hats. Literally 0 hats.");
System.out.println("Yee and yer crew be lookin for any booty to steal, as well as gold and treasure!");
System.out.println("'Look smartly Sir!' yells one of yer sailors. 'A darkness approaches starboard!'.");
System.out.println("You look round the deck as yer biggest fear comes to life. A giant squid begins to wrestle the ship!");
System.out.println("The crew starts to panic as the ship gets dragged into the water. 'Show a leg boys!' is the last thing you say before being dragged into the darkness.");
System.out.println("She be lookin like the end for ol' " + Pn + ", until a giant sea turtle swims up to ye.");
System.out.println("'I am King Randy Myrtle, The Friendly Sea Turtle.' Says Randy. 'I can take you to an island, climb aboard!'");
System.out.println("Do you climb aboard King Randy Myrtle, The Friendly Sea Turtle? (Yes or No)");
////First choice "Yes"
C1 = k.next();
if (C1.equalsIgnoreCase("yes")) {
System.out.println("King Randy takes you to the surface. 'I know of two Islands, the first being the Island of the screaming crabs,");
System.out.println("or the Island of the Pun Telling Trees. which would you like to go to?' (Crab or Tree)");
////Second choice "Crab"
C2 = k.next();
if (C2.equalsIgnoreCase("Crab")) {
System.out.println("'Okay! Here we go!'. King Randy takes off towards a distant land. You come about to a crab staring you dead in the face.");
System.out.println("'Blast', you think to yourself. Ye see the crab take a lung of breath, waiting for the worst screamin crab ever recorded.");
System.out.println("'CAPN CORNELIOUS COXSWAIN, THE HATLESS!'. The crab repeats, as it starts pinching your nose. Angered and afraid, you pick up a nearby rock.");
System.out.println("Do you 'throw' the rock, or 'wait' for the crab to scream again?");
////Third choice "Throw"
C3 = k.next();
if (C3.equalsIgnoreCase("Throw")) {
System.out.println("You throw the rock somewhere in the distance. Why wouldn't you you aim it at the crab?");
System.out.println("Now you're defenseless, and an idiot in the eyes of crabs. GAME OVER.");
System.out.println("Thank you for playing my adventure, press run to play again.");
}
////Third Choice else "Wait"
else if (C3.equalsIgnoreCase("Wait")) {
System.out.println("You wait, and the crab starts screaming again. You notice that the tones ");
System.out.println("are in a pattern, so you sing along. The beautiful harmonies intrigue ");
System.out.println("the rest of the crabs, who then celebrate your presence. You win the island!");
System.out.println("Thank you for playing my adventure, press run to play again.");
}
}
////Second Choice else "Tree"
else if (C2.equalsIgnoreCase("Tree")) {
System.out.println("'Fantastic choice!' says Randy. He takes you to the island, where you hear lots of moans and small chuckles. You reach the sand, and walk up to a line of trees.");
System.out.println("'Is that a pirate over there?' asks one of the trees. 'Yes I think so! Hey I heard they were really good singers!' incorrectly states another.");
System.out.println("'Why is that?' you ask. 'Because they can always hit the HIGH C'S!!' says the tree, bursting with laughter. 'I guess that's a little funny' you mumble to yourself.");
System.out.println("'Oh you're in for a real TREEt then Cap'n! I have one for you.'Why should you pull your plate closer while eating spaghetti?' asks the tree. Do you answer? (Yes or no)");
////Third Choice 2 "Yes"
C3a = k.next();
if (C3a.equalsIgnoreCase("yes")) {
System.out.println("'So you don't spill any of it?' you say, immediately regretting your answer. You know that the tree is staring at you, even if it doesn't have eyes.");
System.out.println("'That was MY PUN.' exclaims the tree. 'NOW YOU WILL NEVER KNOW THE ANSWER, and are BANISHED from my PUNS, STINKy pirate.' Knowing you will never hear the pun, fills you with sadness. ");
System.out.println("Your eyes begin to sting, and you start shedding tears of soy. GAME OVER.");
System.out.println("Thank you for playing my adventure, press run to play again.");
}
////Third Choice 2 else "No"
else if (C3a.equalsIgnoreCase("no")) {
System.out.println("'Hm I'm not sure!' you say. The tree chuckles harmoniously. 'So you'll get less-on-ya! HAHAHAHA!'. After contemplating your death from this joke, you decide to laugh with the tree.");
System.out.println("Knowing that you will be great friends, fills you with determination. YOU WIN!");
System.out.println("Thank you for playing my adventure, press run to play again.");
} else {
System.out.println("That is not an option. Please hit \"run\" to try again.");
}
}
}
////First Choice else "No"
else if (C1.equalsIgnoreCase("no")) {
System.out.println("'Well, SORRY for asking then.' says Randy. He swims away. Now you are sinking into the abyss. It doesn't look too good. When you look up, there is ");
System.out.println("a shark and it's eating your mates! You look up and see a raft, you look down and see a little cave you could hide in. Do you 'swim', or 'hide'?");
////Second Choice 2 "Raft"
C2a = k.next();
if (C2a.equalsIgnoreCase("swim")) {
System.out.println("You begin to swim, and the shark chases right after you! You are able to avoid it, and make it to the raft. You look down and see that the shark is not chasing you, ");
System.out.println("but being chased himself! A blue whale swallows the shark whole as he screams for his wife. You see a paddle out in the water, do you try to 'grab' it before Moby Dick himself ");
System.out.println("consumes you? Or do you 'stay' on the raft?");
////Third Choice 3 "Grab"
C3b = k.next();
if (C3b.equalsIgnoreCase("grab")) {
System.out.println("You lunge for the paddle! Now is your time, and you start swimming faster and harder than ever before. You reach for it and - you got it! As you start to swim towards ");
System.out.println("the raft. You make it, and start paddling to a nearby island. From where you are, you think you can hear a mixture of screaming and laughing... YOU WIN!");
System.out.println("Thank you for playing my adventure, press run to play again.");
}
////Third Choice 3 "Stay"
else if (C3b.equalsIgnoreCase("stay")) {
System.out.println("You decide to stay on the raft. Good choice, that paddle looked real dangerous. The whale can not get close enough due to the wreckage to attack you.");
System.out.println("In a fit of fury, the whale breaches the water and says 'Caw! Caw!'. The whale then starts to fly! He is getting a LOT of air, but he is coming your way. ");
System.out.println("You realize that there is nothing you can do but watch the beauty of the whale come crashing down onto you. 'Take me as I am' are the last words to leave " + Pn + "'s mouth. THE END.");
System.out.println("Thank you for playing my adventure, press run to play again.");
}
}
////Third Choice 4 "Swim"
if (C2a.equalsIgnoreCase("hide")) {
System.out.println("You swim to the nearby cave. Inside is a beautiful mermaid. 'Hello' says the mermaid. You lean in to say hi, but you trip on a big, glossy, wet stack of the movie ");
System.out.println("'The Ocean of Trumpets'. There is at least sixty of them. 'Sorry!' you exclaim. 'Oh, that's okay. You've just stepped on my big, glossy, wet stack of my favorite movie, ");
System.out.println("'The Ocean of Trumpets'. Say, how many do you think I have?'. The wetness of the DVD's entice you. You read the layout of the cave, and realize ");
System.out.println("that you could EASILY run away and STEAL a DVD. So, would you like to take a 'guess', or take a 'DVD'?");
//// Third Choice 5 "60"
C3c = k.next();
if (C3c.equalsIgnoreCase("DVD")) {
System.out.println("You start screaming the tune of 'We Are The Champions' to distract the mermaid. It serenades her into a deep slumber. You STEAL a DVD, Indiana Jones style. However, ");
System.out.println("you have not brought anything to replace the DVD with. The entire cave begins to rumble, and you are suddenly about to be crushed by a rolling boulder, also ");
System.out.println("Indiana Jones style! The only difference is you get crushed by the boulder, THE END.");
System.out.println("Thank you for playing my adventure, press run to play again.");
}
////Third Choice 6 "guess"
else if (C3c.equalsIgnoreCase("guess")) {
System.out.println("Please insert your guess into me! (Number)");
int num = k.nextInt();
double bignum = Math.PI * Math.pow(num, 2);
System.out.println("'Hmmm my guess is " + num + "!'. 'So close!' says the mermaid. But the answer is actually " + bignum + "! I'm sorry but you aren't qualified to touch my DVD's.'");
System.out.println(" You gaze at the wet pile of DVD's and cry tears of soy. When it hits the water, you realize what your life has become. Seeing that murky reflection fills ");
System.out.println("you with sadness. GAME OVER.");
System.out.println("Thank you for playing my adventure, press run to play again.");
} else {
System.out.println("That is not an option. Please run again.");
}
}
}
I hope this is what you wanted.

Related

There is a problem with my nested Do-while loop, it won't display my 3rd level in my code. is there a problem with the logic?

here is my code in java: i used nested do-while loops
do{ //Level hard
do{ //level meduim
do{ //level easy
//LEVEL EASY
if (num==1){
//1st question
//[logic displayed]
System.out.println("Would you like to play again? Type in Y for yes or N for no ");
retake = kbd.nextLine();
} while ( retake.equalsIgnoreCase("Y"));
System.out.print("Bye! Come back soon! ^-^");
//level medium
//[logic is here]
System.out.println("Would you like to play again? Type in Y for yes or N for no ");
retake = kbd.nextLine();
} while ( retake.equalsIgnoreCase("Y"));
System.out.print("Bye! Come back soon! ^-^");
//level hard
//[level hard is the same thing as the ones on top
System.out.println("Would you like to play again? Type in Y for yes or N for no ");
retake = kbd.nextLine();
} while ( retake.equalsIgnoreCase("Y"));
}
}
the thing is when I try to retake the quiz in the hard level, it wont work. it would just display this:
Would you like to play again? Type in Y for yes or N for no
Bye! Come back soon! ^-^Would you like to play again? Type in Y for yes or N for no
but the strange thing is when I type N (no to retake) it would start the quiz the hard level
how can I make it work? and why is it wrong?
(please help this is due today)

End the Game from a separate method

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.

If and if else again

The problem I seem to be having is that I am unsure on how to make the program recognize if the player is in one of the "MVP" positions (C,SS,CF) before moving forward with my program logic.
These three positions qualify for "MVP" status only if their OPS is above 800 for everyone else, it has to be 900 or above to be considered for "MVP".
Once again, I am having trouble with the "if" and "if else" statement.
Again, This IS school given problem and I don't want the answer. Only insight into what I am doing wrong. I want to learn this not have it done for me. Thank you in advance.
import java.util.Scanner;
public class baseBall {
public static void main(String[] args) {
/* A good part of a baseball player's offensive value is captured by the
statistic OPS - the sum of the player's on base percentage and slugging
percentage. An MVP candidate will typically have an OPS above 900,
however if they play a difficult defensive position (catcher, shortstop, or center field)
then they are an MVP candidate if their OPS is above 800. Write a program that will prompt the user for
a player's name, their on base percentage, slugging percentage, and defensive position and report whether the player is an MVP candidate*/
Scanner input = new Scanner(System.in);
System.out.println("Please enter players name: ");
String name = input.next();
System.out.println("Please enter On Base Percentage: ");
double Obp = input.nextDouble();
System.out.println("Please enter slugging Percentage: ");
double Slg = input.nextDouble();
System.out
.println("Please enter position (P,C,1B,2B,3B,SS,LF,CF,RF): ");
String ball = input.next();
String position;
double Ops = Obp + Slg;
if ( position.equalsIgnoreCase("ss")){
if (position.equalsIgnoreCase("cf")){
if (position.equalsIgnoreCase("c")){
System.out.println("MVP Candidate!");
else
System.out.println("NOT an MVP Candidate!);
}
}
}
}
}
Try doing it without nested IFs. Instead, try using Boolean operators like AND and OR.
As previously stated try using a paper first. Try drawing a decision tree to see what and where it might be going wrong.
Your code is checking if the player position is c AND ss AND cf. But the player will be only in one position, it can't be in all the three, so your code will always print "Not an MVP Candidate!".
To make it simple your code is checking if the position is c AND ss AND CF, instead you want to check if the position is c OR ss OR cf.
So you have to use the conditional operator OR -> ||:
if(position.equalsIgnoreCase("ss") || position.equalsIgnoreCase("cf") || position.equalsIgnoreCase("c") {
System.out.println("MVP Candidate!");
} else {
System.out.println("NOT an MVP Candidate!);
}
Your nested ifs will never be true. Think about this logically and on paper.
If position equals ss how can it equal cf and c at the same time? Always ask yourself: "does this make sense?" -- do this before committing code to screen and you'll be golden.
As a side recommendation, please get rid of those distracting // from your question text. They serve no purpose other than to annoy.

Java: Why Doesn't My While Statement Work With My Case 2?

I am trying to create a simple program that outputs the lyrics of a song when the specified number is inputted. The problem is that my second case will not output, but only outputs the first case. When I try to output the second case, it still outputs the first. Regardless if I make two while statement or not, this still happens. Can someone help me fix my code?
Here it is:
import java.util.Scanner;
public class Lyrics {
public static void main (String args[]){
Scanner input = new Scanner (System.in);
int one, two, uone, utwo;
one = 1;
two = 2;
System.out.println("Welcome to the Lyrics Finder!");
System.out.println("Press the number beside the song to see the lyrics!");
System.out.println("1) Thank For The Memories - Fall Out Boy");
System.out.println("2) Take Me To Church - Hozier");
uone = input.nextInt();
utwo = input.nextInt();
switch (one){
case 1:
//code goes here for option 1
System.out.println("");
System.out.println("Thank For The Memories - Fall Out Boy Lyrics");
System.out.println(" == ");
System.out.println("I'm gonna make it bend and break");
System.out.println("Say a prayer but let the good times roll");
System.out.println("In case God doesn't show");
System.out.println("(Let the good times roll, let the good times roll)");
System.out.println("And I want these words to make things right");
System.out.println("But it's the wrongs that make the words come to life");
System.out.println("Who does he think he is?");
System.out.println("Who does he think he is?");
System.out.println("Better put your fingers back to the keys");
//continue song here
break;
case 2:
//retype all code her for it to reset
System.out.println("");
System.out.println("Take Me To Church - Hozier");
System.out.println(" == ");
System.out.println("My lover's got humour, She's the giggle at a funeral");
System.out.println("Knows everybody's disapproval, I should've worshipped her sooner");
System.out.println("If the heavens ever did speak, She's the last true mouthpiece");
System.out.println("Every Sunday's getting more bleak, A fresh poison each week");
System.out.println("We were born sick you heard them say it");
System.out.println("My church offers no absolutes, She tells me Worship in the bedroom");
break;
}
while (uone == one){
System.out.println("");
System.out.println("<-=LYRICS ABOVE=->");
System.out.println("<-=OPTIONS=->");
System.out.println("Press the number beside the song to see the lyrics!");
System.out.println("1) Thank For The Memories - Fall Out Boy");
System.out.println("2) Take Me To Church - Hozier");
uone = input.nextInt();
utwo = input.nextInt();
switch (one){
case 1:
//code goes here for option 1
System.out.println("");
System.out.println("Thank For The Memories - Fall Out Boy Lyrics");
System.out.println(" == ");
System.out.println("I'm gonna make it bend and break");
System.out.println("Say a prayer but let the good times roll");
System.out.println("In case God doesn't show");
System.out.println("(Let the good times roll, let the good times roll)");
System.out.println("And I want these words to make things right");
System.out.println("But it's the wrongs that make the words come to life");
System.out.println("Who does he think he is?");
System.out.println("Who does he think he is?");
System.out.println("Better put your fingers back to the keys");
//continue song here
break;
case 2:
//retype all code her for it to reset
System.out.println("");
System.out.println("Take Me To Church - Hozier");
System.out.println(" == ");
System.out.println("My lover's got humour, She's the giggle at a funeral");
System.out.println("Knows everybody's disapproval, I should've worshipped her sooner");
System.out.println("If the heavens ever did speak, She's the last true mouthpiece");
System.out.println("Every Sunday's getting more bleak, A fresh poison each week");
System.out.println("We were born sick you heard them say it");
System.out.println("My church offers no absolutes, She tells me Worship in the bedroom");
break;
}
}
}
}
When the user types the number one, this should be outputted:
System.out.println("");
System.out.println("Thank For The Memories - Fall Out Boy Lyrics");
System.out.println(" == ");
System.out.println("I'm gonna make it bend and break");
System.out.println("Say a prayer but let the good times roll");
System.out.println("In case God doesn't show");
System.out.println("(Let the good times roll, let the good times roll)");
System.out.println("And I want these words to make things right");
System.out.println("But it's the wrongs that make the words come to life");
System.out.println("Who does he think he is?");
System.out.println("Who does he think he is?");
System.out.println("Better put your fingers back to the keys");
//continue song here
break;
while (uone == one){
System.out.println("");
System.out.println("<-=LYRICS ABOVE=->");
System.out.println("<-=OPTIONS=->");
System.out.println("Press the number beside the song to see the lyrics!");
System.out.println("1) Thank For The Memories - Fall Out Boy");
System.out.println("2) Take Me To Church - Hozier");
When the user types the number 2, this should be outputted:
System.out.println("");
System.out.println("Take Me To Church - Hozier");
System.out.println(" == ");
System.out.println("My lover's got humour, She's the giggle at a funeral");
System.out.println("Knows everybody's disapproval, I should've worshipped her sooner");
System.out.println("If the heavens ever did speak, She's the last true mouthpiece");
System.out.println("Every Sunday's getting more bleak, A fresh poison each week");
System.out.println("We were born sick you heard them say it");
System.out.println("My church offers no absolutes, She tells me Worship in the bedroom");
break;
while (uone == one){
System.out.println("");
System.out.println("<-=LYRICS ABOVE=->");
System.out.println("<-=OPTIONS=->");
System.out.println("Press the number beside the song to see the lyrics!");
System.out.println("1) Thank For The Memories - Fall Out Boy");
System.out.println("2) Take Me To Church - Hozier");
Please note that I am very new to coding, so please try to explain the best that you can. If not, I still may be able to understand, but regardless, please briefly explain your solution.
Change
uone = input.nextInt();
utwo = input.nextInt();
switch (one){
To
int choice = input.nextInt();
switch (choice)

JOptionPane variable might not have been initialized

I'm sorry the code is so long, I just need to know what I'm missing to initialize all my decisions. The compiler is complaining about my variable not being initialized. Thank you.
import javax.swing.JOptionPane;
public class SemesterProject
{
public static void main(String[] args)
{
String SemesterProject =
"Hello and welcome to Juans adventure story! Your choices throughout this story will bring your doom or your salvation!\n"+
"No one has been able to complete this story and lived to tell the tale, but maybe you will be the first one!.\n"+
"Our story begins in the small town of Badow. Many people in the town spread rumors of brave adventurers that\n"+
"go on the quest to solve the mysterious riddles of the abandond castle at the top of the hill.\n"+
"No one really knows who or what lies at the heart of the castle. Legend says that monsters guards the\n"+
"the many riches once owned by the family that died there, so many years ago.\n"+
"The Castle is full of dizzing turns and hidden corridors and dangerous monsters. Many adventureres \n"+
"have gone insane because of how they lose their way or go get stuck. It is the hardes quest known to man.\n"+
"The quest for you is to go to the castle, solve the riddles and claim the riches.\n"+
"The world will little note, nor long remember what we say here, but it can never forget what they did here.\n"+
"Be careful. Watch your back and always mark your trail because you never know what you will find next.\n"+
"If for some crazy reason you end up successful in this task, you will not only get the riches in the castle but\n"+
"you will also be crowned the king of the town of Badow. If you die, you lose.\n"+
"The last thing you have to do is input some of your personal information so that we keep you in our records.\n";
JOptionPane.showMessageDialog(null,SemesterProject);
String name = JOptionPane.showInputDialog(null,"Please give us your first name.");
String age = JOptionPane.showInputDialog(null,"Please give us your age.");
String weight = JOptionPane.showInputDialog(null,"Please give us your weight.");
String haircolor = JOptionPane.showInputDialog(null,"Please give us your hair color.");
String GPA = JOptionPane.showInputDialog(null,"Please give us your GPA.");
String favoritecolor = JOptionPane.showInputDialog(null,"Please give us your favorite color.");
String decision1,decision2,decision3,decision4,decision5,decision6;
decision1 = JOptionPane.showInputDialog("Brave adventurer, welcome to the entrance of the abandoned castle of town Badow. At this moment\n"+
"You have a choice right now to give up and take a walk of shame back to the village, and to safety\n"+
"Or you can decide to go in and test your unique set of skills on the various challenges of the adventure\n"+
"ahead of you. Enter the number of your choice.You can either 1. Enter the castle 2. Stay behind.");
if (decision1.equals("1"))
{
decision2 = JOptionPane.showInputDialog
("You find yourself at the entrance of the castle with a choice to go down a dark hall\n"+
"or to the closest room on the right side. Be vary wary the darkness can make you lose your mind and go insane and remember\n"+
"to keep track of were you are. 1. Into the room 2. Down the hall.");
}
else
{
JOptionPane.showMessageDialog(null,"You go back to your boring life in the town, you wont be remembered by anything and you\n"+
"lost your chance at getting the riches that lie deep in the castle. You lose.");
}
if (decision2.equals("1"))
{
decision3 = JOptionPane.showInputDialog
("You step into the room and find some medication and a lantern with some oil.\n"+
"you also find a sword. You can choose now to go back to the dark hallway or to go down a hidden trap door in the room. It could be\n"+
"a shortcut or it could lead somewhere dangerous. 1. Back down the hall 2. Take your chances with the trapdoor.");
}
else
{
JOptionPane.showMessageDialog(null,"you should have looked in the room, you quickly lose your way and the darkness\n"+
"makes you crazy.");
}
if (decision3.equals("1"))
{
decision4 = JOptionPane.showInputDialog
("You are back in the hall slowly hearing the echoing sound of your footsteps\n"+
"you head downstairs into what seems to be another hallway but this one full of barred rooms, kind of like a dungeon. There is\n"+
"a skeleton body on the ground which seems to be of another failure by an adventurer in the castle. You reach the end of the hall\n"+
"and there is two ways to go left or right. 1. Left 2. Right.");
}
else
{
JOptionPane.showMessageDialog(null,"You squeeze through the trapdoor and fall down to the ground where you find youself lost and disoriented\n"+
"You dont know where you are and start to panic, you start becoming insane and die.");
}
if (decision4.equals("1"))
{
decision5 = JOptionPane.showInputDialog
("You go left and hear a door open behind you, you panic and start to run\n"+
"you run intro different halls to try and escape but you trip. You just remembered that you have a sword with you and can now\n"+
"choose what to do 1. Take out sword and fight enemy 2. Get up and keep running.");
}
else
{
JOptionPane.showInputDialog(null,"You go right and get locked in behind you. You realize that there isnt anwhere to go\n"+
"and get lost in the darkest part of the castle and die alone.");
}
if (decision5.equals("1"))
{
decision6 = JOptionPane.showInputDialog
("You were able to fight of the armored enemy. But something tells you that that isnt the last of them. You continue on down the\n"+"hall and see from the distance to what seems to be your first prize. It cant be that easy.");
}
}
}
Define the decision variables as null. Instead of:
String decision1,decision2,decision3,decision4,decision5,decision6;
Define the variables as:
String decision1 = null;
String decision2 = null;
String decision3 = null;
String decision4 = null;
String decision5 = null;
String decision6 = null;
decision2 is only being set if decision1 is equal to 1. I think you want to put the if statements for the other decisions inside of each other like below:
if (decision1.equals("1"))
{
decision2 = JOptionPane.showInputDialog
("You find yourself at the entrance of the castle with a choice to go down a dark hall\n"+
"or to the closest room on the right side. Be vary wary the darkness can make you lose your mind and go insane and remember\n"+
"to keep track of were you are. 1. Into the room 2. Down the hall.");
if (decision2.equals("1"))
{
decision3 = JOptionPane.showInputDialog
("You step into the room and find some medication and a lantern with some oil.\n"+
"you also find a sword. You can choose now to go back to the dark hallway or to go down a hidden trap door in the room. It could be\n"+
"a shortcut or it could lead somewhere dangerous. 1. Back down the hall 2. Take your chances with the trapdoor.");
}
else
{
JOptionPane.showMessageDialog(null,"you should have looked in the room, you quickly lose your way and the darkness\n"+
"makes you crazy.");
}
}
else
{
JOptionPane.showMessageDialog(null,"You go back to your boring life in the town, you wont be remembered by anything and you\n"+
"lost your chance at getting the riches that lie deep in the castle. You lose.");
}
You must initialize your String variables (decision1, decision2,...) as:
String decision1 = null, decision2 = null, decision3 = null, decision4 = null, decision5 = null, decision6 = null;
Note that you don't get a compile error for decision1 because in the line
decision1 = JOptionPane.showInputDialog(...);
it is being initialized.
Also, your program's logic is bad. If decision1 is not 1, then you will just show a message, but the program will continue to check the next condition:
if (decision2.equals("1"))
where you will get a NullPointerException because you are comparing null with 1.
JOptionPane variable might not have been initialized
So keep in mind one thing that whenever you get such kind of error messages try to see that your variables are properly declared.
See when you try to use int variable it can give you error message if that variable is used in some computation. So try to initialize the variables like:
int a=0;
You can do the same thing with string variables also like:
String a=null;
Returning to answer
In your code you have just declared the variables , but the fact is that you have to actually initialize them.
Replace
String decision1,decision2,decision3,decision4,decision5,decision6;
By
String decision1=null,decision2=null,decision3=null,decision4=null,decision5=null,decision6=null;

Categories