求助!如何用java编写一个程序,使得将输入的一串字符逆序输出?
答案:4 悬赏:60 手机版
解决时间 2021-02-05 05:36
- 提问者网友:萌卜娃娃
- 2021-02-04 07:02
具体要求是,运行的时候要在键盘上输入一组字符,要求不能用改变数组元素顺序的办法。是不是要用递归或者是用reverse呢?本人水平不太高,求高手指教。编写一个语句不太复杂的程序!谢谢了!!
最佳答案
- 五星知识达人网友:过活
- 2021-02-04 08:08
不用递归吧,循环或者reverse都可以,reverse最高效了
import java.util.Scanner;
public class Du {
public static void main(String[] args) {
System.out.println("Please input some string content: ");
Scanner scanner = new Scanner(System.in);
String content = scanner.nextLine().trim();
///***** reverse way /////
String reversedStr = new StringBuffer(content).reverse().toString();
System.out.println("Reversed string is: " + reversedStr);
//***** cycle way /////
System.out.println("\n Reversed by cicyle: ");
for(int i = content.length() - 1; i >= 0; i--){
System.out.print(content.charAt(i));
}
}
}
---------------
Please input some string content:
welcome to china, 12342345abcdefg
Reversed string is: gfedcba54324321 ,anihc ot emoclew
Reversed by cicyle:
gfedcba54324321 ,anihc ot emoclew
import java.util.Scanner;
public class Du {
public static void main(String[] args) {
System.out.println("Please input some string content: ");
Scanner scanner = new Scanner(System.in);
String content = scanner.nextLine().trim();
///***** reverse way /////
String reversedStr = new StringBuffer(content).reverse().toString();
System.out.println("Reversed string is: " + reversedStr);
//***** cycle way /////
System.out.println("\n Reversed by cicyle: ");
for(int i = content.length() - 1; i >= 0; i--){
System.out.print(content.charAt(i));
}
}
}
---------------
Please input some string content:
welcome to china, 12342345abcdefg
Reversed string is: gfedcba54324321 ,anihc ot emoclew
Reversed by cicyle:
gfedcba54324321 ,anihc ot emoclew
全部回答
- 1楼网友:低音帝王
- 2021-02-04 09:42
String s=123;
for(int i=s.length-1;i>0;i--){
System.out.println(s.charAt(i))
}
- 2楼网友:拾荒鲤
- 2021-02-04 08:31
你这样想,逆序,就是从后往前输出,所以啊,你应该将每个字符分割,存放到一个字符数组中,使用循环从后往前输出就好了!具体的实现就是上楼的代码!
- 3楼网友:慢性怪人
- 2021-02-04 08:24
public class ab {
public static void main(string[] args) {
string[] s={"to" ,"be" ,"or" ,"not" ,"to", "be"};
for(int i=s.length-1;i>=0;i--){
system.out.print(s[i]+" ");
}
}
}
str数组只有1个元素那就是to be or not to be所以只能出现to be or not to be,所以要把他们分成不同的元素
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯