用java编写一段程序,输入一段字符串,然后输出该字符串的倒序状态。

2024-11-08 23:50:25
推荐回答(4个)
回答(1):

import java.util.*;//倒入的util中的包用Scanner类;
public class TestOhce {
public static void invertOrder(String s) { //这是倒序的字符串,用字符数组实现;
char[] cArray = s.toCharArray();
for (int i = 0, j = cArray.length - 1; i < j; i++, j--) { //倒序算法;
char tmp; //设置一个中间字符变量;
tmp = cArray[j];
cArray[j] = cArray[i];
cArray[i] = tmp;
}
for (int i = 0; i < cArray.length; i++) {
System.out.print(cArray[i] + " ");
}
}
public void charIO() { //字符数组输出
Scanner s = new Scanner(System.in);//输入一个字符串;
while (true) {
System.out.println("intput: ");
String str = s.next();//输入字符串赋值给str
if ("exit".equals(str)) {
System.out.println("bye - bye");//判断是否退出;
} else {
this.invertOrder(str);//调用倒序算法
}
}
}
public static void main(String[] args) {
new TestOhce().charIO();//创建对象;
}
}

回答(2):

你看看行不:a.java
import java.util.Scanner;
import java.lang.String;
public class a{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String s=sc.next();
StringBuffer str=new StringBuffer();
str.append(s);
System.out.println(str.reverse().toString());
}
}

回答(3):

定义成一个StringBuffer类,用StringBuffer类中的reverse()方法
直接就倒序输出了
package sscr;
import javax.swing.JOptionPane;
public class StringP2 {
public static void reverseString(String str)
{
StringBuffer stringbuffer=new StringBuffer(str);
System.out.print(stringbuffer.reverse());
}
public static void main(String[] args)
{
String s;
s=JOptionPane.showInputDialog("please input a String:");
reverseString(s);
}
}

回答(4):

类名:Invert
import java.util.Scanner;
public class Invert {
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
String str=input.next();
char[] strm=str.toCharArray();
for(int i=0;i System.out.print(strm[str.length()-1-i]+" ");
}
}