【发布时间】:2018-09-26 00:43:06
【问题描述】:
我正在尝试检查两个不同的索引以查看它们是否匹配。在我的情况下,我正在检查索引 3 和 4。确定它们是否匹配没有问题,但是如果我的字符串太短并且在索引 3 或 4 处没有字符,我的程序就会出错。
这是我的代码的副本。谁能告诉我我做错了什么?
/**
* Checks the characters in a String at indices 3 and 4 to see if those characters match
* @param input String to check
* @return "MATCH" if String's indices 3 and 4 have the same letter, "NO MATCH" if String's
* indices 3 and 4 do not have the same letter, "N/A" if the String is too short to have a letter at index 3 or index 4
*/
private static String method4(String input) {
Scanner scan = new Scanner(System.in);
System.out.println("What is your word? ");
input = scan.nextLine();
int len = input.length();
if (len < 4) {
System.out.println("N/A");
}
else{
char char1 = input.charAt(3);
char char2 = input.charAt(4);
if ((char1) == (char2)) {
System.out.println("MATCH");
}}
else
System.out.println("NO MATCH");
【问题讨论】:
-
我建议进行编辑以将java 标签添加到您的问题中。另外,不要说“我的程序出错了”,而是尝试查找错误消息,检查它的内容,然后将其包含在您的帖子中,以便其他人了解问题所在。