Reputation: 97
I want to know if (and how) I can put my reversed array from my method ArrayReverse
in the array result
(where the ?????????? are) in my main
method.
The code should print out "Funktioniert"
My code:
public class blubb {
public static void main(String[] args) {
char[] array = {'t', 'r', 'e', 'i', 'n', 'o', 'i', 't', 'k', 'n', 'u', 'F'};
char[] result= new char[??????????];
result=ArrayReversed(array);
for (int i = 0; i < ergebnis.length; i++) {
System.out.println(ergebnis[i]);
}
}
public static char[] ArrayReversed(char[] arr) {
char [] blubb= new char[arr.length];
for (int i = arr.length-1; i >=0; i--) {
blubb[i]=arr[i];
}
return blubb;
}
}
Upvotes: 0
Views: 177
Reputation: 121
You don't need to allocate new memory to result. Something like this should work (note some changes I made to your code since there was one more bug in your code)
public class blubb {
public static void main(String[] args) {
char[] array = {'t', 'r', 'e', 'i', 'n', 'o', 'i', 't', 'k', 'n', 'u', 'F'};
char[] result= ArrayReversed(array);
System.out.println(result);
}
public static char[] ArrayReversed(char[] arr) {
char [] blubb= new char[arr.length];
for (int i = arr.length-1, j = 0; i >=0; i--, j++) {
blubb[i]=arr[j];
}
return blubb;
}
}
Upvotes: 0
Reputation: 1801
why not just do char[] result = ArrayReversed(array);
Also, your method ArrayReversed is wrong. It should be like this.
public static char[] ArrayReversed(char[] arr) {
char [] blubb= new char[arr.length];
for (int i = arr.length-1; i >=0; i--) {
blubb[i]=arr[arr.length-1-i];
}
return blubb;
}
Upvotes: 0
Reputation: 193
All the answers are correct, you just assign the return result to your variable:
char[] result = ArrayReversed(array);
The reason you think it doesn't work is because of this line in your code:
for (int i = arr.length-1; i >=0; i--) {
blubb[i] = arr[i];
}
This is not going to revers the array. You are just copying same characters from one array to another, into same positions. Perhaps you are looking for something like:
for(int i=0; i<arr.length; i++) {
blubb[i] = arr[arr.length-1-i];
}
Upvotes: 1
Reputation: 178
Basically, you don't need to initialize your "result" array. Just set it to the returned value of ArrayReversed. Then in your for loop, you actually want to use the result array and iterate/print out its values.
public class blubb {
public static void main(String[] args) {
char[] array = {'t', 'r', 'e', 'i', 'n', 'o', 'i', 't', 'k', 'n', 'u', 'F'};
char[] result;
result=ArrayReversed(array);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
public static char[] ArrayReversed(char[] arr) {
char [] blubb= new char[arr.length];
for (int i = arr.length-1; i >=0; i--) {
blubb[i]=arr[i];
}
return blubb;
}
}
Upvotes: 0