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

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);
}

Related

I'm trying to get a toString to print out in a group together after a loop is cancelled [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
This is what I have so far and I tried to use the while (yorn=="yes") to cancel but it keeps going regardless and I am also trying to find a way to make it so the outputs go in one group together rather than being seperated.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String no = "no";
String yes = "yes";
String yorn="yes";
CollegeStudent Student1 = new CollegeStudent();
while (yorn=="yes") {
System.out.println("continue? yes/no:");
yorn=scan.next();
Student1.setname();
Student1.setcourseTitle();
Student1.setcredits();
Student1.setcourseCode();
System.out.println(Student1.toString());
}
}
}
You need to use the equals method for string comparing in the java:
while (yorn.equals("yes"))
{
System.out.println("continue? yes/no:");
yorn=scan.next();
Student1.setname();
Student1.setcourseTitle();
Student1.setcredits();
Student1.setcourseCode();
System.out.println(Student1.toString());
}
Since after you answer exists the logic in the cicle, after yes typing code has been executing anyway (one time). Simply solution for you will be:
System.out.println("Do you need to add a student? yes/no:");
yorn=scan.next();
while (yorn.equals("yes"))
{
Student1.setname();
Student1.setcourseTitle();
Student1.setcredits();
Student1.setcourseCode();
System.out.println(Student1.toString());
System.out.println("continue? yes/no:");
yorn=scan.next();
}

Using Strings in a If, else statements JAVA [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
I'm trying to make a program that can read whatever the user inputs and checks their input using if..else statement.
import java.util.Scanner;
class Answers{
public void FalseAnim() {
System.out.println("Game Over your answer is wrong. try again!");
}
public void CorrectAnim() {
System.out.println("your answer is correct");
}
}
public class quizgame {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
Answers ans = new Answers();
String strans1;
System.out.println("welcome to the quiz game!");
System.out.println("what is 1+1");
strans1 = input.nextLine();
if (strans1=="two"||strans1=="2") {
ans.CorrectAnim();
}
else {
ans.FalseAnim();
}
}
}
every time I run the program and input anything it goes straight into the else statement, even when I input either a "2" or a "two"
if ("two".equals(strans1)||"2".equals(strans1))
will work.
In your code, you are comparing references and not the value. Hence it is returning false either way.

Stuck with creating if statement from string input [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am trying to learn Java and want it so you input your name, and if name input matches your name it will print Hello [your name], I am doing this using an if statement and make if so if the input is equal to a string equal to my name it will print hello plus the input. However it doesn't... the else statement is what confuses me because I got it to print the two value to see if they where equal and they both where... help would be appreciated thanks.
package AgeTester;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class HelpSystem {
public static void main(String args[]) {
String inp = "Jono";
JFrame frame = new JFrame("Input Dialogue");
String name = JOptionPane.showInputDialog(frame, "What is your name?");
if (inp == name) {
System.out.printf("Hello", name);
} else {
System.out.println(inp + name);
}
System.exit(0);
}
}
When you compare two strings you should use the .equals(String) method
if (inp.equals(name)) {
remember: == tests for reference equality (whether they are the same object).
You're not using the equals() method, it's what we use to comapre strings in Java not ==.
if (inp.equals(name)) {
System.out.printf("Hello", name);
} else {
System.out.println(inp + name);
}

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.

While loop skipping over if statements? [duplicate]

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();

Categories

Resources