在java中,如何从for循环中减去,而不以负循环结束?
所以我试图向后打印一个字符串,但它并没有从我想要的地方开始。每当我运行代码时,它都会说它从-1开始。这是我的密码:在java中,如何从for循环中减去,而不以负循环结束?,java,Java,所以我试图向后打印一个字符串,但它并没有从我想要的地方开始。每当我运行代码时,它都会说它从-1开始。这是我的密码: public static String reverse(String str) { //This method will return a string that reverses the letters in 'str' //Example: // reverse("abcdef") returns
public static String reverse(String str)
{
//This method will return a string that reverses the letters in 'str'
//Example:
// reverse("abcdef") returns "fedcba"
String result="";
for(int i = str.length()-1; i >= 0; i--){
result = result + str.substring(i-1, i);
}
return result;
}
我怎样才能让它减去1,而不是认为它是负数呢?为什么不一个接一个地拼接字符呢
for(int i = str.length() - 1; i >= 0; i--){
result += str.charAt(i);
}
代码中有一个逻辑问题 正确的执行应该是正确的
//using subString the way you are trying
public static String reverse(String str)
{
String result="";
for(int i = str.length()-1; i >= 0; i--){
result = result + str.substring(i, i+1);
}
return result;
}
使用charAt的替代方法
public static String reverse(String str)
{
String result="";
for(int i = str.length()-1; i >= 0; i--){
result +=str.charAt(i);
}
return result;
}
使用字符串生成器(如果您不是为了学习而编写代码,那么这可能是最好的方法)
您应该使用:
i>0
noti>=0
尝试将str.substring(i-1,i)
更改为str.substring(i,i+1)
String reversed = new StringBuilder(str).reverse().toString();