Java Rock Paper Scissors [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
looked at the other thread but I could not figure out why my program after i input my choice i.e. Rock The program either gives 2 answers or none at all. I know its similar to a previous thread but I don't understand why the reply varies. Any help would be appreciated.
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
System.out.println("Do you want to play Rock Paper Sissors?");
System.out.println("Yes or No?");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
if (input.equals("Yes")){
System.out.println("OK pick your weapon!");
String weapon = scan.nextLine();
Random rand = new Random();
rand.nextInt(3);
if (rand.nextInt(3) == 0){
//*0=Rock
if (weapon.equals("Rock")) {
System.out.println("I choose Rock, so did you... tie.");
}
else if (weapon.equals("Paper")){
System.out.println("I choose Rock and you choose Paper...You Win :( !");
}
else if (weapon.equals("Scissors")){
System.out.println("I choose Rock and you choose Paper...You Lose :) !");
}
}
if (rand.nextInt(3) == 1){
//*1=Paper
if (weapon.equals("Rock")) {
System.out.println("I choose Paper and you choose Rock...You Lose :) !");
}
else if (weapon.equals("Paper")){
System.out.println("I choose Paper, so did you...tie.");
}
else if (weapon.equals("Scissors")){
System.out.println("I choose Paper and you choose Scissors...You Win :( !");
}
}
if (rand.nextInt(3) == 2){
//*2=Scissors
if (weapon.equals("Rock")) {
System.out.println("I choose Scissors and you choose Rock...You Win :( !");
}
else if (weapon.equals("Paper")){
System.out.println("I choose Scissors and you choose Paper...You Lose:) !");
}
else if (weapon.equals("Scissors")){
System.out.println("I choose Scissors, so did you...tie.");
}
}
}
else {
System.out.println("OK have a nice day.");
}
}
}
Thanks for helping.

You have three if statements each generating their own random value, so it's possible for all three if statements to be executed. You should save off the result of rand.nextInt(3) once, and use that in the three consecutive if statements. I would change the three if statements in a row to a series of if/else if statements as well.
You seem to almost have the correct solution down where you call
rand.nextInt(3);
once before the initial if statements, just save that result to a variable.

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();

Someone have a look at my source code for a number guessing game that seems to keep failing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Hello please may someone run my code and assist me in debugging it. I'm having a lot of troubles trying to figure it out and i have not a lot of guidance when it comes to coding.
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
reccomendations to fix it. Thanks in advance
a brief of what i'm trying to do:
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
import javax.swing.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
/*
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
recomendations to fix it. Thanks in advance
*/
enterScreen();
if (enterScreen() == 0){
number();
userIn();
answer();
}
}
public static int enterScreen (){
String[] options = {"Ofcourse", "Not today"};
int front = JOptionPane.showOptionDialog(null,
"I'm thinking of a number between 0 and 100, can you guess what is is?",
"Welcome",
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE,
null, options, "Yes" );
if(front == 0){
JOptionPane.showMessageDialog(null, "Goodluck then, you might need it. :D");
}
else {
JOptionPane.showMessageDialog(null, "okay i dont mind");
}
return front;
}
private static int number(){
double numD;
numD = (Math.random() * Math.random()) * 100;
int numI = (int) numD;
System.out.println(numD);
return numI;
}
private static int userIn(){
String userStr = JOptionPane.showInputDialog("What number do you think im thinking of?");
int user = Integer.parseInt(userStr);
return 0;
}
private static void answer(){
// here is the problem
if(userIn() == number()){
JOptionPane.showMessageDialog(null, "Well done! You must be a genius.");
}
else {
JOptionPane.showMessageDialog(null, "Shame, TRY AGAIN!");
userIn();
}
}
}
Your problem is this part:
enterScreen();
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You can leave out the first enterScreen(). Because you call it again in the if statement. If you look at the return type of the method: public static int, it returns and int. This makes it so that the outcome of the method is directly available in the if statement. The fist enterScreen is basicly useless, because you dont use the result.
You could do this:
int num = enterscreen();
if (num == 0) {
number();
userIn();
answer();
}
Which is basicly the same as:
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You call enterScreen() twice. Just call it once, and compare the value returned only once.
Also, StackOverflow typically is not for "Here's my code, fix it" kind of not questions.
https://stackoverflow.com/help/how-to-ask
You call enterScreen() and userIn() functions twice or more. Please Computer Science and coding. Hint: Computer's execute intructions from top to bottom.

Black Jack Java

I'm trying to write a black jack program in Eclipse and I'm having an issue when the program deals an Ace. I asked the user if they want the Ace to be worth 1 or 11. It does that, but when I type in a value, it gives an error message
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at PlayBlackJack.main(PlayBlackJack.java:72)"
Could someone help with that? I have a separate class that if the random card generated is an ace, it returns the value of 11. Here's that part of the code
Update: It adds the value of the Ace to the user's total. But after an Ace is dealt and the user chooses a value, no matter what the total is, it stops the users turn and goes to the dealer. How can I correct this? Also another issues I am having is After the user says 'no' to wanting another card, it goes to the dealer and works fine, but then when asking the user if they want to play again, it goes into an infinite loop and starts throwing out random cards. How can I correct this issue also?
import java.util.Scanner;
public class PlayBlackJack {
public final static int MAXCARDS=52;
//declaring the constant maxcards to be 52
//since there are 52 cards in the deck
public static void main(String[] args) {
Scanner kbd=new Scanner (System.in);
String printRules;
//check to see if the user wants to see the rules or not
String more;
//variable used to see if the user would like to play the game
String next;
//variable used to see if the user would like another card
int dealerTotal, userTotal;
//keeps track of the user's total and the dealer's total
int wins=0, losses=0;
//variables used to keep track of the user's wins and losses
int card = 0;
System.out.println(" Welcome to Black Jack!");
System.out.println("Would you like to see the rules? Type yes or no");
//If yes, rules printed, if no, rules not printed
printRules=kbd.nextLine();
printRules=printRules.toUpperCase();
if (printRules.charAt(0)=='Y')
{
(print rules)
System.out.println("Now lets play!\n\n\n");
}
System.out.println("Would you like to play a game of Black Jack?");
more=kbd.nextLine();
more=more.toUpperCase();
next="Yes";
while (!more.isEmpty() && more.charAt(0)=='Y')
{
System.out.println("The game begins with this your first card:");
userTotal=0;
dealerTotal=0;
while (!next.isEmpty() && next.charAt(0)=='Y')
{
card=PickACard.findCardValue();
if (card==11)
{
System.out.println("Would you like the Ace to be a 1 or 11?");
int aceValue=kbd.nextInt();
while (aceValue!=1 && aceValue!=11)
{
System.out.println("You did not enter a 1 or 11");
aceValue=kbd.nextInt();
}
card=aceValue;
}
userTotal=userTotal+card;
System.out.println("You're total is " +userTotal);
if (userTotal>21)
{
System.out.println("Sorry, You lose");
losses++;
System.out.println("Would you like to play again?");
next="No";
more=kbd.nextLine();
more=more.toUpperCase();
}
else
{
System.out.println("Would you like another card?");
next=kbd.nextLine();
next=next.toUpperCase();
}
}
while (dealerTotal<=userTotal && userTotal<21)
{
System.out.println("Now it's the dealer's turn");
int card1=0;
card1=PickACard.findCardValue();
if (card1==11)
{
int aceValue1;
if (dealerTotal+11>21)
{
aceValue1=1;
}
else
{
aceValue1=11;
}
card1=aceValue1;
}
dealerTotal=dealerTotal+card1;
System.out.println("The dealer's total is "+dealerTotal);
if (dealerTotal==userTotal && userTotal<21)
{
losses++;
System.out.println("Sorry, you lose. Would you like to play again?");
more=kbd.nextLine();
more=more.toUpperCase();
}
if (dealerTotal>21)
{
wins++;
System.out.println("You Win! Would you like to play again?");
more=kbd.nextLine();
more=more.toUpperCase();
}
/*else
{
losses++;
System.out.println("You lose. Would you like to play again?");
more=kbd.nextLine();
more=more.toUpperCase();
}*/
}
}
System.out.println("You won "+wins+" game(s) and lost "+losses+" game(s)");
kbd.close();
}
}
I think that because you are using kbd.nextInt() to get the Ace value there is a new line character is left in the buffer so when the loop goes around kbd.nextLine() returns new line character and not Y that might be causing an issue with more.charAt(0) You might have to add an extra kbd.nextLine(); to get rid the new line character. Also as Elliot Frisch pointed out you should check if the string is empty in the while control statement.
while(!more.isEmpty() && more.charAt(0) == 'y')
{
}
I guess next.charAt(0) is showing the error. You can try to do kbd.nextLine(); right before you ask would you like another game and also check if next is not empty.
while(!next.isEmpty() && more.charAt(0) == 'y')
{
}
Try this
System.out.println("Sorry, You lose");
losses++;
System.out.println("Would you like to play again?");
next="No";
kbd.nextLine(); // to flush out new line character
more=kbd.nextLine();
more=more.toUpperCase();
You can also use nextLine() and parse it to int that will avoid the new line character issue.
aceValue = Integer.parseInt(kbd.nextLine());
I can't tell which line is line 72 of your code, but I can tell you that it's pretty likely based on what you've given us that somehow either your more or next variables are becoming empty strings (i.e. ""). If you try and call charAt(0) for a 0-length String, you'll get a StringIndexOutOfBoundsException.

Java If Statements - Beginner [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
So slowly relearning java since I've forgotten all of it from college. I've always wondered if I do my loops in a weird way. I feel there has to be a better way to do loops. I'm pretty sure I always make them far longer than they should be. Anyways I'm following http://programmingbydoing.com/a/twenty-questions.html as it makes me have to google a lot and forces me to come to an understanding rather than just copying code. I'm on this 20 questions part (the link). Here is the code I wrote for it, which works. But is there a better way I could do this? Or what are the other possible ways I could have done this. Does && count as a nested if statement.
edit* Come to think of it. Any critiques at all are welcome. Not necessarily just my loops. If there is anything I am doing the long version of or anything that I'm doing a strange way please let me know.
*edit2. Whoops sorry. Did not know there was a codereview area. Would have posted there if I knew it existed.
import java.util.Scanner;
public class TwoQuestions
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
String answerOne, answerTwo;
System.out.println("Two questions game!");
System.out.println("Think of an object, and I'll try to guess it");
System.out.println("");
System.out.println("");
System.out.println("Question 1 - Is it an animal, vegetable, or random thing?");
answerOne = keyboard.next();
System.out.println("");
System.out.println("Question 2 - Is it bigger than a breadbox?");
answerTwo = keyboard.next();
if (answerOne.equals("animal") && answerTwo.equals("yes"))
{
System.out.println("You are thinking of a moose!");
}
else if (answerOne.equals("animal") && answerTwo.equals("no"))
{
System.out.println("You are thinking of a squirrel");
}
else if (answerOne.equals("mineral") && answerTwo.equals("yes"))
{
System.out.println("You are thinking of a Camaro");
}
else if (answerOne.equals("mineral") && answerTwo.equals("no"))
{
System.out.println("You are thinking of a paper clip");
}
else if (answerOne.equals("vegetable") && answerTwo.equals("yes"))
{
System.out.println("You are thinking of a watermelon");
}
else if (answerOne.equals("vegetable") && answerTwo.equals("no"))
{
System.out.println("You are thinking of a carrot");
}
else
{
System.out.println("Please make sure you are spelling correctly, no caps");
}
}
}
There is nothing wrong with your conditional statements, but those aren't loops.
Read this for information on loops: http://www.tutorialspoint.com/java/java_for_loop.htm
For your else case, you should ask the user for another input so they don't have to rerun the program if they make a typo.

Categories