我编写了一段代码来反转Java中的字符串。但是,它显示出多个错误,我希望了解我哪里出错了。我知道有其他方法可以反转字符串。但是,我想知道我的代码出错了。
public class RevString {
public static void main(String[] args)
{
public Reverse (String str)
{
int len = str.length();
String rev;
for (int i = 0; i <= len; i++)
{
rev = str[i] + rev;
}
System.out.println(rev);
}
Reverse("Canyon");
}
}
错误:
Multiple markers at this line
- Syntax error on token ")", ; expected
- Syntax error on token "(", . expected
- Reverse cannot be resolved to a type
- Illegal modifier for parameter str; only final is
The method Reverse(String) is undefined for the type
RevString
有人能为我提供解决方案吗?
答案 0 :(得分:2)
您的代码中有许多错误:
i < len
此外,这是一个简单的一个用于字符串反转的衬垫:
new StringBuilder(str).reverse().toString()
如果您想在Java中进行任何类型的字符串操作,可能需要使用StringBuilder类。
答案 1 :(得分:1)
您的代码有很多问题:
Reverse()
。rev
初始化为空字符串。str.charAt(i)
访问字符串的每个字符。i <= len;
,那么for循环将超出字符串
应为i < len;
。Reverse()
方法应为static
,因为您在main
中呼叫它
方法(static
)这是工作代码。
public class RevString {
public static void main(String[] args) {
Reverse("Canyon");
}
public static void Reverse (String str) {
int len = str.length();
String rev="";
for (int i = 0; i < len; i++) {
rev = str.charAt(i) + rev;
}
System.out.println(rev);
}
}
答案 2 :(得分:0)
请参阅以下代码:
public class Hello {
public static String reverse (String str){
int len = str.length();
String rev="";
char[] strArray = str.toCharArray();
for (int i = 0; i < len; i++)
{
rev = strArray[i] + rev;
}
return rev;
}
public static void main(String[] args) {
String result = reverse("Canyon");
System.out.println("Reversed String: " + result);
}
}
答案 3 :(得分:0)
public class reverseString
{
public static void main(String[] args)
{
System.out.println("Welcome to the the string reverser.");
System.out.println("Here is where a person may put is a sentence and the orintation" +
" of the words is reversed.");
Scanner keyboard = new Scanner(System.in);
String word = keyboard.nextLine();
int lengthOf = word.length();
int j = 0;
char loopStr;
String LoopStr;
String Nstr = "";
for(int n = lengthOf; n >0 ;n--)
{
j = n;
LoopStr = word.substring(j-1,j);
Nstr = Nstr + LoopStr;
}
System.out.println(Nstr);
}
}