Мне поручено создать основной метод, вызывающий два метода. Первый метод возвращает массив строк, а второй метод принимает массив строк и распечатывает элемент в отдельных строках. затем основной метод передает результат вызова первого метода второму и затем останавливается. Я правильно понимаю вопрос? Когда я компилирую и выполняю, я получаю
sunshine
road
73
11
public class Hihihi
{
public static void main(String args[])
{
method1();
method2();//Will print the strings in the array that
//was returned from the method1()
System.exit(0);
}
public static String[] method1()
{
String[] xs = new String[] {"sunshine","road","73","11"};
String[] test = new String[4];
test[0]=xs[0];
test[1]=xs[1];
test[2]=xs[2];
test[3]=xs[3];
return test;
}
public static void method2()
{
String[] test = method1();
for(String str : test)
System.out.println(str);
}
}




Ваш код работает, но в main возвращаемое значение method1 игнорируется. И вызывать method1 в method2 не нужно.
Вы можете позволить method2 принимать параметр String[] strings:
public static void method2(String[] strings) {
for (String str : strings)
System.out.println(str);
}
и передаем результат method1 в method2:
String[] result = method1();
method2(result);//Will print the strings in the array that
Правильный способ сделать то же самое, что и ниже. Вы должны взять возвращаемое значение метода один и вставить его во второй метод в качестве параметра.
public class Hihihi
{
public static void main(String args[])
{
String[] test=method1();
method2(test);
}
public static String[] method1()
{
String[] xs = new String[] {"sunshine","road","73","11"};
String[] test = new String[4];
test[0]=xs[0];
test[1]=xs[1];
test[2]=xs[2];
test[3]=xs[3];
return test;
}
public static void method2(String[] newtest)
{
for(String str : newtest)
System.out.println(str);
}
}
Вы почти у цели: возврат вашего method1() должен использоваться в первом вызове (вы фактически игнорируете его), и вы должны использовать это возвращаемое значение (я также сделал некоторые заметки в коде):
public static void main(String args[]) {
String[] result = method1(); //TAKE THE VALUE HERE
method2(result);//pass the result here as parameter
System.exit(0); //there's no need of this, the program will exit when method2 is finished
}
Поэтому отредактируйте свой method2, чтобы получить результат method1 в качестве параметра
public static void method2(String[] arrayToPrint){
for(String str : arrayToPrint)
System.out.println(str);
}
Сначала поправьте свой method2
Он должен иметь возможность принимать массив элементов String в качестве параметра:
public static void method2(String[] test)
{
// this line is not needed -> String[] test = method1();
for(String str : test)
System.out.println(str);
}
Таким образом, вы фактически передаете данные методу в соответствии с вашими требованиями. Бонус в том, что его можно повторно использовать и для других массивов String.
Ваш method1 имеет много избыточного кода. Просто отфильтруйте это
public static String[] method1()
{
return new String[] {"sunshine","road","73","11"};
}
а теперь ваш метод main, просто чтобы связать их. Изменять
public static void main(String args[])
{
method1();
method2(); // this will now cause a compilation error, because it expects a parameter
System.exit(0);
}
к:
public static void main(String args[])
{
method2(method1());
System.exit(0);
}
Исходя из того, как был создан ваш код, method1 вызывался два раза, сначала в методе main, который был полностью избыточным, так как результат не использовался, второй раз в method2, где он не должен вызываться, поскольку данные следует передавать как параметр.
Если вы хотите, чтобы данные «текли» через основную систему, выполните следующие действия:
public static void main(String args[]){
String[] arr = method1();
method2(arr);
System.exit(0);
}
public static String[] method1(){
String[] xs = new String[] {"sunshine","road","73","11"};
String[] test = new String[4];
test[0]=xs[0];
test[1]=xs[1];
test[2]=xs[2];
test[3]=xs[3];
return test;
}
public static void method2(String[] arr){
for(String str : arr){
System.out.println(str);
}
}