执行子字符串时字符串索引超出范围
String index out of range while doing substring
我正在尝试创建一个程序来计算 java 中整数的 3 位数字之间的乘积。一切正常,直到我输入一个少于 3 位数的数字,然后 eclipse 抛出这个错误:
Enter a number between 100 and 999
99
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.substring(Unknown Source)
at Ex8.main(Ex8.java:23)
我已经搜索了替代解决方案,所以我知道如何重写我的程序以便它可以 运行 和工作,但我的问题是为什么我的程序不只是说 "number is not valid"而不是忽略我的 if 语句?这是我的代码图片,在此先感谢您的回答。
import java.util.Scanner;
public class Ex8 {
public static void main(String[] args) {
int number, firstDigit, secondDigit, thirdDigit, product;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number between 100 and 999");
number = scan.nextInt();
scan.close();
if (number <= 99 && number> 999){
System.out.println("number is not valid");
}
else{
firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));
secondDigit = Integer.parseInt(Integer.toString(number).substring(1, 2));
thirdDigit = Integer.parseInt(Integer.toString(number).substring(2, 3));
product = firstDigit*secondDigit*thirdDigit;
System.out.println(product);
};
}
}
你用&&写了你的if语句
number <= 99 && number > 999
什么时候你应该真正使用 ||
number <= 99 || number > 999
这将修复代码。
它在这行失败 99 没有三位数。根据您的代码,它涉及其他部分。你必须使用 ||而不是 if 语句中的 &&。
thirdDigit = Integer.parseInt(Integer.toString(number).substring(2, 3));
我正在尝试创建一个程序来计算 java 中整数的 3 位数字之间的乘积。一切正常,直到我输入一个少于 3 位数的数字,然后 eclipse 抛出这个错误:
Enter a number between 100 and 999
99
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.substring(Unknown Source)
at Ex8.main(Ex8.java:23)
我已经搜索了替代解决方案,所以我知道如何重写我的程序以便它可以 运行 和工作,但我的问题是为什么我的程序不只是说 "number is not valid"而不是忽略我的 if 语句?这是我的代码图片,在此先感谢您的回答。
import java.util.Scanner;
public class Ex8 {
public static void main(String[] args) {
int number, firstDigit, secondDigit, thirdDigit, product;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number between 100 and 999");
number = scan.nextInt();
scan.close();
if (number <= 99 && number> 999){
System.out.println("number is not valid");
}
else{
firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));
secondDigit = Integer.parseInt(Integer.toString(number).substring(1, 2));
thirdDigit = Integer.parseInt(Integer.toString(number).substring(2, 3));
product = firstDigit*secondDigit*thirdDigit;
System.out.println(product);
};
}
}
你用&&写了你的if语句
number <= 99 && number > 999
什么时候你应该真正使用 ||
number <= 99 || number > 999
这将修复代码。
它在这行失败 99 没有三位数。根据您的代码,它涉及其他部分。你必须使用 ||而不是 if 语句中的 &&。
thirdDigit = Integer.parseInt(Integer.toString(number).substring(2, 3));