我需要找到从用户输入派生的char值的位置。但是当我没有提供要查找的确切字符时,indexOf方法似乎不起作用。但由于char值是从用户的输入派生的,所以我无法输入确切的值。任何方式使用indexOf我需要的方式?
public class pg2a {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String host;
System.out
.println("Please enter your sequence (any length, any characters):");
host = keyboard.nextLine();
System.out.println("Now enter a 3 character sequence:");
String candidate;
candidate = keyboard.nextLine();
int length = candidate.length();
char a = candidate.charAt(0);
char b = candidate.charAt(1);
char c = candidate.charAt(2);
int i = candidate.indexOf(a);
int j = candidate.indexOf(b);
int k = candidate.indexOf(c);
if (length == 3) {
if (i == -1)
System.out
.println("The 3 character sequence you entered is not a subsequence of your sequence.");
else
System.out.println("Let's go!");
} else {
System.out
.println("The sequence you entered is not a 3 character sequence.");
}
}
}
`
答案 0 :(得分:1)
你拥有的代码应该将i设置为0,j为1,c为2(假设它们都是不同的字符)。你说“给我第一个字符的索引”,然后是第二个和第三个字符。我相信你打算做host.indexOf(a)
等等。
但是,有一种更简单的方法可以做你想做的事情,这只是使用host.indexOf(candidate)
,它应该返回> -1如果候选人在主持人。
答案 1 :(得分:0)
如果我正确理解你的问题:
int i = candidate.indexOf(a);
int j = candidate.indexOf(b);
int k = candidate.indexOf(c);
应该是
int i = host.indexOf(a);
int j = host.indexOf(b);
int k = host.indexOf(c);
你想知道a是否在主机中。 a永远是候选人。此外,您只检查a是否在序列中,而不是b和c
答案 2 :(得分:0)
如果您的目标只是检查host
是否包含candidate
,那么您可以考虑使用contains
方法。
boolean isSubstring = host.contains(candidate);
如果你需要一个candidate
开始的索引,那么下面应该服务于目的。
int startIndex = host.indexOf(candidate);