+ 1
Hi guys I'm new in java can anyone help me to print out a reversed string this my code:
import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String text = scanner.nextLine(); char[] arr = text.toCharArray(); int i,j; j=text.length; for(i=0;i<arr.length;i++){ arr[i]=text[j]; --j; } for(i=0;i<arr.length;i++){ System.out.print(arr[i]); } } }
14 Answers
+ 4
just replace
String sample = "Sample string";
with
String sample = new Scanner(System.in).nextLine();
for getting input
+ 3
Try iterating through your input in reverse with your for loop.
Example:
public class Program
{
public static void main(String[] args) {
for(int i=9; i>=0; i--){
System.out.println(i);
}
}
}
+ 3
String text = sc.nextLine();
StringBuilder sb = new StringBuilder(text);
System.out.println(sb.reverse().toString());
+ 3
Martin Taylor Niththish I see thank u all ,I really apericiate it
+ 2
GHOST mHBr thank u
+ 2
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
char[] arr = text.toCharArray();
int i;
for(i=arr.length-1;i>=0;i--){
System.out.print(arr[i]);
}
}
}
+ 2
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String text = in.nextLine();
for (int i=text.length()-1;i>=0;i--)
System.out.print(text.charAt(i));
}
}
+ 1
reverse() is the key!
But you can do this by yourself:
something like this:
String sample = "Sample string";
String rev = "";
int r=0;
for (int i=0 ; i < sample.length() ; i++){
r = sample.length()-i;
rev.charAt(i) = sample.charAt(r);
{
System.out.println(rev);
+ 1
This will work:
public class Program
{
public static void main(String[] args){
String sample = "Sample string";
char rev[] = sample.toCharArray();
int r=0;
for (int i=0 ; i < sample.length() ; i++){
r = sample.length()-i-1;
rev[i] = sample.charAt(r);
}
System.out.println(rev);
}
}
+ 1
GHOST mHBr I know but I want the user to input the string!
+ 1
Something like this:
https://code.sololearn.com/c4y31h1S2K16/?ref=app
0
Rik Wittkopp when i compile it , an error message appears indicating there is a problem in line 12