Creating Equals Method To Compare Strings In A Class?
Mar 26, 2015
How would I create a equals method to compare strings in a class that I'm creating. I need to create the method in my class, and then call it in a driver. How would I do this?
I am attempting to override the equals method from the Object class which checks if two variables point towards the same object. I want the method to check if if the argument being passed in(an object) has the same data(instance variables) as the object that's calling this method. A NullPointerException is being thrown; Here is the code.
Exception in thread "main" java.lang.NullPointerException at javaapplication5.Product.equals(Product.java:42) at javaapplication5.Product.main(Product.java:24) Java Result: 1
All I am trying to do is to make a section of code execute if two strings are equal. The two strings are userId and "A001062". When I use the debugger in Eclipse, I can see the value of userId as "A001062" but whatever string comparison I try never evaluates to true. I have tried
userId=="A001602" userId.equals("A001602") "A001602.equals(userId) Assigning A001062 to a string called AAA and comparing userId to AAA
My code is as follows. I have also attached a screen shot from the Eclipse Debugger which makes me think the string comparison should succeed. I never see the debugger execute the print line nor do I see the print line on the JBOSS console.
String userId = StringUtils.trim(nextLine[HR_USER_ID]); String AAA="A001062"; if (userId.intern().equals(AAA.intern())) {System.out.print("MKP1: " + userId+"-"+managerId);} if (userId.compareTo("DTS0428")==0) {System.out.print("MKP2: " + userId+"-"+managerId);}
Create an equals method that takes an object reference and returns true if the given object equals this object.
Hint: You'll need 'instanceof' and cast to a (Geocache)
So far I have:
public boolean equals(Object O){ if(O instanceof Geocache){ Geocache j=(Geocache) O; if (this.equals(j)) //I know this is wrong... but I can't figure it out return true; }
else return false; }
I think I have it correct up to the casting but I don't understand what I'm suppose to do with the this.equals(). Also I'm getting an error that I'm not returning a boolean... I get this all the time in other problems. I don't get why since I have to instances of returning booleans in this. "returns true if the given object equals this object" makes no sense to me. I assume the given object, in my case, is 'O'. What is 'this' object referring to?
In the process of creating a new class, I need to move my main method from the class SaveDate to the class DynamicTest. Below I have listed the code of both classes.The objective is to be able to run my program from the DynamicTest Class. I need understanding the process of moving my main method to a different class and creating an Object of a class and calling its method.
public class SaveData { private static final Map<String, Object> myCachedTreeMap = new TreeMap<String, Object>(); public static final List<String> getLines(final String resourceParam, final Charset charset) throws IOException{ System.out.println("Please get: "+resourceParam); if (myCachedTreeMap.containsKey(resourceParam) ) { // Use the cached file, to prevent an additional read.
Its supposed to notify the user if they have a palindrome, but keeps returning true even when I type, "hello".
import java.util.Scanner; public class PalinDrome { public static void main(String[] args) { String line; Scanner input = new Scanner(System.in); System.out.print("Please enter a word ");
Is there a different logic in Java for if statements when it comes to conditions? I mean my attempt to compare a String variable and a String attribute of a class that is on an array of objects was frustrated someway. It will not enter the if block. The two strings are equal. I displayed the values of each strings before the if evaluation and they are equal. The simbol I used was the ==, and I also tried the string.equals(string variable) as well as the compareTo() == 0 option but none of those worked. I wish I knew what it is the way to compare two strings.
I'm attempting a small program as I'm teaching myself the ropes. In it, I need to compare one string (the base) to another which is just the base string that's had it's characters shuffled.
Java Code:
String base = "ABCDEFG" String shuffled = "CDAFBEG" mh_sh_highlight_all('java');
What I need to do is run a loop that shuffles the base string each time, but compares and saves any characters that match in the correct location. For example, if shuffled = "CDAFBEG", then the G would be "locked" in place and the rest of the characters shuffled and looped back to the comparison.
I have all the code I need for shuffling the string, but I'm not sure how I would go about comparing each character and then also locking it in place. I get the basics, I think, of needed to use several variables.
I have to create a class that has two fields. One called length and the other width. I have to make a method that returns the tract area. Similarly, I also have to make a method that indicates whether two objects have the same fields. Here is the code that I have assembled...so far
// create private fields to hold width and length private double width; private double length;
[Code].....
My problem is encountered when writing that equals method
I get an error saying HTML Code: cannot invoke equals(double) on the primitive type double. Meanwhile, I do see, to realize that when I change my fields to capital "Double." The problem disappears; however, in my class I have never dealt with a situation where I have to use capital d in double. In fact, I don't even know what's the difference between Double and double. I do know what double is but not the other one..
For a few days I've been reading about the importance of overriding the equals method. How overriding it actually determines or checks the values stored in the variable. I realize that you can check the values stored in the primitive datatypes with "==", and when you don't override the equals method it acts the same way, right? When used with a reference datatype, "==" or the default equals() method only compares, or sees, if the variable is pointing to the same instance of a class. For some reason, in the examples, what is taking place to actually check the values stored inside the variables.
Here is part of an example (I've added comments for things that are confusing me):
@Override public boolean equals(Object obj) { //So we use Object here instead of the class type // we're overriding this equals method for? Is this so that we can use it to check different types? (overloading?) if (obj == this) { return true;
//Isn't this checking to see if the calling object is the same as the object we're passing to it? Why doesn't this return false? } if (obj == null || obj.getClass() != this.getClass()) { return false; }
//How exactly do we check the values stored in each object though? }
I need to debug the equals method implementation of a class I've made, but I cannot for the life of me get Netbeans' debugger to step into it. I can step into other methods from the class (most of which implement the methods in an interface) that are called in the main method (just like the equals method). I've tried...
-Disabling all the step filters -Clearing the Netbeans cache -Moving the call to the equals method out of the if statement it's in and just calling it as its own statement -placing breakpoints within the equals method as well as on the call to the method -placing a method breakpoint on the overridden equals method in addition to the other locations -Using the shift-F7 version of the step into command
I'm using Netbeans 8.0.1 (I don't know if this is the latest version, but the last time I tried to update everything died and I had to completely remove NB and reinstall it) and JDK 8u05 (I think).
Write a class encapsulating the concept of a course grade, assuming a course grade has the following attributes: a course name and a letter grade. Include a constructor, the accessor and mutator, and methods toString and equals.Write a client class to test all the methods in your class.
how to test and finish the toString and equals method in this code ?
package labmodule7num57; import java.util.*; public class LabModule7Num57 { // Constructors// private String name; private String letterGrade; public LabModule7Num57 (String name,String letterGrade) {
I need to use a counter to keep track of user's input. In this class I am trying to create a combination lock that takes three strings. In the tester class the user inserts three strings and both are compared to see if users input matches correct combination. I have no errors only problem is the setPosition method. My output is always false.
public class CombinationLock { private String first; private String second; private String third; private String firstGuess; private String secondGuess; private String thirdGuess; private boolean open; private int counter;
Design a class named Person and its two subclasses named Student and Employee. Make Faculty and Staff subclasses of Employee. There is also a MyDate class as explained below. A person has a name, address, phone number, and email address. A student has a status (freshman, sophomore, junior, or senior). Define the status as an integer which can have the value 0 (for "Freshman"),
1 (for "Sophomore"), 2 (for "Junior"), and 3 (for "Senior"),
but don't allow the status to be set to any other values. An employee has an office, salary, and dateHired. The dateHired is a MyDate field, which contains the fields: year, month, and day. The MyDate class does not explicitly inherit from any class, and it should have a no-arg constructor that sets the year, month, and day to the current year, month, and day. The MyDate class should also have a three-argument constructor that gets three int arguments for the year, month and day to set the year, month and day.
A faculty member has office hours and a rank. Define the rank as a String (for values like "Professor" or "Instructor"). A staff member has a title, which is also a String. Use data types for the fields as specified, or where one is not specified, use a data type that is appropriate for the particular field. Write a test program called TestEveryone.java that creates a Person, Student, Employee, Faculty, and Staff object, and invoke their toString() method (you don't need to call the objects' toString() method explicitly).
Note: Your MyDate.java class is the object class that your dateHired field is created from in the Employee.java class.
Do not use the Person, Employee or Faculty classes defined on pages 383 and 384 of the book. Create new ones.Here is the code I have so far concerning the employee and MyDate.
public class Employee extends Person { private String office; private double salary; //private MyDate dateHired; //7 argument constructor for employee public Employee(String name, String phoneNumber, String email, String address, String office, double salary /*MyDate dateHired*/) { super(name, phoneNumber, email, address);
I've a parent class with a argument constructor like below(a sample code)
public class Parent { Parent(String name) { System.out.println(name); } public static void main(String[] args) { } }
Also I've child.class which extends Parent.class as shown below,
public class child extends Parent { child(String name) { super(name); } }
Now, I want create/modify the constructor which is in child, by taking "int i" as an input instead of "String name". How can I do that? Run time I want to execute child constructor not a parent constructor.
Condition is: Without making any changes to the Parent class
I have an Abstract Class called GameColorEffect which contains a number of non-static Inner Classes that extend their Parent Class, GameColorEffect. I want to be able to create instances of the Inner Classes, however my IDE, eclipse, prompts me with the error:
No enclosing instance of type GameColorEffect is accessible. Must qualify the allocation with an enclosing instance of type GameColorEffect
And eclipse shows me a possible solution which is to turn the Inner Classes to static, this would allow me to create instances, but not really. This is because using methods from the static Inner Classes that change values in the Inner Classes will do this for every instance of the same Inner Class which is literally like a single instance. However, I want these Inner Classes to be individual with their values and still be able to use them outside as instances. I've found out a possible solution, which I'm not sure works like I want it to:
Java Code : GameColorEffect = new GameColorEffect.ExampleEffect(); mh_sh_highlight_all('java');
However, this is in-compact because sometimes all I need is to use just a method like:
Java Code : new GameColorEffect.ExampleEffect(intensity).applyEffect() mh_sh_highlight_all('java');
And another solution that I already knew prior was that I could make the Inner Classes proper classes not inside of the GameColorEffect class, but this is also in-compact because I will have to have so many classes for the so many effects that I have.
I am wondering if there is something similar to the "Find and Replace" action, that we use in applications like Eclipse and MS Word, that is actually built into the Java API so we can use it in our code, mainly for method names?
For example, right now I have these couple of lines
that does one operation for a side of Rubik's cube. However, all other sides of the cube can use these same exact code with the exception of the 2nd word, ie the position, in each method.
So for example, another side would do something, like, lets say
The reason why I ask this is because this would DRASTICALLY shrink the size my code, rather than have to create separate methods for each operation. Now I know there is a Find and Replace feature for Strings, but I am not sure about method names...
Basically, I'm just trying to let the user enter the name. It crashes whenever the input isn't an int. Also, here's the bit of code I'm using that has to do with that. I don't feel like putting the entire class, so here's that bit of code:
I'm doing an exercise we're you're supposed to sort strings in alphabetical order, without importing anything , not using the Arrays.sort() method.
I think I got the method down partially right, or it is on the right track, but it is completely not being applied to my answer. All it prints out in the console is the actual String array twice, without sorting anything.
public class arrayofstrings { public static void sort(String[] a) { String temp= ""; int min; int i= 0; for (int j=0; j<a.length-1; j++) {
I am having trouble with methods. What I want to do is be able to create 4 types of strings under the same method, but only draw one of them at a time.
So I'm trying to implement a quick sort method for an ArrayList of Strings and right now I'm getting the compiler error message: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space. I don't know what that error means nor how to fix it. I've marked in my code where the error seems to be occurring.
import java.util.ArrayList; public class quickSort { // constructor public quickSort()