我确实有一些代码,我觉得无法理解。我在变量中保存了一个较长的字符串,然后尝试在其中找到一段特定的字符串。线索是我可以输出各种子串,但它不会找到特定的字符串并停止进程......
import java.io.*;
import java.util.*;
public class Readin {
public static void main(String[] args) {
String specChar = "DISD";
String gen = "MLRVFILYAENVHTPDTDISDAYCSAVFAGVKKRTKVIKNSVNP";
for (int i = 0; i < gen.length() - 3; i++) {
char char1 = gen.charAt(i);
char char2 = gen.charAt(i + 1);
char char3 = gen.charAt(i + 2);
char char4 = gen.charAt(i + 3);
String concatChar = new StringBuilder().append(char1).append(char2).append(char3).append(char4).toString();
System.out.println(concatChar);
if (specChar == concatChar) {
System.out.println(specChar);
break;
} else {
System.out.println("Error");
}
}
}
}
答案 0 :(得分:0)
简短回答:您需要将(specChar == concatChar)
替换为(Objects.equals(specChar, concatChar))
或(specChar.equals(concatChar))
,然后您将转到break
运营商
答案 1 :(得分:0)
在查看您的代码之后,我认为您的if
不应该用于字符串比较,而应该是字符比较,条件应该如下面的代码中所示。此外,我还重写了代码,以便在java中进行实际的子字符串比较。 : - )
import java.io.*;
import java.util.*;
public class Readin {
public static void main(String[] args) {
String specChar = "DISD";
String gen = "MLRVFILYAENVHTPDTDISDAYCSAVFAGVKKRTKVIKNSVNP";
for (int i = 0; i < gen.length() - 3; i++) {
char char1 = gen.charAt(i);
char char2 = gen.charAt(i + 1);
char char3 = gen.charAt(i + 2);
char char4 = gen.charAt(i + 3);
String concatChar = new StringBuilder().append(char1).append(char2).append(char3).append(char4).toString();
System.out.println(concatChar);
//if (specChar == concatChar) {
//compare each character from 1st to 4th
if (char1 == specChar.charAt(0) && char2 == specChar.charAt(1) && char3 == specChar.charAt(2) && char4 == specChar.charAt(3)) {
System.out.println(specChar);
break;
} else {
System.out.println("Error");
}
}
}
}
现在看下面修改过的一个: -
public class Readin {
public static void main(String[] args) {
String specChar = "DISD";
String gen = "MLRVFILYAENVHTPDTDISDAYCSAVFAGVKKRTKVIKNSVNP";
if (gen.contains(specChar)) {
System.out.println(specChar);
} else {
System.out.println("Error");
}
}
}