我现在是学生,所以我还在学习。我很快就学会了 VB,但另一方面,我很困惑它是简单的 Java。
这次给我的作业让我很困惑“写一个方法来确定两个字符串不同的位置数。例如,”Peace”和“Piece”在两个位置上不同。方法声明为int compare(String word1, String word2); 如果字符串相同,则该方法返回 0。如果两个字符串的长度不同,则返回 -1。"
附加“编写一个主要方法来测试该方法。主要方法应该告诉字符串有多少,位置不同,或者它们是相同的,或者如果它们是不同的长度,则说明长度。从控制台获取字符串。到目前为止这就是我所在的地方,如果可以的话,我正在寻找可以帮助我用 DUMDUM 术语解决这个问题的人,我不需要解决方案,只需要帮助理解它。
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");
}