This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
My if-then-else statement is always outputting the else outcome
import java.util.Scanner;
public class NiallScanner {
public static void main(String[] args)
{
System.out.println("Hello, What is your name?");
Scanner scanner = new Scanner(System.in);
String yourName = scanner.nextLine();
System.out.println("Is your name: "+yourName + "?");
Scanner scanner1 = new Scanner(System.in);
String isCorrect = scanner1.nextLine();
if (isCorrect == "Yes")
{
System.out.println("Thank you for your confirmation!");
}
else
{
System.out.println("Retry please.");
}
}
Any ideas why guys? I'm really new to java btw, so I may be overlooking basic coding errors.
Use "Yes".equals(isCorrect);, == compares object references, not content. Two different Strings can have the same content.
Alternatively you can use String.intern() to obtain unique references from the pool of strings; those can be safely compared using the == operator:
"Yes" == isCorrect.intern();
While both methods work, I would advice you to go with the first one. Use equals to compare objects and == to compare primitives.
Check out the Working example.
Use equals() method instead, because == compare object reference the bit it contain to see if two object are refering to the same object. But equals() method compare the value instead. so in this case you should do: "Yes".equals(isCorrect)
If you want to check if two object are refering to the same object for example:
Object1 x = new Object1();
Object2 y = x;
if(x == y) {
//This will return true because 'y' is refering to object 'x' so both has the bit to access the object on memory.
}
But if you want to check by value for example:
String hola1 = "hola";
String hola2 = "hola";
if(hola1.equals(hola2)){
//Return true because both has the same value.
}
Use equals method to Compare strings.== will compare the references not the content.Please find the corrected program.
public class NiallScanner {
public static void main(String[] args) {
System.out.println("Hello, What is your name?");
Scanner scanner = new Scanner(System.in);
String yourName = scanner.nextLine();
System.out.println("Is your name: "+yourName + "?");
Scanner scanner1 = new Scanner(System.in);
String isCorrect = scanner1.nextLine();
if (isCorrect.equals("Yes"))
{
System.out.println("Thank you for your confirmation!");
}
else
{
System.out.println("Retry please.");
}
}
}
Related
My exercise is to create a String variable called "Hallo". I should check, if the String is called "Hallo" with a scanner. If its true, my code should answer with "Hallo". If not, the code should answer with "Tschüss".
Here is the code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
String hallo = "Hallo.";
Scanner input = new Scanner(System.in);
{
System.out.println(input);
input.nextLine();
if (hallo.equalsIgnoreCase(hallo)) {
System.out.println(hallo);
} else {
System.out.println("Tschüss.");
}
}
}
}
input.nextLine(); returns a String. You need to store the result into a variable like String userResponse = input.nextLine(); then in your condition do if(userResponse.equalsIgnoreCase(hello)). Because in your code you test if your variable hello is equals to your variable hello. It can only be true. You need to store the response of the user and then test if it's equal to your variable hello
I am very new in programming into Java.
My question is that I have a code (see below) and I want to compare them with if statement. An errors occur at line 9 (string test) and 11(if(test.equals). I completely do not have idea.
I have made a code with int and it works perfect, but that.
package bucky;
import java.util.Scanner;
class apples {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
String test = sc.nextLine();
if (test.equals("YES")) {
System.out.println("YES");
} else {
System.out.println("TIS IS ELSE");
}
}
}
You are almost there... define YES as string and that it
String test = sc.nextLine();
String YES = "yes";
if (test.equals(YES)) {
or even better use equalsIgnoreCase() so you can get rid off the case sensitive input
if (test.equalsIgnorecase(YES))
This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 7 years ago.
import java.util.Scanner;
class Pal {
public static boolean Palindrome(StringBuffer str) {
StringBuffer str1 = str.reverse();
System.out.println(str1);
if (str == str1) {
return true;
} else {
return false;
}
}
public static void main(String args[]) {
System.out.println("Enter a string");
StringBuffer str = new StringBuffer();
Scanner input = new Scanner(System.in);
str.append(input.nextLine());
boolean result = Palindrome(str);
System.out.println(result);
}
}
How sholud I improve my code such that values come out to be perfectly correct?
if (str == str1)
{
return true;
}
else
{
return false;
}
is the same as
return str == str1;
However, this still "won't work" correctly because
Code should equals() for comparing objects (including Strings and StringBuffers) and
StringBuffer does not have a useful equals.
A correction, taking both of these into account, would be:
return str.toString().equals(str2.toString());
In this case we first get the current String content of both StringBuffer objects and then compare it with String.equals(String), which works as expected.
An alternative would be to bypass the StringBuffers in this case and directly use Strings; this would allow skipping the toString calls.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
When the user inputs pBreak, it should break the while loop. However, this isn't working and I'm confused on why. Could somebody please help me?
package main;
import java.io.*;
import java.util.*;
public class TextFiles {
public static void main(String[] args) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
Scanner input = new Scanner(System.in);
while (true) {
String line = input.next();
if (line == "pBreak") {
break;
}
out.write(line);
out.newLine();
}
out.close();
} catch (IOException e) {
System.out.println("Error!");
}
}
}
Use equals instead of ==. Consider, null-safe equals
if ("pBreak".equals(line)) {
Change:
if (line == "pBreak") {
to
if (line.equals("pBreak")) {
== compares object references, .equals(String) compares String values.
This code will also work:
if (line.equals("pBreak")) {
break;
}
== operator will compare the references of the two operands.
As line variable is a different string object's reference ,it will not match to string literal constant reference pBreak while comparing.
if (line .equals("pBreak")) {
break;
}
So equals() method has to be used to compare the String.enter code here
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
I am using jcreator to practice java language. I came up with a conditional statement in which if the user input is = "test" it will print an "okay!" message. This is my code:
class conditional {
public static void main (String[] args) {
Scanner user_input = new Scanner(System.in);
String username;
System.out.print("username: ");
username = user_input.next();
if (username == "test") {
System.out.println("okay");
}
else {
System.out.println("not okay");
}
}
The above code does not show any error, it does not display the "okay" && "not okay" message either. I am not sure what's wrong with my logic.
Strings should be compared using .equals rather than ==. This is the case for all non-primitive comparisons. For example, you would compare two int fields with ==, but because Strings are not primitive, .equals is the correct choice.
if (username.equals("test")) {
You should use String.equals here.
if (username.equals("test")) {
Otherwise, you're comparing the identities of the objects rather than their semantics. In fact, you have two separate Strings here, which satisfy semantic equality.
as #veer said,
you can use equalsIgnoreCase / equals if (username.equals("test")) { ... }
Or
You can use compareToIgnoreCase / compareTo
if (username.compareTo("test")==0) { ... }
Or If you want to use == do username.intern(); Then you can use ==.
Note: Not a recommended approch just for FYI.
To compare string you need to use .equals() method and also if you need ignore the case of the letters in the String you can use .equalsIgnoreCase()
if (username.equals("test")){
}
else{
}
It will work if you do it like this:
import java.util.Scanner;
class Conditional {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String username;
System.out.print("username: ");
username = user_input.next();
if (username.equals("test")) {
System.out.println("okay");
} else {
System.out.println("not okay");
}
user_input.close();
}
}
A few remarks:
Class names should start with an upper case.
Use equals to compare Strings.
You state that no result is printed at all. You will have to click in the console to type your answer and end the input with Enter.