This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
This a simple program that asks the user for two questions. Based on the user's input, we will display a guess of what the object is. Similar to the game "20 Questions". No matter what input I give the program, it always returns the value of myGuess as "paper clip"
I have tried commenting out the inside of each if/else statement and having the output set to 1,2,3 but it still gets to 3 ( the block of the paper clip). This leaves me to think that my comparison of strings has a bug either in the assignment of the user input or conditional logic... Here is the code:
import java.util.Scanner;
public class JavaTraining {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String input1,input2;
String myGuess;
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I'll try to guess it.\r\n");
System.out.println("Question 1) Is it an animal, vegetable, or mineral?");
input1 = keyboard.nextLine();
System.out.println("\r\nQuestion 2) Is it bigger than a breadbox?");
input2 = keyboard.nextLine();
if (input1 == "animal"){
if (input2 == "yes"){
myGuess = "moose";
}
else{
myGuess = "squirrel";
}
}
else if (input1 == "vegetable"){
if (input2 == "yes"){
myGuess = "watermelon";
}
else{
myGuess = "carrot";
}
}
else{
if (input2 == "yes"){
myGuess = "Camaro";
}
else{
myGuess = "paper clip";
}
}
System.out.println("\r\nMy guess is that you are think of a "+myGuess+".\r\nI would"
+" ask you if I'm right, but I don't actually care."+input1+input2);
}
}
Use .equals() for strings instead of == . Java strings are objects not primitive data types.
change this
if (input1 == "animal")
to
if(input1.equals("animal"))
Take a look at this link
Related
This question already has answers here:
String.equals versus == [duplicate]
(20 answers)
How do I compare strings in Java?
(23 answers)
Closed 11 months ago.
I wrote a function to receive user input. Can't get the correct answer back. Always Failure. I am losing my mind right now.
public String getChoice() {
Scanner SC = new Scanner(System.in);
System.out.print("Ready to play? (Y/N) ");
String playChoice = SC.next(); // Input Y or N
playChoice = playChoice.replace("\n", "");
System.out.println("Input length is: " + playChoice.length());
System.out.println(playChoice);
if (playChoice == "N") {
SC.close();
return "Success N";
}
else if (playChoice == "Y") {
SC.close();
return "Success Y";
}
SC.close();
return "Failure"; // Always this one works
}
Try this:
public String getChoice() {
Scanner SC = new Scanner(System.in);
System.out.print("Ready to play? (Y/N) ");
String playChoice = SC.next(); // Input Y or N
playChoice = playChoice.replace("\n", "");
if (playChoice.equals("N")) { // Replace operator '==' with 'equals()' method.
SC.close();
return "Success N";
} else if (playChoice.equals("Y")) { // Same here.
SC.close();
return "Success Y";
}
SC.close();
return "Failure"; // Always this one works
}
The reason why your code is not working as intended, is that the == operator compares whether the 2 compared object references are pointing to the same object. This obviously is not the case in your if-statements, and therefore those expressions will always evaluate to false.
the equals() method on the other hand actually compares the content of the given objects , thus delivering the desired result.
#Bialomazur gave an explanation already and here is a bit cleaner code and tips.
Actually, closing Scanner is not a good practice, but if you decided to, you can close it before your ifs just in one place, since you are not using scanner anymore.
Also, switch looks better here
public String getChoice() {
Scanner SC = new Scanner(System.in);
System.out.print("Ready to play? (Y/N) ");
String playChoice = SC.next(); // Input Y or N
playChoice = playChoice.replace("\n", "");
System.out.println("Input length is: " + playChoice.length());
System.out.println(playChoice);
SC.close();
switch (playChoice) {
case "Y":
return "Success Y";
case "N":
return "Success N";
default:
return "Failure";
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I've just started java couple of days ago. Im currently following this 'course' http://programmingbydoing.com . Havent had encountered any problems yet but now im stuck at task 32.
heres my code so far (always getting Squirrel instead of moose as output):
import java.util.Scanner;
public class TwoQuestion32 {
public static void main(String[] args) {
boolean animal, vegetable, mineral, smallerthan;
String whatIsIt, biggerThan;
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello and welcome, i've got 2 questions for you!");
System.out.println("Think of an object and i'll try to guess it");
System.out.println();
System.out.println("Question 1) Is it an animal, vegetable or mineral?");
System.out.print(">");
whatIsIt = keyboard.nextLine();
if (whatIsIt == "animal")
animal = true;
if (whatIsIt == "vegetable")
vegetable = true;
if (whatIsIt == "mineral")
mineral = true;
System.out.println("Question 2) Is it bigger than a breadbox?");
System.out.print(">");
biggerThan = keyboard.nextLine();
if (biggerThan == "yes")
smallerthan = false;
if (biggerThan == "no"){
smallerthan = true;}
System.out.print("My guess is that you are thinking of a ");
if (animal = true){
if (smallerthan = true)
System.out.println("squirrel");
}else {
System.out.println("moose");}
}
}
Thanks in advance! Would also love to hear tips how to put up the code in smarter ways. Be friendly, keep in mind i've just started!
Edit: Okay I took another approach. My first attempt was really strange. Thanks for the help!
Heres the working code:
import java.util.Scanner;
public class Questions32 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String whatIsIt, whatIsIt2;
String animal = "animal";
String mineral = "mineral";
String vegetable = "vegetable";
String bigger = "yes";
String smaller = "no";
System.out.println("Hello and welcome, i've got 2 questions for you!");
System.out.println("Think of an object and i'll try to guess it");
System.out.println();
System.out.println("Question 1) Is it an animal, vegetable or mineral?");
System.out.print(">");
whatIsIt = keyboard.nextLine();
System.out.println("Question 2) Is it bigger than a breadbox?");
System.out.print(">");
whatIsIt2 = keyboard.nextLine();
if (whatIsIt.equalsIgnoreCase(animal)){
if (whatIsIt2.equalsIgnoreCase(bigger)){
System.out.println("My guess is that you are thinking of a moose");
}else{ System.out.println("My guess is that you are thinking of a squirrel");
}
}
if (whatIsIt.equalsIgnoreCase(vegetable)){
if (whatIsIt2.equalsIgnoreCase(bigger)){
System.out.println("My guess is that you are thinking of a melon");
}else{ System.out.println("My guess is that you are thinking of a carrot");
}
}
if (whatIsIt.equalsIgnoreCase(mineral)){
if (whatIsIt2.equalsIgnoreCase(bigger)){
System.out.println("My guess is that you are thinking of a Camaro");
}else{ System.out.println("My guess is that you are thinking of a paper clip");
}
}
System.out.println("I would ask you if I'm right, but I dont actually care.");
}
}
in your if-statement you are setting animal to true every time if (animal = true){, instead of checking it (==) .
Also, for Strings you must use .equals() instead of ==.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am fairly new to Java and am in need of help with my If/Else statement. Basically I want to make it so that if the person types in n or no do one thing, or if the person puts in y or yes, do another thing, and if the person doesn't put in n, no, yes or y than do a different thing. But no matter what the user puts in, it acts as if they did not put in n, no, yes or y. How can I fix this?
This is my code so far:
public class Main
{
public static void main (String[] args)
{
Scanner userInputScanner = new Scanner(System.in);
String [] charName = {"John", "Bob", "Sam"};
Random random = new Random();
int charNameChoice = random.nextInt(charName.length);
System.out.println("Random char selected: " + charName[charNameChoice]);
System.out.println("Y N Question1");
System.out.println("You can input y, yes, n or no");
String questionOneAnswer = userInputScanner.nextLine();
if (questionOneAnswer == "n" || questionOneAnswer == "no")
{
System.out.println("I disagree");
}
else if (questionOneAnswer == "y" || questionOneAnswer == "yes")
{
System.out.println("I agree");
}
else
{
System.out.println("Invalid");
}
}
}
You should use equals to compare String values, like stringVar.equals("something").
Better yet, reversing it "something".equals(stringVar) prevents Nullpointerexceptions.
== compares the pointers, which are almost never equal (unless you're comparing String constants).
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
This relates to the method userInput() and its if statements. The output for userInput() is 0 no matter what, why? I know the initial value of calculate = 0; but i want to change it so that each time the user enters "Paper" for example the value of calculate = 1; IVE TRIED EVERYTHING! now im stuck wondering whats wrong with my if statements. Please help. (sorry if i'm a noob)
import java.util.Scanner;
class RPS{
private static String[] userOption = new String[]{"Rock", "Paper","Scissors"};
public static void main(String[] args){
System.out.println("Enter: Rock, Paper Or Scissors");
System.out.println(userInput());
}
public static int userInput(){
int calculate = 99;
Scanner input = new Scanner(System.in);
String userChoice = input.nextLine();
if(userChoice == userOption[0]){
calculate = 0;
} else if(userChoice == userOption[1]){
calculate = 1;
} else if(userChoice == userOption[2]){
calculate = 2;
}
return calculate;
}
}
You have to use the equals Method if you are working with strings.
e.g.:
if(userChoice.equals(userOption[0]))
Because if you use == it checks whether the references to the objects are equal.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
im only 15 and new to java so i am trying to build a simple calculator, but i cant seem to figure out why this if statement is being ignored. I have check to be sure that all values are being stored and yes they are so i can not see any other problems which would explain this. Any help would be great! Look for the comment in the second class //This if statement
The first class
public class CalculatorOperations {
double fnum, snum,answer;
String operation;
void plus(){
operation="+";
answer = fnum + snum;
}
void subtract(){
operation="-";
answer = fnum - snum;
}
void multiple(){
operation="*";
answer = fnum * snum;
}
void divide(){
operation="/";
answer = fnum / snum;
}
void invalidOperation(){
System.out.println("Invalid operation.");
}
void showAttributes(){
System.out.println(fnum);
System.out.println(snum);
System.out.println(operation);
}
}
The second class
import java.util.Scanner;
public class calculatorApplication {
public static void main(String [] args){
CalculatorOperations Operators = new CalculatorOperations();
Scanner userInput = new Scanner(System.in);
String loop2 = null;
boolean loop;
while (loop = true){
// Getting input and storing it
System.out.print("Please enter first number: ");
Operators.fnum = userInput.nextDouble();
System.out.println("TEST:"+Operators.fnum);
System.out.print("Please enter second number: ");
Operators.snum = userInput.nextDouble();
System.out.println("TEST:"+Operators.snum);
System.out.print("Please enter operation (+, -, * or /): ");
Operators.operation = userInput.next();
System.out.println("TEST:"+Operators.operation);
// this if statement
if (Operators.operation == "+") {
Operators.plus();
} else if (Operators.operation == "-") {
Operators.subtract();
} else if (Operators.operation == "*") {
Operators.multiple();
} else if (Operators.operation == "/") {
Operators.divide();
} else {
Operators.invalidOperation();
}
System.out.println("Answer: " +Operators.answer);
System.out.print("Would you like to do another sum? (yes or no): ");
loop2 = userInput.next();
}
if (loop2.equals("yes") || loop2.equals("Yes")){
loop = true;
System.out.println();
System.out.println();
}else{
loop = false;
// Closes scanner to prevent resource leaks
userInput.close();
System.exit(0);
}
}
}
Comparing Strings with == generally doesn't work the way you'd like it to. It's because Strings are Objects and == compares object references against each other, instead of checking if the Strings contain identical text.
Try String.equals instead:
if (Operators.operation.equals("+")) {
... //and of course the same for the rest of the statements
Good luck with your program!
Use the .equals(String) method, instead of ==. Your if-structure would change to this:
if (Operators.operation.equals("+")) {
Operators.plus();
} else if (Operators.operation.equals("-")) {
Operators.subtract();
} else if (Operators.operation.equals("*")) {
Operators.multiple();
} else if (Operators.operation.equals("/")) {
Operators.divide();
} else {
Operators.invalidOperation();
}
.equals(String) is used for comparing strings, whereas == is used for comparing everything else pretty much. == is comparing the reference to an object and .equals(String) is used to compare String values.
Also, change while (loop = true) to while(loop) or while (loop == true); otherwise you are indicating that you are actually changing the value of loop.
You don't want to compare strings with == because by doing that you're comparing the reference of the string, and not the value of the string. You need to use the .equals method.
if (Operators.operation.equals("+"))
From the javadoc:
boolean equals(Object anObject)
Returns true if and only if the argument is a String object that represents the same sequence of characters as this object.
Also, you need to change
while (loop = true)
to
while (loop)
= is the assignment operator, == is the comparison operator.