If statement String trouble [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm trying to create a program which takes user input of two words and determines whether or not these words are the same.
import java.util.Scanner;
public class L7E3 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System. in );
String word1, word2;
System.out.println("Please enter a word: ");
word1 = keyboard.nextLine();
System.out.println("Please enter a word: ");
word2 = keyboard.nextLine();
if (word1 == word2) {
System.out.println("The words are " + word1 + " and " + word2 + ". These words are the same.");
} else {
System.out.println("The words are " + word1 + " and " + word2 + ". These words are not the same.");
}
}
}
I figured that word1==word2 would have worked to determine whether the two strings were equal, I'm using JGrasp and it goes directly to my else option regardless of input. Am I doing something wrong with strings?

if(word1.equals(word2))
== doesn't do what you think it does. == essentially compares the memory locations of the two String variables and returns true only if they're located at the same memory location. The String.equals method compares the contents of the strings and returns true if they hold the same characters.

Short answer: use String#equals(Object) instead:
word1.equals(word2)
For a super detailed explanation to the reasoning why: check out this.

For Strings you need to use the .equals() function rather than the == equality operator.
if(word1.equals(word2))
If you wanted to test if two words are the same, while ignoring case ("This" is the same as "this) then you need to do something like this:
if (word1.toLowerCase().equals(word2.toLowerCase()))
Also in your specific example you might want to remove unnecesary whitespace from before and after the word (" word1 " should becomes "word1"). You can do this using the trim() function:
word1 = word.trim();

Related

How do I write a Java program that reads two words representing passwords from the keyboard and outputs the number of characters in the smaller one?

I am new to learning Java and I am currently writing a short program to take the input of two words from the keyboard and output the length of the smaller word.
I am unsure of how to do this, since I will not know what words the users will be typing into the keyboard ahead of time. So far, I have prompted the user to write two words and storing the two Strings in two separate variables. I have also created two other variables to store the length of both words but I am stuck on how to output the smaller word, if I do not know what either word is.
{
{
Scanner keyboard = new Scanner(System.in);
// Password #1:
System.out.print("Write a word: ");
String passwordOne = keyboard.nextLine();
int passwordLengthOne = passwordOne.length();
// Password #2:
System.out.print("Write another word: ");
String passwordTwo = keyboard.nextLine();
int passwordLengthTwo = passwordTwo.length();
System.out.print("The number of characters in the shorter password is " +
(I have not completed this variable yet) + ".");
}
}
There are numerous of ways to do it. Here's the most simple one.
String shorter = "";
if(passwordLengthOne > passwordLengthTwo)
shorter = passwordTwo;
else if(passwordLengthOne < passwordLengthTwo)
shorter = passwordOne;
System.out.print("The shorter password is " + shorter + ".");
System.out.print("The number of characters in the shorter password is " + shorter.length() + ".");
Remember to take into account the case where both could have same length.

how can I detect if a recurring word is in an array java

I am trying to create a program where one can input words, which are added to an array, until the same word is entered twice. Then the program breaks.
Something like this:
public static void main(String[] args) {
ArrayList<String> words = new ArrayList<String>();
Scanner reader = new Scanner(System.in);
while (true) {
System.out.println("Type a word: ");
String word = reader.nextLine();
words.add(word);
if (words.contains(word)) {
System.out.println("You typed the word: " + word + " twice.");
break;
}
Every time I enter a single word, the program says "You have typed the word twice." I need to find a way to distinguish the items in the array from one another. Is it possible to use a for block?
Thank you.
You're adding word to words before doing the contains check.
if (words.contains(word)) {
System.out.println("You typed the word: " + word + " twice.");
break;
} else {
words.add(word);
}
will resolve this.
You should also consider making words a Set, which has faster lookups and doesn't allow duplicates.
A slightly improved version would be to use a Set: its add method returns false when the element is already present (and it's more efficient than a list to "find" an element - although in your case, because there is only a small number of words, it won't make any noticeable difference).
Set<String> words = new HashSet<> ();
while (true) {
System.out.println("Type a word: ");
String word = reader.nextLine();
if (!words.add(word)) {
System.out.println("You typed the word: " + word + " twice.");
break;
}
}

Can somebody spot the error in this java program [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
My program should check whether the input is a palindrome or not. The given program compiles and runs successfully. Program prints reverse string correctly but gives wrong output. Please help!
class Palindrome
{
public static void main(String[] args)
{
String str,revStr="";
System.out.println("Enter something to check if it is a palindrome");
Scanner sn = new Scanner(System.in);
str = sn.nextLine();
for(int i=str.length()-1;i>=0;i--)
{
revStr+=Character.toString(str.charAt(i));
}
if(revStr==str)
{
System.out.println("The string "+str+" is a Palindrome");
System.out.println(revStr);
}
else
{
System.out.println("The string "+str+" is not a Palindrome");
System.out.println(revStr);
}
}
}
output:
Enter something to check if it is a palindrome
nitin
The string nitin is not a Palindrome
nitin
Here change this line
if(revStr==str)
To
If ( revStr.equals(str))
The thing is == checks reference equality
Object.equals is the method given in java to define your object equality
String class overrides that and check if two Strings represent same char array
Your answer here:
import java.util.Scanner;
class Palindrome
{
public static void main(String[] args)
{
String str,revStr="";
System.out.println("Enter something to check if it is a palindrome");
Scanner sn = new Scanner(System.in);
str = sn.nextLine();
for(int i=str.length()-1;i>=0;i--)
{
revStr+=Character.toString(str.charAt(i));
System.out.println("revStr" + revStr);
}
if(revStr.equals(str))//Don't use ==
{
System.out.println("The string "+str+" is a Palindrome");
System.out.println(revStr);
}
else
{
System.out.println("The string "+str+" is not a Palindrome");
System.out.println(revStr);
}
}
}
The “==” operator
In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.
Equals() method is defined in Object class in Java and used for checking equality of two object defined by business logic
your if condition should be like this
if(revStr.equals(str)){
System.out.println("The string "+str+" is a Palindrome");
System.out.println(revStr);
}
Because in java == check the address of object not content
for more details check below thread
What is the difference between == vs equals() in Java?

Java: Yes to continue No to exit [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I've been working on a solution of a problem in Java. I have a store and I need to ask the customer if she/he had bought anything. If he/she types "yes" I want the program to continue to the next question and if he/she types "no" I want a message to appears such as "have a nice day!" and then I want the program to stop. How can I manage this?
Thank you!
Here's what I've done so far ~Line 17 to 20~ (but it doesn't work very well):
import java.util.Scanner;
public class Discount {
public static void main(String[] args) {
String cname;
float I_price, drate, discount, dprice;
Scanner in = new Scanner(System.in);
System.out.println("Enter Costumers Name:");
cname = in.next();
System.out.println("Have you bought anything?");
if (cname == "no") {
System.out.println("Have a good day!");
System.exit(0);
}
System.out.println("Enter Price of Item:");
I_price = in.nextFloat();
System.out.println("Enter Discount Rate:");
drate = in.nextFloat();
discount = (I_price * drate / 100);
dprice = (I_price - discount);
System.out.println(
"Costumer Name:" + cname + "\n" + "Discount Rate:" + discount + "\n" + "Discounted Price:" + dprice + "\n");
}
}
replace if(cname=="no"){ with if(cname.equals("no")){
While comparing 2 Strings use String#equals() instead of ==
Compare String with equals() method not ==. you should change it to
if(cname.equals("no")){
== will do a conditional equality test on the values of right and left operand. This should be used only for comparing primitive types like int, float etc. This should not be used since the object reference values will point to the memory address and they will not be same. There is also a concept called String Constant Pool. When you create the String using assignment operator instead of new like
String name ="StackOverFlow";
then, it will pass the equality test using if(name == "StackOverFlow") Since the memory address would be same for equal String values in constant pool. In this case, usage of == works. i.e compile time constants
Generally, use equals() to test the equality of the object. The equals() method of String Class compares the actual values (i.e characters) in the String literal instead of their memory address. So, In Java, Strings should be compared using equals() method only!

while loop not working Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
When I create a variable and wrap the code in a while loop it never repeats. Here's a sample of code I tried it on.
String repeat = "y";
Scanner keyboard = new Scanner(System.in);
while (repeat == "y"){
String word1 = "this";
String word2 = "that";
String word3 = word1 + word2;
System.out.println(word3);
for(int x = 10; x<20; x = x+1){
word3 = word1 + word3;
System.out.println(word3);
}
repeat = keyboard.nextLine();
}
No matter what the input is in the end of the script, it just ends. Any help?
Change the line
while (repeat == "y")
to
while("y".equalsIngnoreCase(repeat))
and
keyboard.nextLine() ;
to
keyboard.next();
Reading How do I compare strings in Java? will be helpful.
When you compare a string using '=='. you are comparing the object reference. You are essentially asking if the two objects are the same, rather than comparing the string contents. Try using the String.compareTo(..) method.
Example:
while (repeat.compareTo("y") == 0) {
The problem probably comes from the facts you compare two objects with = but I guess what you want to do is compare Strings with the String method equals, so it would look like that:
while(repeat.equals("y")){
...
}
Never use == to compare strings.
Try this:-
while ("y".equalsIngnoreCase(repeat) )

Categories