r/javahelp • • Oct 10 '15

Write a public method called reverse, which is passed a String as a parameter and which returns the input parameter in reverse order --- a String value. Example: "abcd" --> "dcba"

public String reverse(String x){

for (int i = (x.length()-1); i>=0;i=i-1){

}

return(x.charAt(i));

}

2 Upvotes

6 comments sorted by

3

u/empire539 "empire"+(((int)-~(byte)+('\''&~'&')<<(' '>>('+'+~'(')))+0x1b); Oct 10 '15

It can't find the symbol because i is defined only inside the for loop.

-3

u/lmmuir Oct 10 '15

how do i make it run...

1

u/empire539 "empire"+(((int)-~(byte)+('\''&~'&')<<(' '>>('+'+~'(')))+0x1b); Oct 10 '15

You should put all your operations involving i inside the for loop, and then return the final String at the end. You will probably want to create a new String which will be used to store each character as the loop traverses the String.

5

u/404_UserNotFound Oct 10 '15 edited Oct 10 '15
public String reverse(String x){

 for (int i = (x.length()-1); i>=0;i=i-1){

 }

return(x.charAt(i));

}

Since you probably have never heard the word scope I will give you the spoiler on this one.

int y;
for(int x;x<y;){ some code } 
//x no longer exists because we are outside the for loop.
//y is still useable because it is part of the bigger section of code

What is happening in the loop?

int i = (x.length()-1) . . does it need to be in () ? does it affect the value of i ?Does it affect readability?

i=i-1 . . . vs i-- | just a helpful bit of info to look into

Why is your return a char not a string? shouldn't you return the reversed string?

If you are only returning one char and your varibile I goes out of scope next time you call this method wont it return the same lest letter?

-2

u/lmmuir Oct 10 '15

says cannot find symbol at the i of the return(x.charAt(i));

-2

u/lmmuir Oct 10 '15

what do i do to fix it...