我有 2 个类,测试类和主类。类测试有 2 个属性 a 和 b。我想让程序使用数组和用户输入的值。
public class Testing{
private String a,b;
public Testing(a,b){
this.a=a;
this.b=b;
}
public void getA(){
return a;
}
public void getB(){
return b;
}
}
接下来是我的主课
public class Main{
public static void main(String[] args){
Scanner ss = new Scanner(System.in);
Scanner s = new Scanner(System.in);
int x,i;
System.out.print("How many lines? ");
x = s.nextInt();
//method inputData
Testing ts[] = new Testing[x];
for (i=0; i<x; i++)
System.out.print("Enter Value A :"); String a = ss.nextLine();
System.out.print("Enter Value B "); String b = s.nextInt();
ts[i] = new Testing(a,b);
}
//method outputData
System.out.println("Output---");
for(i=0; i<x; i++){
System.out.print("Value A"+i+" "+ts[i].getA());
System.out.print("Value B"+i+" "+ts[i].getB());
}
}
它实际上工作正常,但我想将下面的代码从//method inputData 和//method outputData 移动到测试。所以,我只是从 Main 调用方法 inputData()
和 outputData()
。但我不知道该怎么做。
如果你能帮助我,我将不胜感激。
最佳答案
首先,方法应该在主方法之外声明。只需将方法部分复制到测试文件即可。然后,实例化一个测试对象:
Testing test = new Testing(...)
test.inputData()
test.outputData()
关于java - 在 Java 中使用方法输入和输出变量数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34155408/