Reputation: 61
Im trying to make an if statement so when r1 and num are equal it prints r1 but it just wont print. it asks for the product number and when I enter it nothing prints. Main all the way at the end. please show me what im doing wrong?
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
public class ProductType implements Comparable<ProductType>
{
private String partnum;
private double price;
private int stock;
public ProductType (String partnum, double price , int stock ){
this.partnum = partnum;
this.price = price ;
this.stock = stock ;
}
public ProductType(){
partnum = "" ;
price = 0;
stock = 0;
}
public void setNum(String partnum)
{this.partnum = partnum;}
public void setPrice(double price)
{this.price = price ;}
public void setStock(int stock)
{this.stock = stock ;}
public String getNum()
{return partnum;}
public double getPrice()
{return price;}
public int getStock()
{return stock;}
public int compareTo(ProductType otherType)
{
int temp = (this.getNum().compareTo(otherType.getNum()));
return temp;
}
//object1.compareTo(object2);
//(function).compareTo.function2;
public String toString()
{
String result = "" + partnum + " Price" + price + "Stock" + stock;
return result;
}
public static void main(String[] args)
{
ProductType r1 = new ProductType("1422", 1.00, 2);
ProductType r2 = new ProductType("8535", 2.00, 3);
Scanner in = new Scanner(System.in);
System.out.print("enter a Product number: ");
String num = in.nextLine();
if ( r1.equals(num))
System.out.print(r1);
}
}
Upvotes: 0
Views: 74
Reputation: 1133
while using the equals mrthod, we need to make sure that both are different instances of same class. The methods returns True if the argument is not null and is an object of the same type and with the same numeric value.So, if you are comparing the number as it looks like in this case, you should use as following.
if ( r1.getNum().equals(num)){
System.out.println(r1); // prints only if equal
}
Upvotes: 0
Reputation: 600
The equals()
method compares two objects for equality and returns true if they are equal. The equals()
method provided in the Object class uses the identity operator (==)
to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not.
In your case you are comparing ProductType
with String
which will never be equal, hence you can try comparing rq.getNum()
with num
which will give you the desiring result..
if (r1.getNum().equals(num)) {
System.out.print(r1);
}
Upvotes: 1
Reputation: 146
Did you mean to do the following?
if (r1.getNum().equals(num)) {
System.out.print(r1);
}
Upvotes: 2
Reputation: 6944
r1 is instance of ProductType and num is a string. So it will never be equal.
You could check r1 instance's num value with num string. Like
if ( r1.getNum().equals(num))
System.out.print(r1);
Upvotes: 3