有个Java的小程序不会写

定义一个类A,类中有一个private的整型变量data;一个private的字符串对象str。类中有两个构造函数,一个不含参数,初始化data和str为其缺省值;另一个有两个参数,分别用来初始化data和str。类中还定义了三个方法,方法头的定义和其功能如下。
public A add(int k, String s);该方法把data和str的值分别加上k和s。
编写应用程序测试类A,使用类A中的add方法并将结果输出

4个回答

按照要求,实例代码如下:

 public class A {
    private int data;
    private String str;

    public A(){

    }

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

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

    public static void main(String[] args) {
        A a = new A(10,"a");
        a.add(1, "add");
        System.out.println("after add ,data is:"+a.getData()+";str is:"+a.getStr());
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }


}

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.data+=k;
this.str+=s;
}

public void clear(){
this.data = 0;
this.str = "";
}

public String toString(){
String s = data+"";
s+=str;
return (s);
}

public static void main(String args[]){
A a = new A();
a.add(10,"Hello");
System.out.println("data is:"+a.data+" str is:"+a.str);
System.out.println(a.toString());
a.clear();
A b = new A(199,"nihao");
System.out.println("data is:"+b.data+" str is:"+b.str);
System.out.println(b.toString());
b.add(200, " dajiahao");System.out.println("data is:"+b.data+" str is:"+b.str);
System.out.println(b.toString());
}
}

 import java.util.*;

public class Test {

    public static void main(String[] agrs){

        A  mytestA = new A(1, "I love ");
        mytestA.add(1, "China");
        int tmpData = mytestA.getData();
        String tmpStr = mytestA.getStr();
        System.out.printf(tmpData + "   " + tmpStr);
    }
}

class A{
    private int data;
    private String str;

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

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

    public int getData(){
        return this.data;
    }

    public String getStr(){
        return this.str;
    }
}
//这里void就行
 public viod add(int k, String s){
        this.data += k;
        this.str+=s;
    }
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐