Problem with if statements
MOVED TO Loops & Control Statements SUB-FORUM
http://www.javaprogrammingforums.com...html#post41860
So I was sitting in the living room last night on my laptop and my sister was watching some rubbish on the television. A show called something like 'Red & Blue'. The basis of the game is that people choose either a red or a blue box and depending on which one they choose, they win or lose. I was in awe at how melodramatic the whole show was and how it was generally ridiculous. It led me to think "Hey! That seems simple enough, I could code a program to do that!" Which leads me onto the Java
I can't get my head around what on Earth is wrong with this code. I think the problem lies in the first if statement, but I can't work out what it is. It's especially odd that the error message that I set up as the 'else' of that statement also outputs. There are no compiler errors thrown, so it's compiling ok (duh), but just not doing what I want it to.
I've sat staring at the screen for ages but can't work it out. This problem has thus been the catalyst for me finally joining a dedicated java forum. Any help would be fantastic, thank you! ~o) ~o) ~o)
Code :
import java.util.Scanner;
import java.util.Random;
class apples {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random dice = new Random();
String userGuess;
System.out.println("Which will it be? Red or blue? Enter your guess NOW! (r/b): ");
userGuess = input.nextLine();
int userGuessInt = 0;
if (userGuess == "r") {
userGuessInt = 0;
}
else if (userGuess == "b"){
userGuessInt = 1;
}
else {
System.err.println("You were supposed to guess either \"b\" or \"r\", nigga!");
}
int number = dice.nextInt(2);
if (number == 0){
System.out.println("It's red!");
}
else {
System.out.println("It's blue!");
}
if (number == userGuessInt){
System.out.println("You win!");
}
else {
System.out.println("You lose! Now go cry over a fucking gameshow like a freaking idiot...");
}
}
}
Output:
Code :
Which will it be? Red or blue? Enter your guess NOW! (r/b):
r
It's blue!
You lose! Now go cry over a fucking gameshow like a freaking idiot...
You were supposed to guess either "b" or "r", nigga!
Re: Problem with if statements
Quote:
if (userGuess == "r") {
Use the equals() method when comparing the contents of objects, like Strings.
Re: Problem with if statements
*Searches 'equals()' in the API*
I'll give it a shot, ta.
Re: Problem with if statements
Just found this for anyone else having a similar problem: Java: ==, .equals(), compareTo(), and compare()
Re: Problem with if statements