gpt4 book ai didi

java - 将字符串数组返回给其他类(包括继承)并打印

转载 作者:行者123 更新时间:2023-12-01 23:22:04 25 4
gpt4 key购买 nike

我在将数组返回到 java 中的其他类或继承子类时遇到问题。

A级

import java.util.Scanner;

public class A {
String [] month = new String[4];
Scanner sc = new Scanner(System.in);

public String[] Select()
{
System.out.println("choose");

int pick=sc.nextInt();
switch(pick)
{
case 1:
month[0]="January";
break;
case 2:
month[0]="February";
break;
case 3:
month[0]="March";
break;
case 4:
month[0]="April";
break;

}
return month;
}

}

C级

    public class C extends A{

public void child_class()
{
System.out.println(month[0]);
}

}

B级

public class B {

A select = new A ();
public void normal_class()
{
System.out.println(select.month[0]);
}
}

主类公共(public)类主{

public static void main(String[] args) {

A sun = new A();
B moon = new B();
C star = new C();

System.out.println(sun.month[0]);
moon.normal_class(); //
star.child_class();
}

}

结果

null
null
null

我想将数组的结果返回给类或子类。如果我在A类中选择情况1,我想从类中获取结果“January”

最佳答案

请更正并完成问题中的类,将其复制到编辑器中,并确保使用预览时它们看起来正确。我不明白 B 类中 print(test.arr[0]); 中的 test 来自哪里。但是,您正在打印尚未初始化的对象。这就是为什么你看到 null。

当您使用 A sun = new A(); 创建 A 然后打印它时 print(sun.arr[0]); 您从未运行过测试或者给 arr 赋值。

编辑原始类后。

System.out.println(sun.month[0]); 正在访问 A 类中的 month 但因为您没有调用 Select 方法(应以小写字母开头),您将永远不会用数据填充数组月份。

试试这个:

public class A {
String [] month = new String[4];

public String[] select(int pick)
{
switch(pick)
{
case 1:
month[0]="January";
break;
case 2:
month[0]="February";
break;
case 3:
month[0]="March";
break;
case 4:
month[0]="April";
break;

}
return month;
}

public static void main(String[] args) {

    A sun = new A();
B moon = new B();
C star = new C();

sun.select(1);
System.out.println(sun.month[0]); //printing January
moon.normal_class(); //you are not printing anything here
star.child_class(); //you are not printing anything here
}

关于java - 将字符串数组返回给其他类(包括继承)并打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58325590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com