Need help - Java If/Else [duplicate] - java

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).

Related

not executing the if statement even when the condition is true [duplicate]

This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 5 months ago.
I have made a java code to play hangman game. I have given the user 15 chances to guess the word and once the user has guessed the correct answer it should execute the if statement but it does not. I have tried to solve this problem many times but it is never working. I would appreciate it if you could tell me the problem and give a suitable solution without making much change in my code.
My code:
import java.util.*;
public class game
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String list[] = {"apple", "banana", "mango", "kiwi", "coconut", "papaya", "lichi", "strawberry", "orange", "cherry"};
int rand = (int)(Math.random()*9)+0;
String word = list[rand];
String ask = "_";
for(int i = 1; i < word.length();i++){
ask = ask + "_";
}
System.out.println(ask);
System.out.println("hint: It is a fruit");
ArrayList<String> ans = new ArrayList<String>();
for (char i : ask.toCharArray()){
ans.add("_");
}
for (int j = 1; j<=15; j++){
System.out.println("Enter a character: ");
String input = in.next();
char alt = input.charAt(0);
int x = 0;
for (char i : word.toCharArray()){
if(alt == i){
ans.set(x, input);
}
x++;
}
for (String i : ans){
System.out.print(i);
}
int y = 0;
ArrayList<String> answer = new ArrayList<String>();
for (char i : word.toCharArray()){
answer.add("_");
}
for(char i : word.toCharArray()){
String alternate = String.valueOf(i);
answer.set(y, alternate);
y++;
}
if (ans == answer){
System.out.println("\nyou win");
break;
}
System.out.println("\n"+ans);
System.out.println(answer
);
}
}
}
Due to so many many unsuccessful attempts my code may have some unnecessary lines which are making the long.
when you use == it compares whether these two reference variables are pointing to the same object or not.
if you want to compare their content then you should use the equals() method which compares the content of the object, not the object itself.
use ans.equals(answer) instead of ans== answer
Try using equals() method instead of ==.
if (ans.equals(answer)){

Nested If Statement - Not Receiving Expected Output Java [duplicate]

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

Why wont my scanner equal a value in my array? Please help a beginner out [duplicate]

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.

how do you check an input in java is a certain word or character [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have this code:
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number");
String l =reader.next();
String[] a = new String[2];
a[0] = l ;
a[1] = "5";
if((String) a[0] == "5" )
{
System.out.println("hey");
}
however if I enter "5" as my input, "hey" is not printed how do I get it so that I can use an if statment to see if what is entered is a certain character or word
Use a[0].equals("5"), == is just checking if they're the same object rather than string content.
Use nextInt() to get integer
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number");
int l =reader.nextInt();
if(l == 5 )
{
System.out.println("hey");
}
You should to compare array member with equals method, regarding to that is the String.
You should to use this:
if(a[0].equals("5") )
{
System.out.println("hey");
}
instead of
if((String) a[0] == "5" )
{
System.out.println("hey");
}
In that case you will check content, not the reference.

Java While loop won't loop [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
package pack;
import java.util.Scanner;
public class Calculator {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
String cont = "Yes";
while(cont == "Yes" || cont == "yes" ){
System.out.print("Enter a Number: ");
int x = scan.nextInt();
System.out.print("Enter another Number: ");
int y = scan.nextInt();
int diff = x - y;
int sum = x + y;
int prod = x * y;
int quot = x / y;
System.out.println("The Sum is: " + sum);
System.out.println("The Diffrence is: " + diff);
System.out.println("The Product is: " + prod);
System.out.println("The quotient is: " + quot);
System.out.print("Enter Yes to Continue: ");
cont = scan.next();
System.out.println(cont);
}
}
}
This entire code works, but the while loop doesn't repeat. The cont = scan.next(); is catching the string. The output looks like this:
[
Enter a Number: 5
Enter another Number: 6
The Sum is: 11
The Diffrence is: -1
The Product is: 30
The quotient is: 0
Enter Yes to Continue: Yes
Yes
]
Then the program terminates without any problems. All I need it to get the while loop to repeat. Thanks for the help!
Compare Strings with .equals instead of ==
while(cont.equals("Yes") || cont.equals("yes") )
Or even better:
while(cont.equalsIgnoreCase("Yes"))
You need to need to compare the Strings this way:
while("Yes".equalsIgnoreCase(cont))...
That's because when using input, you won't have String literals, but String objects. Those need to be compared via equals() and not ==.
Change
while(cont == "Yes" || cont == "yes" ){
As
while(cont.equalsIgnoreCase("Yes"))
Reason
You need to know the reason behind == and equals()
equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects!. That means, the contents of the objects. Whereas the == operator is expected to check the actual object instances are same or not.
Example with if statement
Consider two different reference variables str1 and str2
str1 = new String("abc");
str2 = new String("abc");
if you use the equals()
System.out.println((str1.equals(str2))?"TRUE":"FALSE");
You will get the output as TRUE
if you use ==
System.out.println((str1==str2)?"TRUE":"FALSE");
Now you will get the FALSE as output because both str1 and str2 are pointing to two different objects even though both of them share the same string content. It is because of new String() everytime a new object is created.
instead of (cont == "Yes" || cont == "yes" ) you should use (cont.equals("Yes") || cont.equals("Yes"))
change to this
while(cont.equalsIgnoreCase("Yes"))

Categories