.JAVA.验证第二个索引是否小于第一个索引?



在我的代码中,我希望用户输入 3 个输入,以根据第 2 个输入提取子字符串,该输入将是 int 变量。我已经涵盖了大部分验证,但是如果用户输入的第二个索引少于第一个索引,则会返回有关如何解决此问题的任何错误?

System.out.println("Enter the 2nd index of the word : ");
endIndex = scanner.nextInt();
while (endIndex > inputString.length()) {
System.out.println("Index is not in string length, try again.");
System.out.println("Enter the second index of the substring : ");
endIndex = scanner.nextInt();
} 
char[] ch = new char[endIndex - startIndex + 1];
inputString.getChars(startIndex, endIndex + 1, ch, 0);
System.out.println("Output : " + String.valueOf(ch));

while中也检查该条件

while (endIndex > inputString.length() || endIndex < startIndex + 1) {

具有讽刺意味的是,当您显然缺少对这两个整数的验证时,您如何确保验证代码......

无论如何,您需要在获取时验证 startIndex。您有两种选择:

  • 当你获取endIndex时,你检查它是否小于startIndex

    while (endIndex > inputString.length() || endIndex < startIndex + 1)

  • getChars之前,请检查这两个值,如果startIndex>endIndex,则交换它们。

也:

  • 您没有验证它们是否为负数。
  • 您正在使用while,因为它是do - while

相关内容

最新更新