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.
Related
If String.length() cannot be used to compare two String objects and determine which object is larger, then what string method would do such a thing? When I run this code it terminates immediately. Is there a method to compare pairs of strings? I'm using the API for the string class as a reference here: https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
public class ThingsComparer {
public static void main(String[] args) {
String ObjectOne = new String("One");
String ObjectTwo = new String("Two");
if (ObjectOne.length() > ObjectTwo.length())
{
System.out.println("ObjectOne is larger");
}
else if (ObjectOne.length() < ObjectTwo.length())
{
System.out.println("ObjectTwo is larger");
}
else if (ObjectOne.equals(ObjectTwo))
{
System.out.println("ObjectOne and ObjectTwo are equal");
}
}
}
.....
.....
else if (ObjectOne.length() == ObjectTwo.length())
{
System.out.println("ObjectOne and ObjectTwo are equal");
}
Furthermore, according to Thilo, you don't need else if (ObjectOne.length() == ObjectTwo.length()) at all specially after you have tried to look for greater and lesser than conditions. What's the 3rd condition? It's equal.
#Peanutcalota
The above code is working fine. The reason that you are not getting any output is that the 2 objects ObjectOne and ObjectTwo are having different strings and have equal lengths.
So the first and second condition will not work as both are having the same length.
The last condition will not work because both strings are different.
ObjectOne.equals(ObjectTwo) will only work if they are having same string.
And I have tried running this program, it is executing fine.
Give it a try.
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.");
}
}
}
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:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am implementing a String matching algorithm for a username database. My method takes an existing Username database and a new username that the person wants and it checks to see if the username is taken. if it is taken the method is supposed to return the username with a number that isn't taken in the database.
Example:
"Justin","Justin1", "Justin2", "Justin3"
Enter "Justin"
return: "Justin4"
since Justin and Justin with the numbers 1 thru 3 are already taken.
In my code sample below, newMember returns Justin1 even though it already exists--where is the mistake?
public class UserName {
static int j = 0;
static String newMember(String[] existingNames, String newName){
boolean match = false;
for(int i = 0; i < existingNames.length; i++){
if(existingNames[i] == (newName)){
match = true;
}
}
if(match){
j++;
return newMember(existingNames, newName + j);
}
else{
return newName;
}
}
public static void main(String[] args){
String[] userNames = new String[9];
userNames[0] = "Justin1";
userNames[1] = "Justin2";
userNames[2] = "Justin3";
userNames[3] = "Justin";
System.out.println(newMember(userNames, "Justin"));
// I don't understand why it returns Justin1 when the name is already taken
// in the array.
}
}
This line:
if(existingNames[i] == (newName)){
Should become
if(existingNames[i].equals(newName)){
In general, always use equals instead of == for Strings in Java.
I would change your approach to this. I think it would be better to use a Map<String, Integer>. For example, the fact that "Justin" - "Justin3" are taken usernames can be represented by the map:
{"Justin": 3}
To check if a username is taken, check if it's a key in the map. To get the "next" username for a specific taken username, get the value corresponding to the name from the map and add 1. Something like this:
static String newMember(Map<String, Integer> existingNames, String newName) {
if (existingNames.containsKey(newName)) {
int newNum = existingNames.get(newName) + 1;
existingNames.put(newName, newNum);
return newName + newNum;
}
existingNames.put(newName, 0);
return newName;
}
Oh, and use .equals() instead of == when comparing strings :)
*Never ever compare equality of Strings with ==. use equals() *
Use .equals to compare strings in Java, not ==.
== will determine if the string references are the same which they almost certainly will not be. (There are rare cases when they may be due to the intern pool.)
.equals will determine if the content of the strings are the same.
When comparing strings in Java, you should generally use the equals() methods to do so.
Using == with strings compares the references, not the underlying objects. Use str.equals().
I guess you have a function somewhere in your application answering if a username already exists, I call this usernameExists(String username) returning true or false.
String getOkUsername (String wantedUsername) {
//if it's free, return it!
if(!usernameExists(wantedUsername)) {
return wantedUsername;
};
//OK, already taken, check for next available username
int i=1;
while(usernameExists(wantedUsername+Integer.toString(i))) {
i++;}
return wantedUsername + Integer.toString(i);
}
You're not comparing the strings correctly, and you're adding the integer 1 to a string. Comparing strings is done with .equals. In order to concatenate the integer onto the end of the string:
static Integer j=0;
return newMember(existingNames, newName + j.toString());
It is much easier to do it in SQL:
select ... where ... LIKE username%
No matter what I do this piece of code will never evaluate to true when the user inputs 1 at the console... I'm confused as to why it is evaluating to false.. any help is much appreciated.
import java.io.*;
public class Default
{
public static void main(String [] args)
{
System.out.println("Welcome to the CS conversation game\n");
System.out.println("Choose your game\n1)Hex to Decimal\n2)Binary to Decimal");
Hex2Decimal PlayHex = new Hex2Decimal();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String GameSelection = null;
try
{
GameSelection = br.readLine();
}
catch (IOException ex)
{
ex.printStackTrace();
}
if(GameSelection == "1")
{
PlayHex.Play();
}
}
}
Should be "1".equals(GameSelection), == compares references of objects, while equals compares content.
Also, the Java naming convention is to start variable names in lower case. (e.g. gameSelection, playHex etc.)
You need:
if(GameSelection.equals("1"))
instead of:
if(GameSelection == "1")
== is used to check if the 2 references refer to the same object in the memory, while equals() checks whether the 2 references refer to the same object in the memory OR to 2 different objects but with the same values (the 2 strings are equivalent).
Java doesn't have operator overloading.
You will have to use .equals(...). Otherwise, you are comparing the reference address.
if(GameSelection.equals("1"))
{
PlayHex.Play();
}