Currently I am writing a program, for learning purposes, that is more or less a user defined dictionary. You are given a word, and then you input the corresponding word in English, and then it should tell you whether or not it is true or false, depending on what was put in as a answer previously.
Now, the trouble I am having is that I am currently unable to figure out how to check if the user input is correct, as I do not know how to compare the 2 values within the arraylist.
Currently I have this:
public void add(String question, String answer) throws FileNotFoundException, IOException
{
wordlist.add(new WordPair(question, answer));
}
to add new elements to the array, which is just 2 strings, and then I am stuck on this:
public boolean checkGuess(String question, String quess)
{
}
which is where I want to compare the 2 strings. Any help is much appreciated.
Override the equals method in your Word class and simply do :
public boolean checkGuess(String question, String quess)
{
return wordlist.contains(new WordPair(question, quess));
}
I assumed that each question is unique.
Note that a Map would be a better implementation.
To compare two strings you would use the equals() method:
String a = "a";
String b = "a";
if(a.equals(b)){
//TRUE
}
To cycle through the array list you can use a for each loop
for(WordPair pair : wordlist){
if(guess.equals(pair.getAnswer())){
// Equals the word
}
}
alternatively equalsIgnoreCase() can be used if the capitalisation of the word is not considered important.
String a = "A";
String b = "a";
if(a.equalsIgnoreCase(b)){
// TRUE
}
Related
In Java, how can I use equalsIgnoreCase to apply to multiple strings?
I am new to Java and I want the user to enter a or c or e in either lowercase or uppercase.
Just connect your possibilities with the logical OR operator (||):
if ("a".equalsIgnoreCase(string)
|| "c".equalsIgnoreCase(string)
|| "e".equalsIgnoreCase(string)) {
// Valid string
} else {
// Invalid string
}
String equalsIgnoreCase()
This method compares the two given strings on the basis of content of the string irrespective of case of the string. It is like equals() method but doesn't check case. If any character is not matched, it returns false otherwise it returns true.
As the example
public class EqualsIgnoreCaseExample{
public static void main(String args[]){
String s1="java";
String s2="java";
String s3="JAVA";
String s4="python";
System.out.println(s1.equalsIgnoreCase(s2));//true because content and case both are same
System.out.println(s1.equalsIgnoreCase(s3));//true because case is ignored
System.out.println(s1.equalsIgnoreCase(s4));//false because content is not same
}}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I don't know what's going on with it. Code below. I'm not trying to get anyone to code the whole thing for me, just don't know what's wrong and would like a little help
private void javabutton1(java.awt.event.ActionEvent evt) {
String testa= new String (jPasswordField2.getPassword());
String testb= new String (jPasswordField3.getPassword());
if (testa.toString() == testb.toString()){
JOptionPane.showMessageDialog(this, "Success");
}
}
When I replace testa.toString() == testb.toString()) with "A" == "A".
The messagebox "Success" is achieved but this entry comparison won't work
Also: The text entered in both jPasswordField2 and jPasswordField3 are the same.
You should try:
testa.equals(testb)
And there is no point of doing this:
String testa = getSomething();
String temp = testa.toString();
// becasue
testa.equals(temp) // always true
If you would have something like:
String a = getSomething();
String b = a;
a == b // now this is true, because they have the same reference/pointer
Use .equals() when comparing strings.
Try with String.equals()
Consider two different reference variables str1 and str2
str1 = new String("abc");
str2 = new String("abc");
if you use the equals()
System.out.println((str1.equals(str2))?"TRUE":"FALSE");
You will get the output as TRUE
if you use ==
System.out.println((str1==str2)?"TRUE":"FALSE");
Now you will get the FALSE as output because both str1 and str2 are pointing to two different objects even though both of them share the same string content. It is because of new String() everytime a new object is created.
Fix your issue by using String.equals(string) like this
String testa= new String (jPasswordField2.getPassword());
String testb= new String (jPasswordField3.getPassword());
if (testa.equals(testb)){
JOptionPane.showMessageDialog(this, "Success");
}
Basically, you should never use == to compare Strings, instead use equals(), so for you:
testa.equals(testb)
The difference is that == is used to compare references, it is saying: "Do these two String references point to the same String object in memory?"...this is unpredictable due to how Java stores Strings, which basically accounts for why "A" == "A" returns true...not something to go into here.
The equals() method is more what you would expect, in the Java Class String, this method basically checks whether or not each character in the String is the same, and returns true if they do.
If it's an object, you should use equals() to compare, if its a primitive data type, such as an int (or you are checking if a reference is null) then use ==.
While I agree with Takendarkk that answer duplicate questions promotes their repeated posting, I think there is at least one issue that should be noted which has not been mentioned. StephenTG asked a poignant question in the comments: "Why do you need to convert your Strings to Strings?"
Given the name of your variables, if you are indeed using the swing JPasswordField, then the getPassword() method returns a char[] array. You don't need to convert this to a string, you can compare them using java.utils.Arrays#equals(char[]. char[]) to get the result you desire. Your code might look like this:
private void javabutton1(java.awt.event.ActionEvent evt) {
char[] testa = jPasswordField2.getPassword();
char[] testb = jPasswordField3.getPassword();
if (Arrays.equals(testa, testb)){
JOptionPane.showMessageDialog(this, "Success");
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
thank you for taking the time to read this. Sorry if my question is dumb, I tried searching but couldn't quite figure out why I'm having this problem. I was trying to test some code for another application, but I'm having issues. Perhaps I just don't understand arrays properly.
I have a method named halfStepUp in a class named Transpose that, for testing purposes, should return "c#" if given "c" and "d#" if given "d". This is the code:
public class Transpose{
public static String halfStepUp(String note){
String n = null;
if (note == "c") n = "c#";
if (note == "d") n = "d"#;
return n;
}
}
I have the following code in my main method:
String [] scale = new String[2];
scale[0] = "c";
scale[1] = "d";
System.out.println(Transpose.halfStepUp(scale[0]));
This prints "null." What am I doing wrong?
I know the method works because if I use
System.out.println(Transpose.halfStepUp("c"));
It works fine. The solution is probably embarrassingly easy but I couldn't find a good way to word it when searching for help.
Thanks again for reading, and any answers are greatly appreciated!
To add a little more info to the answers you already got:
Java has two types of storage. One is the stack, which includes variable names and their values. One is the heap, that is just a huge collections of free-floating objects.
Now, if you're working with primitive types (like int, boolean or char), assigning a variable like
int myInt = 1;
pushes that variable on thje stack - the name is myInt, the value is 1.
If you, however, have an object (like strings are), assigning a variable does a little bit more.
String myString = "Hey!";
now creates an object (instance of String) somewhere on the heap. It has no name there, only some address in the memory where it can be found.
In addition to that, it pushes a variable on the stack. The name is myString - and the value is the address of the object on the heap.
So why is this relevant to comparing variables? Because == compares values of variables. ON THE STACK, that is. SO if you compare primitive types, everything works as expected. But if you're comparing Objects, == still only compares the values of the variables - which is, in that case, the addresses to the objects. If the addresses are the same, it returns true. That does mean, both variables point to the same object. If the addresses are different, == returns false., Without ever looking at the heap, where the objects really are.
An example:
String a = new String("Hey!");
String b = a;
if (a == b) System.out.println("true");
else System.out.println("false");
will echo "true" - because both variables contain the same object.
String a = new String("Hey!");
String b = new String("Hey!");
if (a == b) System.out.println("true");
else System.out.println("false");
will echo "false" - because you have two objects on the heap now, and a points to the one, while b points to the other. So while the contents of both objects may be the same, the contents of a and b on the stack are different.
Therefore, to compare any object, always use .equals() if you want to compare contents, not instance-equality.
[Addendum]:
With strings, this is even more complicated. As you already found out already,
String a = "Hey!"; // mention the difference to the example above:
String b = "Hey!"; // I did NOT use the `String()` cosntructor here!
if (a == b) System.out.println("true");
else System.out.println("false");
will actually give you "true". Now why is THAT? One might think that we still create two objects. But actually, we are not.
String is immutable. That means, once a String has been created, it cannot be modified. Ever. Don'T believe that? Take a look!
String myString = "test"; // we create one instance of String here
myString += " and more"; // we create another instance of String (" and more")
// and append that. Did we modify the instance stored in
// myString now? NO! We created a third instance that
// contains "test and more".
Therefore, there is no need to create additional instances of String with the same content - which increases performance, as Strings are widely used, in masses, so we want to have as few of them as possible.
To archive that, the JVM maintains a list of String Objects we already created. And every time we write down a String literal (that is something like "Hey!"), it looks in that lists and checks if we already created an instance that has that value. If so, it returns a pointer to that exact same instance instead of creating a new one.
And THIS is, why "Hey!" == "Hey!" will return true.
You should use the .equals() method when comparing strings, not ==. The == operator compares the references to see if they are pointing to the same underlying object. The .equals() method, compares the underlying objects to each other to see if they are semantically equivalent.
Try this instead: (edited from comments)
public class Transpose{
public static String halfStepUp(String note){
String n = null;
if ("c".equals(note)) n = "c#"; //using .equals as a string comparison
if ("d".equals(note)) n = "d#"; //not "d"#
return n;
}
}
The glitch is in this line:
if (note == "c") n = "c#";
This compares strings by address, not by value. Try using "c".equals(note) instead.
class Transpose{
public static String halfStepUp(String note){
String n = null;
if (note == "c") n = "c#";
if (note == "d") n = "d#";
return n;
}
}
public class TransposeTest {
public static void main(String... args) {
String [] scale = new String[2];
scale[0] = "c";
scale[1] = "d";
System.out.println(Transpose.halfStepUp(scale[0]));
}
}
working code
I have this problem where there are several parts in my code where I check if these certain conditions are met so that I can understand if what I am checking is of one type or the other. this ends up becoming large if else trees because I am making lots of checks, the same checks in each method, and there are several different types the thing I am checking can be. This I know can be solved using objects!
Specifically, the things I am checking are 4 string values from a file. based on these string values, the 4 strings together can make one of 3 types. Rather than making these same checks every time I need to get the type the 4 strings make up, I am wondering if I can create a general object given these 4 strings and then determine if that object is an instanceof either specific class 1, 2, or 3. Then I would be able to cast that general object to the specific object.
Say I name the general object that the 4 strings create called Sign. I would take those 4 strings and create a new Sign object:
Sign unkownType = new Sign(string1, string2, string3, string4);
I need to check which specific type of sign this sign is.
EDIT:
for more detail, the Signs I am checking are not symbols like "+" or "-", they are signs with text like you would see on the road. there are 4 lines on each sign and they need to be checked to see if each line evaluates to match a specific type of sign.
The first line of SignType1 will be different of the first line of SignType2, and I want to take those 4 lines (Strings) and pass it onto an object and use that object throughout my code to get the values from it rather than making the same checks in each method.
If you want me to show some code, I can, but it won't make much sense.
What you seem to asking for is a factory pattern
public interface ISign {
public void operation1();
public void operation2();
}
and a Factory class to generate classes based on input
public class SignGenerator {
public static ISign getSignObject(String str1,String str2, String str3, String str4) {
if(str1.equals("blah blah"))
return new FirstType();
if(str1.equals("blah blah2") && str2.equals("lorem ipsum"))
return new SecondType();
return new ThirdType();
}
}
public class FirstType implements ISign {
}
public class SecondType implements ISign {
}
public class ThirdType implements ISign {
}
Implement all Type specific logic in these classes so you can call them without checking with tons of if..else clauses first
From what I gathered from your statement.
Say: create the method that returns a certain object provided the given string is equal to whateva value you specify
//provided the objects to be returned are subtypes of Sign
public Sign getInstance(String first, String second, String third, String fourth)
{
if(first==null || second==null || third==null || fourth===null )
return null;
if(compare1.equals(first))
return new SignType1();
else
if(compare2.equals(second))
return new SignType2();
else
if(compare3.equals(third))
return new SignType3();
else
if(compare4.equals(fourth))
return new SignType4();
}
Above code checks and returns thee appropriet instance corresponding to the string passed
Hope that's what was your concern
I have text file. In that i want to remove duplicate words.My text file contains words like
அந்தப்
சத்தம்
அந்த
இந்தத்
பாப்பா
இந்த
கனவுத்
அந்த
கனவு
I remove duplicate words. But the words which has ending 'ப்' , 'த்' are consider as seperate words and not able to remove as duplicate word. If i remove 'ப்' , 'த்' it remove from some other words like பாப்பா, சத்தம். Please suggest any ideas to solve this problem using java.Thanks in advance.
I think I would use a Set with a custom comperator (such as a TreeSet). That way you can define equals any way you like.
I don't understand the given language (google translate's guess is Tamil), but from your question I read, that there are special rules for 'equality' for words written in that language - like words can be equal even if they're written differently (e.g. with different endings).
So you may want to wrap the strings containing words of that language in special object where you can define a custom 'equals' method, like this:
public class TamilWord {
String writtenWord = null;
public TamilWord(String writtenWord) {
this.writtenWord = writtenWord;
}
public String getWrittenWord() {
return writtenWord;
}
#Overwrite
public boolean equals(Object other) {
// Define your custom rules here, so that two words that
// are written differently may be considered as equal
}
}
Then you can create TamilWord objects for all parsed Strings and drop them into
a Set. So if we have the word abcd and abcD which are different in writing but according to rules considered equal, only one of those will be added to the set.
Use a scanner to scan in each line as a string into a set then write the strings in the set to a file.
First you should explain us how you parse your file, as it seems that your tokenization is not working appropriately. Then, to my mind, the obvious suggestion to a query for unduplication is to use a Set (and even a TreeSet) which should ensure uniqueness of your elements according to given Set contains rules.
My way to solve this:
Read word by word and put it to java.util.Set<TheWord>. Finally, you will have the Set with no duplicates. You also should define TheWord class:
class TheWord {
String word;
public TheWord() {}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public boolean equals(TheWord o) {
// put here your specific way to compare words
// taking into account your language rules and considerations
}
}