Home > Article > Computer Tutorials > How can I read an input string in Java?
I wrote a more general method, which is not limited to 3 characters, and can be of any length. It can be used for communication:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string:");
String str = input.next();
Reverse(str);
}
public static void Reverse(String str){
System.out.println ("The reversed string is:");
for(int i = 0; i String temp = """;
temp = temp str.charAt(str.length()-i-1);
System.out.print(temp);
}
I don’t know why you have this idea. If you have a good algorithm, you can discuss it with me. I wrote 2 codes below hoping to help you.
package app;
public class TransDemo {
//abcdef" is reversed to "fedcba
public static void main(String[] args){
String str = "abcdef";
char[] ary = str.toCharArray();
for(int i = 0; i
int temp = ary[ary.length-i-1]-ary[i];
ary[i] = temp;
ary[ary.length-i-1] -=temp;
}
str = new String(ary);
System.out.println(str);
}
}
package app;
public class TransDemo {
//abcdef" is reversed to "fedcba
public static void main(String[] args){
String str = "abcdef";
char[] ary = str.toCharArray();
for(int i = 0; i
char c = ary[i];
ary[i] = ary[str.length()-1-i];
ary[str.length()-1-i] = c;
}
str = new String(ary);
System.out.println(str);
}
}
The above is the detailed content of How can I read an input string in Java?. For more information, please follow other related articles on the PHP Chinese website!