如何将字符串数组作为参数传递给类对象?



我尝试将数组作为参数传递,而不是单个参数,这发生了。我哪里做错了?我是初学者,顺便说一句!

public class ClassArrayTest
{
public static void main(String[] args)
{
fruit f = new fruit({"peach","apple","mango"});
f.display();
}
}

class fruit
{
String[] a;

public fruit(String[] aa)
{
a = aa;
}

void display()
{
System.out.println(a);
}
}

OK…所以我认为你的问题是理解在Java中创建初始化数组的语法{"peach","apple","mango"}语法只能在两种上下文中使用:

String[] fruit = {"peach", "apple", "mango"};

new String[]{"peach", "apple", "mango"};

你想这样使用它:

someMethod({"peach", "apple", "mango"});

,但这是不允许的。这里不能使用{ ... }语法。但是你可以这样写:

someMethod(new String[]{"peach", "apple", "mango"});
public class ClassArrayTest {
public static void main(String... args) {
fruit f = new fruit(new String []{"peach","apple","mango"}); // use new Sring[]{""...} when passing an array
f.display();
}
}
class fruit
{
String[] a;

public fruit(String[] aa)
{
a = aa;
}

void display()
{
for(String stringElements : a){
System.out.println(stringElements );
}// i also find it easy to iterate through than print an object

}
}
import java.util.Arrays;
public class ClassArrayTest {

public static void main(String[] args) {
fruit f = new fruit(new String[] { "A", "B", "C" });
f.display();
}
}
class fruit {
String[] a;
public fruit(String[] aa) {
a = aa;
}
void display() {
Arrays.stream(a).forEach(System.out::println);
}
}

这是你想要的吗?

public class ClassArrayTest
{
public static void main(String[] args)
{
String[] aa = {"peach","apple","mango"};
fruit f = new fruit(aa);
f.display();
}
}

class fruit
{
String[] a;

public fruit(String[] aa)
{
a = aa;
}

void display()
{
// System.out.println(a);
for (String f: a) {
System.out.println(f);
}
}
}

我建议使用Fruit而不是fruit来命名Java中的类。

最新更新