0
Plz, tell me the error in this program...!! Did I successfully reversed the string garbage....!! I need ur help
import java.util.*; public class Program { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String text = "garbage"; String lght = text.lenght(); for(i=lght-1;i>=0;i--){ char letter = text.toCharAt(i); String rev =rev+letter; System.out.println(rev); } } }
2 Answers
+ 2
Fix a typo,
text.lenght -> text.length
text.length returns integral value,
Change String lght -> int lght
Define <rev> string as empty string before the for-loop, otherwise you won't get the result as expected.
Undefined variable <i> in loop definition
for(int i = lght - 1; i >= 0; i--)
Change text.toCharAt -> text.charAt
char letter = text.charAt(i)
The line below better be out of the for-loop body, otherwise you will be printing <rev> in each loop iteration.
System.out.println(rev);
+ 1
Hello... Try this:
import java.util.*;
public class Program
{
public static void main(String[] args) {
//Scanner scan = new Scanner(System.in);
String text = "garbage";
//String lght = text.lenght();
int lght = text.length();
for(int i=lght-1;i>=0;i--){
char letter = text.charAt(i);
String rev ="";
rev=rev+letter;
System.out.print(rev);
}
}
}