Java 执行子字符串时字符串索引超出范围

Java 执行子字符串时字符串索引超出范围,java,if-statement,Java,If Statement,我试图创建一个程序,在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 Sourc

我试图创建一个程序,在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)
我一直在寻找替代解决方案,因此我知道如何重写程序,使其能够运行和工作,但我的问题是,为什么我的程序不只是说“数字无效”,而不是忽略我的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);
    };
}
}
import java.util.Scanner;
公共类Ex8{
公共静态void main(字符串[]args){
整数、第一位数、第二位数、第三位数、产品;
扫描仪扫描=新扫描仪(System.in);
System.out.println(“输入一个介于100和999之间的数字”);
number=scan.nextInt();
scan.close();
如有需要(电话号码999){
System.out.println(“编号无效”);
}
否则{
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));
产品=第一位数*第二位数*第三位数;
系统输出打印项次(产品);
};
}
}

您用&&

number <= 99 && number > 999
999号
当你真的应该使用||

number <= 99 || number > 999
999号

这将修复代码。

第99行的fail没有三位数字。根据您的代码,它将转到其他部分。在if语句中必须使用| |而不是&&in

        thirdDigit = Integer.parseInt(Integer.toString(number).substring(2, 3));

你应该有-
if(号码999)
在那里。是的,逻辑错误,就是这样。非常感谢。此外,您还可以使用整数数学,而不是将整数转换为字符串并返回,从而提高代码的效率。i、 e.
firstDigit=number/100
;然后
secondDigit=(数字%100)/10
thirdDigit=(数字%10)不是这样的。。。在IF语句中错误地使用了&&而不是| |,这就是问题所在。我知道,我的问题是它为什么会在不应该运行那段代码的情况下崩溃。不,它会到达那一行,因为根据这个IF(编号999){它说数字应该小于或等于99,如果两者都满足,数字应该大于999。在你的案例99中,如果语句不能同时满足这两个条件,则转到内部