While loop skipping over if statements? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
This is a program that runs a Conways Game of Life simulation.
The main method is here:
public static void main(String Args[]) {
int x = 0;
int y = 0;
boolean cellState[][] = new boolean[][]{};
boolean newCellState[][] = new boolean[][]{};
String answer;
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("\n Type anything for next generation, 'new' for new grid, or 'stop' to end>> ");
answer = input.nextLine();
if (answer == "new") {
cellState = newCells(cellState);
} else if (answer == "stop") {
break;
} else {
System.out.println("Not an option yet");
}
}
}
No matter what answer is entered it will skip past the if statements and return to the beginning of the loop.
It has nothing to do with the actual contents of the statements as far as I can tell, but its might have to do with the boolean expressions.

You should use .equals() to compare Strings and not ==.
== is used to check object references, while .equals() checks the String values.
Use: if(answer.equals("new")) and you should be golden.
It has been explained very thoroughly here.

I'll recommend to do it like this:
if ("new".equals(answer)) {
cellState = newCells(cellState);
} else if ("stop".equals(answer)) {
break;
} else {
System.out.println("Not an option yet");
}

Strings can be compared with == as well, if and only they are internalized. Strings initialized with double quotes are already internalized.
So, in your case, you can do just this.
answer = input.nextLine().intern();

Related

Java - IF condition not reading entered String variable value [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String play = "y";
System.out.print("Enter something: ");
play = scan.next();
System.out.println(play);
if (play == "Y" || play == "y")
{
System.out.println("If test works!!");
}
System.out.println("Did it work???");
}
}
I assume this has something to do with when I press enter, it's storing that as well. I tried changing String play to a char, but then I get errors from Scanner saying it can't change a String to a char.
You should atmost avoid using “==“ when comparing objects especially strings. “==“ checks for object references. Change the comparison to use .equals method and it should work
if(play.equals(“Y”) || play.equals(“y”))
in case if “play” can be null, the below snippet is more safe.
if(“Y”.equals(play) || y.equals(play))

Java: Why does if statement never resolve to true? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am trying to make a noughts-and-crosses prototype. The section of code I am struggling with is getting an user input, and if the input is y, it should change the gamestate to 0 which restarts the game. However this doesn't happen. Can anyone explain why?
Scanner s = new Scanner(System.in);
System.out.println("Would you like to play again?");
if (s.next().toLowerCase() == "y") {
System.out.println("Okay");
g.gamestate = 0;
} else {
g.gamestate = 4;
}
Try to use s.next().toLowerCase().equals("y")
Operator "==" comparing the links on your string objects, and method "equals" comparing values.
Yes, as somebody commented the solution is need to use equals() instead of ==.
Scanner s = new Scanner(System.in);
System.out.println("Would you like to play again?");
if (s.next().equalsIgnoreCase("y")) {
System.out.println("Okay");
//g.gamestate = 0;
} else {
System.out.println("No");
// g.gamestate = 4;
}

Program not noticing when the string is equal to a specific string [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I've been trying to create a program that censors a word but I was having difficulty with that so I tried going back to some of the fundamental code and testing it and I am coming across an odd result.
import java.util.Scanner;
public class TextCensor
{
public static void main(String[] args)
{
String input;
Scanner keyboard = new Scanner(System.in);
input = keyboard.nextLine();
int length = input.length() - 1;
if (length + 1 >= 3)
{
for (int i=0; i<(length - 1); i=i+1 )
{
char first = input.charAt(i);
char second = input.charAt(i+1);
char third = input.charAt(i+2);
String censorCheck = "" + first + second + third;
if (censorCheck == "tag")
{
System.out.println("success");
}
else
{
System.out.println(censorCheck);
}
}
}
else
{
System.out.println(input);
}
}
}
If I input the string "adtag" I will obtain the following output:
adt
dta
tag
yet "success" will never be printed despite the fact that I have printed a censorCheck that is equal to "tag".
String is an object. You have to compare objects by equals():
censorCheck.equalsIgnoreCase("tag")
Ignore case works fir upper letters as well.
Only for primitives you can use comparison by ==:
3 == 3
You are trying to check whether both instance of String is same or not instead of checking contents of both string.
You should try censorCheck.equals("tag") .
To compare whether contents of two string are equal or not in JAVA you should use the equals() method. You cannot compare the value of two string by the == operator . In your case use if (censorCheck.equals("tag")) and see if you get the desired result.

Never runs `if` , always `else` [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
For some reason, my (basic) program always prints the text I reserved for my else statement.
I am a newb when it comes to Java, so if I am making an obvious mistake I apologize. I also searched high and low for an answer, but couldn't find one. Could you take a look at this:
package test;
import java.util.Scanner;
public class tutorial_7 {
private static Scanner x;
public static void main(String args []) {
x = new Scanner(System.in);
System.out.print("Apples, or oranges: ");
String bog = x.next();
if (bog == "Apples") {
System.out.print(1);
}
if (bog == "Oranges") {
System.out.print(2);
}
else {
System.out.print(3);
}
}
}
}
Why is the text reserved for my if statements never being output? Everything seems to be fine.
Regards,
JavaNoob
Don't use == to compare strings, it's for object identity.
Comparing strings should be done with the equals() method, such as:
if (bog.equals ("Oranges")) {
How do I compare strings in Java?
if (bog.equals("Apples")){
System.out.print(1);
}
if (bog.equals("Oranges")){
System.out.print(2);
}
else{
System.out.print(3);
}

Java If loop don't get executed: Scanner [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
My second scanner input get stored as desired but still the if condition comparing correctString == stringValue is not executed.
Could you help.
{
static String stringValue = "A";
public static void main(String[] args) {
int time;
time = speedType();
//System.out.println(time);
}
private static int speedType() {
System.out.println("Let's play a game\nHow fast can you type \"I type very quickly\" \nPress Enter then type the statement and then press Enter again");
Scanner scanner = new Scanner (System.in);
String string = scanner.nextLine();
if(string.equals("")){
Date startTime = new Date();
System.out.println("Start:\n");
String correctString = scanner.nextLine();
System.out.println(correctString);
if (correctString == stringValue){
Date endTime = new Date();
System.out.println(endTime);
}
else
System.out.println("Please enter correct string");
}
return 0;
}}
Regarding,
if (correctString == stringValue){
Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in right now. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if ("bar".equals(fu)) {
// do something
}
or,
if ("bar".equalsIgnoreCase(fu)) {
// do something
}

Categories

Resources