我现在是一名学生,所以我仍在学习。我很快就学会了 VB,而且 Java 很简单,但我对它却很困惑。
这次给我的作业让我很困惑“编写一个方法来确定两个字符串不同的位置数。例如,“Peace”和“Piece”有两个位置不同。该方法声明为 intcompare(String word1, String word2);如果字符串相同,则该方法返回 0。如果两个字符串长度不同,则返回 -1。”
附加“编写一个主要方法来测试该方法。主要方法应该告诉字符串有多少个位置不同,或者它们相同,或者如果它们的长度不同,则说明长度。从控制台获取字符串。 到目前为止,这就是我所处的位置,我正在寻找有人帮助用我愚蠢的术语来解决这个问题,如果他们可以的话,我不需要解决方案,只需要帮助理解它。
package arraysandstrings;
import java.util.Scanner;
public class differStrings {
public static void main (String agrs[]){
Scanner scanner = new Scanner (System.in);
System.out.print("Enter a word");
String word1;
String word2;
word1 = scanner.next();
System.out.print("Enter another word");
word2 = scanner.next();
int count = 0;
int length = word1.length();
for(int x = 0; x >= length; x = x+1) {
if (word1.charAt(x) == word2.charAt(x)) {
count = count + 1;
System.out.print (count);
}
}
}
}
附加问题
package arraysandstrings;
import java.util.Scanner;
public class differStrings {
public static void main (String agrs[]){
Scanner scanner = new Scanner (System.in);
System.out.println("Enter a word");
String word1 = scanner.next();
System.out.println("Enter another word");
String word2 = scanner.next();
int count = 0;
int word1Length = word1.length();
int word2Length = word2.length();
if (word1Length != word2Length) {
System.out.println ("Words are a diffrent length");
System.out.println (word1 + "Has" + word1.length() + " chars");
System.out.println (word2 + "Has" + word2.length() + " chars");
}
for(int x = 0; x < word1Length; x = x+1) {
if (word1.charAt(x) != word2.charAt(x)) {
count = count + 1;
}}}
System.out.println (count+" different chars");
}
在实现了从您的回复中获得的知识后,我遇到了最后一行的问题:
System.out.println (count+" different chars");
它说预期错误,但在我添加作业的下一部分之前它就起作用了:
if (word1Length != word2Length) {
System.out.println ("Words are a diffrent length");
System.out.println (word1 + "Has" + word1.length() + " chars");
System.out.println (word2 + "Has" + word2.length() + " chars");
}
最佳答案
for(int x = 0; x >= length; x = x+1) {
你的意思可能是
for(int x = 0; x < length; x = x+1) {
关于java - 无法弄清楚 Java 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16071944/