Reputation: 13
This code isn't working. Can you tell me what's wrong and why?
package exer0403e08;
public class EXER0403E08 {
public static void main(String[] args) {
String str= "hello";
System.out.println(str);
char[]strchar = str.toCharArray();
int first;
int last=5;
System.out.println("The reversed is: ");
for (first=1; first<=5; first++){
strchar[first]=strchar[last];
last--;
}
str=String.valueOf(strchar);
str=str.toUpperCase();
System.out.println(str);
}
}
The answer is "OLLO" and i want to make it "OLLEH".
Upvotes: 0
Views: 2152
Reputation: 175
you can write your own method like this:
public static String reverse(String str)
{
String reversed = new String();
for ( int j = str.length()-1; j >= 0; j-- )
reversed += str.charAt(j);
return reversed;
}
and then try reverse("Hello");
Upvotes: 1
Reputation: 121998
You loop have several problems. And you misunderstood the array indexes.
You are iterating and modifying the same array. Hence the weird behaviour and indexces will start from zero for arrays.
So the fixed code will be
public static void main(String[] args) {
String str = "hello";
System.out.println(str);
char[] strchar = str.toCharArray();
int first;
int last = 4;
System.out.println("The reversed is: ");
for (first = 0; first < 5; first++) {
strchar[first] = str.charAt(last);
last--;
}
str = String.valueOf(strchar);
str = str.toUpperCase();
System.out.println(str);
}
Update :
Demo link http://ideone.com/GfgDZ3
Upvotes: 1
Reputation: 2593
You have better methods in java to reverse string. Please check this answer :
You can use this:
new StringBuilder(hi).reverse().toString()
Or, for versions earlier than JDK 1.5, use java.util.StringBuffer
instead of StringBuilder
— they have the same API. Thanks commentators for pointing out that StringBuilder
is preferred nowadays.
Upvotes: 0