I'm making a simple mortgage calculator and trying to validate two things through two "if-statements" before moving on to the next method. The first thing I'm checking is if the input from the scanner is an integer. If it is, I then want to check if the integer is between 1,000 and 1,000,000.
Below is the specific code:
public static Integer checkPrincipalValidation(Scanner scanner) {
while (true) {
if (scanner.hasNextInt()) {
principal = parseInt(scanner.nextLine());
if (principal >= 1_000 && principal <= 1_000_000) {
break;
}
System.out.println(scanner.nextLine() + " is not between 1,000 and 1,000,000. Please enter correct Principal (1K - $1M):");
}
if (!scanner.hasNextInt()) {
System.out.println(scanner.nextLine() + " is not a valid integer. Please enter correct Principal (Integer):");
}
}
return principal;
}
Below is the whole file if interested:
import java.util.Scanner;
import static java.lang.Float.parseFloat;
import static java.lang.Integer.parseInt;
public class Validation {
static int principal;
public static Integer checkPrincipalValidation(Scanner scanner) {
while (true) {
if (scanner.hasNextInt()) {
principal = parseInt(scanner.nextLine());
if (principal >= 1_000 && principal <= 1_000_000) {
break;
}
System.out.println(scanner.nextLine() + " is not between 1,000 and 1,000,000. Please enter correct Principal (1K - $1M):");
}
if (!scanner.hasNextInt()) {
System.out.println(scanner.nextLine() + " is not a valid integer. Please enter correct Principal (Integer):");
}
}
return principal;
}
public static Float checkInterestValidation(Scanner scanner) {
while (true) {
if (scanner.hasNextFloat() || scanner.hasNextInt()) {
if (scanner.hasNextInt()) {
return parseFloat(scanner.nextLine());
}
return scanner.nextFloat();
} else {
System.out.println(scanner.nextLine() + " is not a valid rate");
System.out.print("Please enter correct Rate: ");
}
}
}
public static Integer checkPeriodValidation(Scanner scanner) {
while (true) {
if (scanner.hasNextInt()) {
return scanner.nextInt();
} else {
System.out.println(scanner.nextLine() + " is not a valid period");
System.out.print("Please enter correct Period (Years): ");
}
}
}
}
When it passes through the first "if-statement", I have to enter the number twice before it goes into the second "if-statement". Why? Thank you for your time. I took a year off of coding so I'm extremely rusty and still extremely new to java, haha!