Equals Signature / Constructors And Arguments

Jul 14, 2014

In Java code, write class called Student with the following features:

• a private instance variable int studentNumber that is initialized to zero.
• a private instance variable String firstName;
• a private instance variable String lastName;
• a constructor which takes an integer argument and two String arguments to initializes the three respective data items.
• a public method with signature equals(Student s) . . .

So far this is my code :

public class student {
private int studentnumber = 0;
public student () {
firstname= "forename":
lastname="surname":
public student (integer studentnumber, string firstname, string lastname) {
this.firstname= firstname
this.lastname= lastname:

My question is how do i add the integer in the argument do i have to use int =? and how would i go about doing the public signature equals...

View Replies


ADVERTISEMENT

Overriding Equals Method - Cannot Invoke Equals On Primitive Type (double)

Jan 7, 2014

I am trying to override the equals method for my class TeamMember I have two fields:

private Details details;
private double salary;

Code for override I get an error on salary saying cannot invoke equals (double) on the primitive type (double)

Is their something I am missing/coding wrong?

Java Code:

public boolean equals(Object obj) {
//test exceptional cases
//avoid potential NullPointerException/ClassCastException
if ((obj == null) || (this.getClass() != obj.getClass()))
return false;
TeamMember other = (TeamMember) obj; //cast to a TeamMember object
// compare fields details and salary
return this.details.equals(other.details)
&& this.salary.equals(other.salary);
} mh_sh_highlight_all('java');

View Replies View Related

Method Is Declared To Take Three Arguments - Only Two Arguments Pass On Program Call

Jun 9, 2014

A method is declared to take three arguments. A program calls this method and passes only two arguments.Will it take the third argument as

1 null
2 void
3 zero
4 Compilation error

View Replies View Related

How To Apply Electronic Signature To Predefined XML

Oct 4, 2014

I must apply a electronic signature to a predefined XML.
 
File looks like this:

<xml....
<invoice serialCode="NT" serialNumber="123" issueDate="2014-10-01" startDate="2014-09-01" endDate="2014-09-30" orgUnitCode="CAS-NT" providerCode="15107618" providerCategory="PARA" contractNumber="8207" contractType="PAR" contractDate="2014-06-27" totalAmmount="34.81"
 
And at the end there is a sinature that looks like this:
‚ R0‚ N0‚ 6          $P Gæ&"ùO]ó]0
  *†H†÷
0h1%0#  U    DigiSign Qualified Public CA1 0   U    DigiSign Public CA1 0   U
  DigiSign S.A1 0   U    RO0 
140722065817Z

[Code] ....

How can I do this in java?

View Replies View Related

Equals Method - Take Object Reference And Return True If Given Object Equals This Object

Mar 28, 2014

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?

View Replies View Related

Signature Of ReplaceAll Function In Collections Class

Jul 14, 2014

I am confused with the following function signature in the class java.util.Collections.

static <T> boolean replaceAll(List<T> l, T oldValue, T newValue);

I got the other parts but i could not figure out at all what is the meaning of <T> in the beginning.

View Replies View Related

Do While Loop - Using Equals?

Sep 30, 2014

having a hard time with my do while loop. for some reason in my else if structure it will break when i using .equals in the do while loop. But if i try doing tmp == "D" || tmp == "d" it will keep looping how can i go about using alternative for .equals?

Here is my code:

do {
Object object = new Object();
System.out.println("For a deposit Enter: D
Withdrawal Enter: W
"
+ "or 'Quit' to exit.");
String tmp = input.next();
if (tmp.equals("D"))

[Code] ....

View Replies View Related

HashCode And Equals Implementation

May 15, 2014

Its that very old question regarding hashcode and equals implementation which i am not getting .

import java.util.*;

public class MyElement {
public static void main(String a[]){

HashSet<Price> lhm = new HashSet<Price>();
lhm.add(new Price("Banana", 20));
lhm.add(new Price("Apple", 40));

[Code] .....

In the above program even if i comment out the Hashcode method , i believe it is still taking the memory address values from the native hashcode method of Object class. but the equals override implentation says that i have two insertions which are same . So as per my logic it should not allow the duplicate element to enter.but its not so ...the duplicate element is well inserted without hashcode .

View Replies View Related

Equals Comparison Does Not Work

Jan 12, 2015

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);}

Attached image(s)

View Replies View Related

What Is Overloading Constructors

Apr 6, 2014

Can you give me a simple description of what overloading a constructer is?

View Replies View Related

Using Constructors In Interfaces?

Sep 1, 2014

Can i use constructors in an interface?

interface AI {
public abstract AI();
public abstract void hello();
}

Output:

I got the error as the method AI() should have return type.

View Replies View Related

Getting Error On Equals Method For Objects

Mar 26, 2014

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

if(length.equals(object.length) && width.equals(object.width))

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..

View Replies View Related

Average Of Numbers With Sentinel Value Equals To 0

Mar 27, 2014

(Count positive and negative numbers and compute the average of numbers). Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number.

I moved the different boolean statements around, but I'm not getting the sentinel value to end the run. It continues to let me add integers endlessly. The code I wrote is below:

package exerciseFourOne;
import java.util.Scanner;
public class AverageOfIntergers {
public static void main(String[] args) {
// TODO Auto-generated method stub
int positive = 0; // number of positive integers
int negative = 0; // number of negative integers
int sum = 0; // value of sum of integers

[Code] .....

View Replies View Related

Roman To Arabic Converter Says Everything Equals 1

Mar 25, 2015

Im working on a roman numeral to arabic converter and all I had to do was fill out the conversion method romanToDecimal. But for some reason no matter what number I enter It always says my number is equal to one.

//Quiz 1 EC
import java.util.*;
class Roman {
private String romanNum;
private int decimalNum;
public Roman(){
romanNum = "I";
decimalNum = 1;

[code]....

View Replies View Related

Clarity On Overriding Equals Method

Oct 2, 2014

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?
}

View Replies View Related

While Loop - How Result Being Replace If It Only Equals To 1

Jul 6, 2014

I was reading a book and came across this while loop.

public class Powers {
public static void main (String [] args){
int e;
int result;
for(int i = 0; i < 10; i++){

[Code] .....

This loop presents the following (I'm sure it's not necessary):

2 to the 0 power is 1
2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
2 to the 4 power is 16
2 to the 5 power is 32
2 to the 6 power is 64
2 to the 7 power is 128
2 to the 8 power is 256
2 to the 9 power is 512

I am just having a difficult time understand and grasping this concept. My main issue is result *=2; this is making it very difficult to understand. How is result being replace if it only equals to 1.

View Replies View Related

Two Strings - Equals Comparison Fails

Jan 12, 2015

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);}

View Replies View Related

Two Classes With Identical Constructors?

Jun 3, 2014

Is it possible to combine two classes that I have defined to contain some of the same elements so that NetBeans stops giving me errors? I don't want to get rid of any necessary code, and if both classes are necessary, should I just rename one of them? One class is an ArrayList that I am using to write the information for employees entered to a text file "employee.txt." I also want users to be able to call on this information via employeeID in order to display employee information. The code is the following:

public ArrayList<Employee> getEmployees() {
// if the employees file has already been read, don't read it again
if (employees != null)
return employees;
employees = new ArrayList<>();
if (Files.exists(employeesPath)) // prevent the FileNotFoundException {

[code]....

The other class is a getEmployee class that I previously defined before attempting to read the information from the text file and display it in the console. It is as follows:

private void getEmployees() {
try {
// if the file doesn't exists, create it
if (!Files.exists(employeesPath))
Files.createFile(employeesPath);
BufferedReader in =
new BufferedReader(
new FileReader(employeesFile));

[code]....

View Replies View Related

Constructors In Class Hierarchy?

Feb 9, 2014

I remember reading that a super() call to parent no-argument constructor is automatically inserted by compiler. So, if i have a chained hierarchy of classes (starting at top, with Object), will there be a chain of super() calls, going from bottom to top in the chain ? Will a super() call be inserted in child, if i provide a no-argument constructor for this class ?

View Replies View Related

Can Call One Constructor From Two Different Constructors?

Nov 19, 2014

I am getting error in second constructor that I have created, it gives an error: cannot find symbol variable

package Objects;

import javax.swing.JOptionPane;
public class Constructor {
public static void main(String[] args) {
Piggybank1 pg1 = new Piggybank1("Abhinav", 500);
pg1.deposit(200);
pg1.withdraw(10);

[Code] ....

View Replies View Related

Passing Objects To Constructors?

Mar 20, 2014

We are learning about how to pass objects into constructors. In our class, we made this following code:

public class InventoryItem {
//fields
private String description;
private int units;
//Add New constructor
public InventoryItem(InventoryItem some_object) {
description=some_object.description;

[Code] .....

As you can see the object of the same class is passed as the argument. Inside the constructor, our teacher did

some_object.description

This constructor, from my understanding, copies the description field and unit field to an object to the new object of class. Meanwhile, here is the demo class.

public static void main(String[] args)
{
//Create object
InventoryItem item1;
item1=new InventoryItem("hammer",20);
 System.out.println("Item 1: ");

[Code] .....

Over here, my teacher uses :

.getDescription

My problem is that in the constructor of the first class I showed, why didn't he use

.getDescription

method instead of this

.description

May I know what is difference between these two. If I use .getdescription that would return the value of a field from that object too.

View Replies View Related

Repeating Constructors With Same And Different Parameters

May 26, 2014

So while experimenting with constructors, repeating constructors with the same parameters, and with different parameters. I got an output -explaining how I got it.

I made 2 classes. a "support class" (has all the info) and an "execute class" (executes info).

Support:

package inschool;
public class Constructors {
String video;
public Constructors() {
video = "frozen";

[Code] ....

Execute:

package inschool;
//this is part of Constructors class
public class App{
public static void main(String[] args){

[Code] ....

The Output:

the video name is frozen
Second constructor running
Constructor running!
the video name is frozen

Output Explanation:

constructor call number 1 and 3 are the same (essentially) and both refer to the same constructor.

My Question: if both call #1 and #3 refer to the same constructor, why is the output for #1 "the video name is frozen"

while the output for #3 used both methods in the accessed constructor-with the resulting output as
"Constructor running!"
and
"the video name is frozen"

I double checked the output-and this time made sure to scroll up ... its the same result

View Replies View Related

Copying Objects Through Constructors?

Apr 4, 2014

I have a class named Cash shown below

public class Cash
{
//Quanity Field and RetailItem Object field
private int total_units;
private Retail myRetail;
 
//Create first constructors
public Cash()
{
this(0,null);
 
[Code] ....

I'm seriously need to understand the concept of making shallow copies and deep copies. My book has shown me that its better to perform deep copies and I have followed that method. if you guys look in my constructor of the cash class

//Create a a constructor
public Cash(int total_units,Retail myRetail)
{
this.total_units=total_units;
this.myRetail=new Retail(myRetail);

Apparently I have field in Cash Class named

Retail myRetail

When I pass in an argument from my demo, I'm making a copy of that object from the demo class. In my retail class, I have the following copy constructor .

//Make a copy constructor
public Retail(Retail Object1)
{
Item_Name=Object1.Item_Name;
Item_Number=Object1.Item_Number;
// if I use this then my program would work//this.cost=Object1.cost;
 
//if I use this part of code below, my program won't work at all and I would get an error saying Exception in thread "main" java.lang.NullPointerException
this.cost.Item_Cost=Object1.cost.Item_Cost;
this.cost.Wholesale_Cost=Object1.cost.Wholesale_Cost;
}

My question is why can't I perform a deep copy there. I know if I do

this.myRetail=myRetail

in my cash constructor it would work, but then the book says its not a good method;

View Replies View Related

Overriding Equals Method From Object Class

May 5, 2014

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.

package javaapplication5;
import java.text.NumberFormat;
import java.util.Scanner;
import java.lang.Object;
public class Product {
private String product;
private String description;
private double price;

[Code] ....

And here is the stack trace

Exception in thread "main" java.lang.NullPointerException
at javaapplication5.Product.equals(Product.java:42)
at javaapplication5.Product.main(Product.java:24)
Java Result: 1

View Replies View Related

Netbeans - Unable To Debug Equals Method

Mar 11, 2015

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).

View Replies View Related

Why Boolean Equals (Object) And HashCode Not Working

Jul 17, 2014

Here is my code the whole program is working correctly but the Boolean equals and the has code and it is a requirement for the assignment. Why it is not working.

I know there are issues with the code I am new with java and was struggling so I have to clean my code up before I submit the assignment but for right now I have the out put the way I want it except the Boolean and hash code methods always output that the rectangles aren't equal even when I know they are and it outputs the not equal statement twice??

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Scanner;

[Code] ....

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved