I'm trying to make a simple code to play Rock, Paper, Scizzors, there is more to the code however this is the important part
int comResult = (int)(Math.random() * 3);
String comChoice;
if (comResult == 0) {
comChoice = "rock";
} else if (comResult == 1) {
comChoice = "scizzors";
} else if (comResult == 2) {
comChoice = "paper";
}
String results;
if (comChoice == humanChoice)
When I get to comparing the computers choice to the humans the computer says that I haven't declared a value for comChoice even though I put it in the if then statement, how do I properly declare the value
You can add an "else" at the end of your condition block to make sure comChoice gets initialized.
if (comResult == 0) {
comChoice = "rock";
} else if (comResult == 1) {
comChoice = "scizzors";
} else if (comResult == 2) {
comChoice = "paper";
} else {
comChoice = "invalid input";
}
You can use switch with default case.
Related
Coding a simple HiLo card game where the user is given a card value from a deck of cards and then inputs 'higher', 'lower' or 'equal' trying to guess the balue of the next card.
Just really can't get my head around user input validation with iteration ie. not moving on until a string with the required parameters has been entered.
My code so far:
import java.util.Scanner;
import java.util.Random;
public class HiLoGame {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
Random randomCard = new Random();
int numberOfSuccesses = 0;
boolean finished = false;
int card = (randomCard.nextInt(13) + 2);
while (finished != true) {
int nextCard = (randomCard.nextInt(13) + 2);
String pictureCard = "";
if (((numberOfSuccesses < 0) ? nextCard : card) == 11) {
pictureCard = "Jack";
} else if (((numberOfSuccesses < 0) ? nextCard : card) == 12) {
pictureCard = "Queen";
} else if (((numberOfSuccesses < 0) ? nextCard : card) == 13) {
pictureCard = "King";
} else if (((numberOfSuccesses < 0) ? nextCard : card) == 14) {
pictureCard = "Ace";
}
System.out.println("The card is a " + ((card > 10) ? pictureCard : card));
if (numberOfSuccesses == 4) {
System.out.println("Congratulations. You got them all correct");
finished = true;
break;
}
while (!reader.nextLine().toLowerCase().equals("higher")
|| !reader.nextLine().toLowerCase().equals("lower")
|| !reader.nextLine().toLowerCase().equals("equal")) {
System.out.println("Try again!");
reader.next();
}
String userGuess = reader.nextLine().toLowerCase();
//TODO validate input
if (userGuess.equals("higher")) {
if (nextCard > card) {
numberOfSuccesses++;
} else {
finished = true;
break;
}
} else if (userGuess.equals("lower")) {
if (nextCard < card) {
numberOfSuccesses++;
} else {
finished = true;
break;
}
} else if (userGuess.equals("equal")) {
if (nextCard == card) {
numberOfSuccesses++;
} else {
finished = true;
break;
}
}
System.out.println(numberOfSuccesses);
card = nextCard;
}
if (numberOfSuccesses < 4) {
System.out.println("Sorry, incorrect!");
}
}
}
and the relevant code extract:
while (!reader.nextLine().toLowerCase().equals("higher")
|| !reader.nextLine().toLowerCase().equals("lower")
|| !reader.nextLine().toLowerCase().equals("equal")) {
System.out.println("Try again!");
reader.next();
}
It kinda just gets stuck at the above part giving "Try again" over and. I've completed programs having to use .hasNextInt() but I'm struggling with this string validation.
Thanks for any and all help/comments!
You are calling reader.nextLine() up to 3 times and so you are comparing 3 different strings.
If I enter "xxx" your code says "xxx != higher so read another line" - it never compares "xxx" to "lower" or "equal".
Also pay attention to && vs ||.
Solution is to read one line into a variable and use that variable for each condition. I'm not going to write it out as this is clearly homework or a self learning exercise, so best for you to do it yourself.
I think your condition logic needs to change. You are checking if input not equal to "higher" or not equal to "lower" or not equal to "equal" so it will always be false overall even if you enter expected value - if you enter "higher" it's not equal to lower. You need to change ors to ands.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
import java.util.Scanner;
public class SneakyDice
{
public static void main(String[] args)
{
game();
}
public static void game()
{
int player1;
int player2;
int p1Final=0;
int p2Final=0;
boolean gameStatus = true;
Die idie1 = new Die();
Die idie2 = new Die();
Die idie3 = new Die();
Die idie4 = new Die();
if (idie1.getNum()==idie2.getNum())
{
if(idie1.getNum()==1)
{
p1Final = 99;
}
else if(idie1.getNum()==2)
{
p1Final = 8;
}
else if(idie1.getNum()==3)
{
p1Final = 12;
}
else if(idie1.getNum()==4)
{
p1Final = 16;
}
else if(idie1.getNum()==5)
{
p1Final = 20;
}
else if(idie1.getNum()==6)
{
p1Final = 24;
}
}
else
{
p1Final = idie1.getNum() + idie2.getNum();
}
player1 = idie1.getNum() + idie2.getNum();
if (idie3.getNum()==idie4.getNum())
{
if(idie3.getNum()==1)
{
p2Final = 99;
}
else if(idie3.getNum()==2)
{
p2Final = 8;
}
else if(idie3.getNum()==3)
{
p2Final = 12;
}
else if(idie3.getNum()==4)
{
p2Final = 16;
}
else if(idie3.getNum()==5)
{
p2Final = 20;
}
else if(idie3.getNum()==6)
{
p2Final = 24;
}
}
else
{
p2Final = idie3.getNum() + idie4.getNum();
}
player2 = idie3.getNum() + idie4.getNum();
while(gameStatus == true)
{
System.out.println("Player 1's roll:" + player1);
System.out.println("Player 2's roll:" + player2);
System.out.println("Player 1's real roll:" + p1Final);
System.out.println("Player 2's real roll:" + p2Final);
System.out.println("Enter the player who rerolls: ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if(input == "p1" || input =="1")
{
Die die1 = new Die();
Die die2 = new Die();
if (die1.getNum()==die2.getNum())
{
if(die1.getNum()==1)
{
p1Final = 99;
}
else if(die1.getNum()==2)
{
p1Final = 8;
}
else if(die1.getNum()==3)
{
p1Final = 12;
}
else if(die1.getNum()==4)
{
p1Final = 16;
}
else if(die1.getNum()==5)
{
p1Final = 20;
}
else if(die1.getNum()==6)
{
p1Final = 24;
}
}
else
{
p1Final = die1.getNum() + die2.getNum();
}
player1 = die1.getNum() + die2.getNum();
}
else if(input =="p2" || input =="2")
{
Die die3 = new Die();
Die die4 = new Die();
if (die3.getNum()==die4.getNum())
{
if(die3.getNum()==1)
{
p2Final = 99;
}
else if(die3.getNum()==2)
{
p2Final = 8;
}
else if(die3.getNum()==3)
{
p2Final = 12;
}
else if(die3.getNum()==4)
{
p2Final = 16;
}
else if(die3.getNum()==5)
{
p2Final = 20;
}
else if(die3.getNum()==6)
{
p2Final = 24;
}
}
else
{
p2Final = die3.getNum() + die4.getNum();
}
player2 = die3.getNum() + die4.getNum();
}
else if(input == "stop" || input == "s")
{
System.out.println("This exists");
gameStatus = false;
}
}
if(p1Final>p2Final) //player1>player2
{
System.out.println("Player One Wins");
}
if(p2Final>p1Final)
{
System.out.println("Player Two Wins");
}
else
{
System.out.println("Tie");
}
}
}
Initial runs of this code work as it is able to print out what the pure rolls of each player are and if they fit in a special case, the actual value it is. My code is never able to make it the gameStatus = false or change a player's roll however as it seems to ignore whatever I type into the console. However, this is able to work the way I intended it to when I remove the special cases where I make the dice roll larger than it should be.
Your problem is with the below line of code,
if(input == "p1" || input =="1")
input, "p1" , "1" etc are string objects, you should use the equals method to perform the comparison.
change it to,
if(input.equals("p1") || input.equals("1"))
Make the same changes to the below too,
else if(input =="p2" || input =="2")
else if(input == "stop" || input == "s")
change these to,
else if(input.equals("p2") || input.equals("2"))
else if(input.equals("stop") || input.equals("s"))
While the use of "==" will sometimes get you want you want during Java String comparison, it's better to simply use the .equals() method.
This answer (https://stackoverflow.com/a/513839/8021378) can explain the full reasoning.
Because of this, none of your inputs would ever equal the conditionals you set, and the loop would run again with the same parameters and inputs it began with. This would give you the impression that your console inputs were being ignored, when they were just simply inequal.
Additionally, you are going to want to be careful with how you set up your final if statements. As of right now you have:
if(p1Final>p2Final) //player1>player2
{
System.out.println("Player One Wins");
}
if(p2Final>p1Final)
{
System.out.println("Player Two Wins");
}
else
{
System.out.println("Tie");
}
With this setup, if player one wins, it will print out "Player One Wins" as well as printing "Tie". This is because you start a whole new if statement block with your second if statement.
To fix this simply change:
if(p2Final>p1Final)
To:
else if(p2Final>p1Final)
That should fix your issue.
I am working on a ROCK PAPER SCISSORS project for class and am trying to use a method which prints who wins the match and also return a value I'm using to determine who has the most wins.
However in the first method when I assign the method to a value to use it it prints out the statements in the evaluate method, is there any way around this or will I have to create another method that does the same thing just with out the print statements?
(userWins and computerWins are declared and initialized in main() )
main( ) {
int userWins = 0;
int computerWins = 0;
.....
int value = winEvaluation(userChoice, computerChoice);
if (value == 1){
userWins++;
} else if (value == 2){
computerWins++;
} else{
}
System.out.prinln("user wins: " + userWins + " computer wins: " + computerWins);
}
private static int evaluate(int userChoice, int computerChoice) {
int winValue = 0;
String win = "You win.";
String lose = "I win.";
String draw = "We picked the same thing! This round is a draw.";
if( userChoice == 1) {
if(computerChoice == 1){
System.out.println(draw);
winValue = 0;
}else if(computerChoice == 2){
System.out.print("PAPER covers ROCK." );
System.out.println(lose);
winValue = 2;
}else {
System.out.print("ROCK breaks SCISSORS.");
System.out.println(win);
winValue = 1;
}
}else if (userChoice == 2 ) {
if (computerChoice == 1){
System.out.print("PAPER covers ROCK.");
System.out.println(win);
winValue = 1;
}else if (computerChoice == 2){
System.out.println(draw);
winValue = 0;
}else {
System.out.print("SCISSORS cuts PAPER.");
System.out.println(lose);
winValue = 2;
}
}else if (userChoice == 3){
if (computerChoice == 1){
System.out.print("ROCK breaks SCISSORS.");
System.out.println(lose);
winValue = 2;
}else if (computerChoice == 2){
System.out.print("SCISSORS cuts PAPER.");
System.out.println(win);
winValue = 1;
}else {
System.out.println(draw);
winValue = 0;
}
}
return winValue;
}
For this assignment, I need to accept a lock combination and check if:
It is 9 chars long
At position 2,8 the char is R or r
At position 5 the char is l or L
All of the other positions are integers 0-9
I am wondering if there is a better way to do this than checking each position for a digit?
Scanner input = new Scanner(System.in);
String lockComb;
System.out.print("Please enter a lock combination ( ddRddLddR ): ");
lockComb = input.nextLine();
if((lockComb.length() == 9) && ((lockComb.charAt(2) == 'r') || (lockComb.charAt(2) == 'R')) &&
((lockComb.charAt(5) == 'l') || (lockComb.charAt(5) == 'L')) && ((lockComb.charAt(8) == 'r')
|| (lockComb.charAt(8) == 'R')))
{
if((Character.isDigit(lockComb.charAt(0))) && (Character.isDigit(lockComb.charAt(1))) &&
(Character.isDigit(lockComb.charAt(3)) && (Character.isDigit(lockComb.charAt(4))) &&
(Character.isDigit(lockComb.charAt(6))) && (Character.isDigit(lockComb.charAt(7)))))
{
System.out.println(lockComb + " is a valid lock combination!");
}
else
{
System.out.println(lockComb + " is not a valid lock combination!");
}
}
else
{
System.out.println(lockComb + " is not a valid lock combination!");
}
To simplify things, you can use a regular expression:
if (lockComb.matches("[0-9][0-9][rR][0-9][0-9][lL][0-9][0-9][rR]")
(That's lowercase-l and uppercase-L in the middle.)
(No need to check the length, which is implicitly defined by the regular expression.)
How about just for fun a solution that doesn't involve regular expressions. I'm not arguing at all for or against just merely a different solution. One thing you do lose if using a regular expression is the ability to tell exactly why this is not a valid lock combination. It's up to you to figure out what the best solution is given the scenario you are coding for.
public static boolean matcher (String lockComb) {
if(lockComb.length() != 9) {
System.out.println(lockComb + " is not a valid lock combination!");
return false;
}
boolean isValid = true;
char[] comb = lockComb.toUpperCase().toCharArray();
for (int i = 0; i < comb.length; i++) {
switch (i) {
case 2:
case 8:
isValid = (comb[i] == 'R');
break;
case 5:
isValid = (comb[i] == 'L');
break;
default:
isValid = Character.isDigit(comb[i]);
break;
}
if(isValid == false) break;
}
if(isValid) {
System.out.println(lockComb + " is a valid lock combination!");
} else {
System.out.println(lockComb + " is not a valid lock combination!");
}
return isValid;
}
i'm really not sure what's wrong with my code. It's supposed to do rock paper scissors against the computer by taking in the user choice, comparing it to the random computer choice, and displaying the results.
I get two errors that i have no return statements for the 3rd and 4th methods. Also, when i run it without fixing the errors, the nested if statements starting at line 60 only print out one of the two println statements, which really makes zero sense to me.
import java.util.Random;
import java.util.Scanner;
public class Chapter5ProjectPart2 {
public static void main(String[] args) {
Random generator = new Random();
Scanner keyboard = new Scanner(System.in);
int userNum;
int compNum;
String userChoice = "";
String compChoice = "";
int rnum;
int result = 0;
boolean keepPlaying;
int input = 1;
do
{
compNum = generator.nextInt(2)+1;
compChoice = numToChoice(compNum);
menu();
userNum = keyboard.nextInt();
userChoice = numToChoice(userNum);
keyboard.nextInt();
System.out.println();
System.out.println("you chose " + userChoice);
System.out.println("the computer chose " + compChoice);
result = resultCheck(userNum, compNum);
if (result == 1) // user wins
{
if (userNum == 1) //user won choosing rock
{
System.out.println("rock beats scissors");
System.out.println("you win");
}
else if (userNum == 2) //user won choosing paper
{
System.out.println("paper beats rock");
System.out.println("you win");
}
else if (userNum == 3) //user won choosing scissors
{
System.out.println("scissors beats paper");
System.out.println("you win");
}
}
else if (result == 3) //user loses
{
if (userNum == 1) //user lost choosing rock
{
System.out.println("paper beats rock");
System.out.println("you lose");
}
else if (userNum == 2) //user lost choosing paper
{
System.out.println("scissors beats paper");
System.out.println("you lose");
}
else if (userNum == 3) //user lost choosing scissors
{
System.out.println("rock beats scissors");
System.out.println("you lose");
}
else if (result == 2) //draw
System.out.println("draw");
}
System.out.println("would you like to play again?");
System.out.println("1 = yes");
System.out.println("2 = no");
input = keyboard.nextInt();
keepPlaying = play(input);
} while (keepPlaying == true);
}
// method 1 (menu)
public static void menu()
{
System.out.println("Enter your choice of rock, paper, or scissors\n" + "1 = rock\n" + "2 = paper\n" + "3 = scissors");
}
// method 2 (result check)
public static int resultCheck(int userNum, int compNum)
{
if (userNum == 2 && compNum == 1)
return 1;
else if (userNum == 1 && compNum == 3)
return 1;
else if (userNum == 3 && compNum == 2)
return 1;
else if (userNum == compNum)
return 2;
else
return 3;
}
// method 3 (converting number choice to rock/paper/scissors
public static String numToChoice(int num)
{
if (num == 1)
return "rock";
else if (num == 2)
return "paper";
else if (num == 3)
return "scissors";
}
//method 4 (play again)
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
}
}
I get two errors that i have no return statements for the 3rd and 4th methods.
Right. Let's look at the third:
public static String numToChoice(int num)
{
if (num == 1)
return "rock";
else if (num == 2)
return "paper";
else if (num == 3)
return "scissors";
}
Suppose num isn't 1, 2, or 3? Then what should the return value of the method be? That's why you're getting the error, you need a final else (with no if) saying what that return value should be when none of the earlier branches has returned a value. Without it, the method causes a compile-time error.
Also, when i run it without fixing the errors, the nested if statements starting at line 60 only print out one of the two println statements, which really makes zero sense to me.
You can't run it without fixing the errors, because these are compile-time errors. If you try to compile this source code with those errors in place, it fails, and you don't get an updated class file. So if you then try to run, and it seems to work, you're running an earlier copy of the class file you compiled before those errors were there. That class file doesn't relate to the current source code, and so it's understandable that it would make no sense to you. You're not looking at what the JVM is running.
If you correct the methods so that things compile (by adding the final else with no if on it), then run the compiled result, things should make more sense. Meanwhile, you might want to delete the previous Chapter5ProjectPart2.class file, since it's out of date.
public static String numToChoice(int num)
{
if (num == 1)
return "rock";
else if (num == 2)
return "paper";
else if (num == 3)
return "scissors";
}
//method 4 (play again)
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
}
These methods should always return something. Method 3 for example, if int num is 4 it won't return anything. Solve it by adding:
else return "";
That's because you are not ending your else-if statement in methods 3 and 4 with an else clause.
You indeed lack return statements. Java expects a non-void method to always return a value or throw an exception. Having a non-void method end without returning or throwing an exception is an error.
public static String numToChoice(int num)
{
if (num == 1)
return "rock";
else if (num == 2)
return "paper";
else if (num == 3)
return "scissors";
}
Here, your method doesn't return anything if num isn't 1, 2 or 3. Likewise:
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
}
Here inputs that aren't 1 or 2 lack their return statements.
First of all, never run code that doesn't compile.
Second: examine this method:
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
}
What would the method return if input is 6, or -67, or 789? You didn't tell, and the compiler can't guess it. So it refuses to compile until you tell it what to return in these cases.
If the other cases should never happen, then throw an exception:
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
else {
throw new IllegalStateException("input is " + input + ". Something's really wrong");
}
}
Java method MUST return a value unless it states void as return.
In your play method, if input is not 1 or 2, Java won't return any value. This does not allow to compile in Java.
In your numToChoice method, if num is not 1, 2 or 3, Java won't return any value. This does not allow to compile in Java.
Add an else close to return a value in "unexpected" cases, and allow Java to compile.