Sorry guys, first time poster here, so please let me know if there's some etiquette or anything I should be following!
I've seen a few of these on the forums, and I've scoured through them, trying to make one work, but I can't seem to do it.
I need to create a program that asks for the user to input two positive integers. Each time an integer is answered, I want to validate to make sure it is 1) a number and 2) also positive. If it is not, I am supposed to just terminate the program. So far, I've tried:
import java.util.Scanner;
public class Assignment4 {
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Please enter two positive integers.");
System.out.println("Please enter the first integer:");
int num1 = in.nextInt();
do {
System.out.println("Invalid. ***End of Program***");
System.exit(0);
while (!in.hasNextInt()) {
System.out.println("Invalid. ***End of Program***");
System.exit(0);
}
}while (num1 <= 0);
}
}
}
which works for when I enter a negative number, but for some reason, java just receives the invalid error input and doesn't run when I type in a letter. I also tried:
import java.util.Scanner;
public class Assignment4 {
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Please enter two positive integers.");
System.out.println("Please enter the first integer:");
int num1 = in.nextInt()
if (!in.hasNextInt()){
System.out.println("Invalid integer. ***End of Program***");
System.exit(0);
}else if (num1 <= 0){
System.out.println("Invalid negative number. ***End of Program***");
System.exit(0);
}
}
}
which just doesn't do anything. I've been at this problem for about 2 hours yesterday and another hour today, looking online for other solutions. I cannot use any match or try/catch statements, as I have not learned them yet! Any insight would be great, as I'm going crazy here.