Java代码类问题

Java代码类问题第一题,谢谢
2025-01-18 13:09:33
推荐回答(2个)
回答1:

public class A {

private int date;
private String str;

public A() {
}

public A(int date, String str) {
this.date = date;
this.str = str;
}

// 添加
public void add(int k,String s){

date += k;
str += s;
System.out.println("给date添加值以后的值是:" + date + "\n给str添加值以后的值是:" +str);
}

// 清除
public void cleanA(){

date = 0;
str = null;
System.out.println("清除date以后的值是:" + date + "\n清除str以后的值是:" +str);
}

// 转字符串
public String toStrng(){

String newDate = date + "";
str = str + "";
return "A [date=" + date + ", newDate=" + newDate + "]";
}

// 转字符串
public String toString() {
return "A [date=" + date + ", str=" + str + "]";
}

public static void main(String[] args) {

A a = new A(50,"hello");
a.add(10, "World");

String string = a.toString();
System.out.println("转字符串以后的结果" + string);

a.cleanA();

}
}

测试效果:

回答2:

public class A{
private int data;

private String str;

public A(){
data = 0;
str = "";
}

public A(int data,String str){
this.data = data;
this.str = str;
}
public void add(int k,String s ){
this.str +=s;

this.data += k
}
public void clearA(){
this.data =0;
this.str = "";
}

public String toString(){//这个地方的题出的有歧义,是双返回还是单返回?
return this.data+this.str;

}

public static void main(String args[]){
A a = new A();

a.add(1,"k');

a.clearA();

System.out.print(a.toString());

}
}