java使用方法toString()打印对象
Hellow我有一个rmiclient和RMIserver,并发送了一系列对象产品,我想用toString put it show me将其打印为列表{Product2@sad45我不能去 代码是
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int pin=0;
String tostring="";
try {
String name = "//Localhost/RMI_Server";
Functions lp =(Functions)Naming.lookup(name);
try{
System.out.println("Please give your Personal Code (PIN)");
pin=in.nextInt();
}catch (Exception nfe) {
System.out.println("Input must be a number." + nfe);
}
if(lp.validate(pin)){
System.out.println("Give description of item");
String desc=in.next();
Product [] p =lp.search(desc);
for(int i=0;i<p.length;i++){
tostring=(String)p[i];
System.out.println(tostring);}
System.out.println("Give numberCode of item you want to buy");
String code=in.next();
System.out.println(lp.purchase(code));
}else{
System.out.println("Your code is False");}
lp.close();
}catch (Exception e) {
System.out.println("SumClient err: " + e);
System.exit(1);
}
}
}
类产品的代码是
import java.io.Serializable;
public class Product implements Serializable {
private String description;
private String serialNum;
private float price;
private String company;
public Product(String description,String serialNum,float price,String company){
this.description=description;
this.serialNum=serialNum;
this.price=price;
this.company=company;
}
public void set_description(String description){this.description=description;}
public String get_description(){return description;}
public void set_serialNum(String serialNum){this.serialNum=serialNum;}
public String get_serialNum(){return serialNum;}
public void set_price(float price){this.price=price;}
public float get_price(){return price;}
public void set_company(String company){this.company=company;}
public String get_company(){return company;}
public String toSting(){
String str="Item "+ this.serialNum +" is product from "+ this.company +" price " + this.price +"E Description: ( "+ this.description +" )";
return str;
}
}
# 1 楼答案
你的
toString
方法中有一个输入错误:toSting
而不是toString
# 2 楼答案
除了将
public String toSting()
更改为public String toString()
之外,代码中还有另一个问题像排队时那样把你的
Product
投给String
是错误的只需打印
Product
,它的toString
方法就会自动为您调用