I am trying to create a program that calculates the product between the 3 digits of an integer in java. Everything works fine until I enter a number that has less than 3 digits, then eclipse throws this error:
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)
I've searched for alternate solutions, so I know how to rewrite my program so that it can run and work, but my question is why isn't my program just saying "number is not valid" instead of just ignoring my if statement? Here is my pice of code, and thank you in advance for answering.
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)there.firstDigit = number/100; thensecondDigit = (number%100)/10;andthirdDigit = (number%10);