有人可以,最好是详细解释以下代码行中的内容吗?
originalString = input.nextline;
int length = originalString.length;
for (int i = length - 1; i >= 0 ; i --)
String reverse = reverse + originalString.charAt(i);
答案 0 :(得分:1)
originalString= input.nextline;
要求输入并将其保存在变量originalString
中。
int length= originalString.length;
获取此变量(输入)的长度并将其保存为length
for (int i= length -1; i >=0; i --)
本质上是一个循环,循环运行的次数与变量中包含字符的次数相同。
String reverse= reverse + originalString.charAt(i);
这将引发错误,因为您正在调用反向,因为尚未定义。
另外,循环应如下所示:
for (int i= length -1; i >=0; i --) {
String reverse= reverse + originalString.charAt(i);
}
需要使用花括号将循环打开和关闭。您可能还想在这里阅读一些有关Java缩进最佳实践的信息:http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html
答案 1 :(得分:1)
首先,该代码存在许多语法错误。尝试修复它们并显示您尝试过的内容。基本上,代码段正在执行reverse()
,工作代码并带有解释:
// 1. Read a string
String originalString = "stackoverflow"; // or input.nextLine();
// 2. Get the length of the string
int originalStringLength = originalString.length();
// 3. declare a string that can hold reverse of original
String reverseString = "";
// 4. Loop through and add characters in reverse order using index
for(int i= originalStringLength-1; i >= 0; i--) {
reverseString = reverseString + originalString.charAt(i);
}
// 5. Print to check
System.out.println(reverseString);
在此处执行以上操作:http://www.javarepl.com/term.html应该给您:
wolfrevokcats
答案 2 :(得分:0)
此代码主要用于反转字符串。但是您在循环内声明了反向变量。对于循环的每次迭代,都会声明一个新的反向变量,并且该反向变量中可用的旧数据将丢失。
答案 3 :(得分:0)
完整的工作代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the word");
String originalString = input.nextLine(); //Asks & Stores the input from user in String variable called originalString.
int length = originalString.length(); //Calculates the length of the input String.
String reverse = ""; //Declares the String variable called reverse.
for (int i = length - 1; i >= 0; i--) { //loops from (length -1) to 0 (Both indices inclusive)
reverse = reverse + originalString.charAt(i); //stores the last character followed by second to last and so on.
}
System.out.println("Reverse of " + originalString + " is " + reverse);
}
}
输出:
请输入单词
FooBar
FooBar的反面是raBooF
以退出代码0结束的过程