英文:
How do I pass a String Array inside of a method to another method?
问题
import java.util.Arrays;
public class YourClassName { // Add your class name here
public static void ArrayPrinter(String[] transactions) {
System.out.println(Arrays.toString(transactions)); // Print the array using Arrays.toString()
}
public static String[] TransactionName() { // Make this method static
String[] transactions = new String[]{"Mr. ", "Mrs. ", "Ms. "};
ArrayPrinter(transactions);
return transactions; // Add a return statement to return the transactions array
}
public static void main(String[] args) {
TransactionName(); // Call the method from the main method
}
}
请注意,你之前的代码存在一些问题。我进行了以下更改:
- 添加了一个类名
YourClassName
,你需要将它替换为你自己的类名。 - 将
ArrayPrinter
方法和TransactionName
方法声明为static
,这样你就可以从静态的main
方法中直接调用它们。 - 在
ArrayPrinter
方法中,使用Arrays.toString(transactions)
来打印数组内容。 - 在
TransactionName
方法中,添加了一个return transactions;
语句,以便可以将数组返回。 - 添加了一个名为
main
的方法,用于调用TransactionName
方法,从而启动程序并执行操作。
请确保将 YourClassName
替换为你的实际类名,以便代码能够正常编译和运行。
英文:
I have two methods (not using a main method in this example), and I'm trying to pass the String array "transactions" found in the TransactionName method to the ArrayPrinter method and print it out. No return statements if possible.
Yes, I'm aware that the method headings probably need fixing to allow it to happen, so I'd like some help on that too. Sorry for the mess ahead of time.
import java.util.Arrays;
//I don't have my class or main method posted to save room ;)
public static void ArrayPrinter(String[] transactions)
{
System.out.println(transactions);
}
public String[] TransactionName()
{
String[] transactions = new String[]{"Mr. ", "Mrs. ", "Ms. "};
ArrayPrinter(transactions);
}
How can I make it compile?
答案1
得分: 0
你需要在静态方法内部实例化该类以调用非静态方法。
public class Test {
public static void main(String[] args) {
String[] transactions = new String[]{"Mr. ", "Mrs. ", "Ms. "};
ArrayPrinter(transactions);
}
public static void ArrayPrinter(String[] transactions) {
Test t = new Test();
for (String s : t.TransactionName()) {
System.out.println(s);
}
}
public String[] TransactionName() {
String[] transactions = new String[]{"Mr. ", "Mrs. ", "Ms. "};
return transactions;
}
}
以上代码将调用非静态方法并输出以下内容 -
Mr.
Mrs.
Ms.
英文:
You need to instantiate the class inside the static method to call non static method
public class Test {
public static void main(String[] args) {
String[] transactions = new String[]{"Mr. ", "Mrs. ", "Ms. "};
ArrayPrinter(transactions);
}
public static void ArrayPrinter(String[] transactions) {
Test t = new Test();
for(String s : t.TransactionName()) {
System.out.println(s);
}
}
public String[] TransactionName() {
String[] transactions = new String[] { "Mr. ", "Mrs. ", "Ms. " };
return transactions;
}
}
The above code will call the nonstatic method and outputs following -
Mr.
Mrs.
Ms.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论