0

Hi I am trying to take in an integer between 1 and 10. If the user does not do so would like the program to run again. I believe that I need to use an else if statement that calls on my function but I do not know how to call functions in java.

Here is my code so far:

import java.util.Scanner;
public class NumChecker {
     public static void main(String[] args){

         Scanner in = new Scanner(System.in);
         System.out.print("Enter a number between 1 and 10: ");
         int num1 = in.nextInt();
         if (num1 >= 1 && num1 <= 10); {
             System.out.println("Input = " + num1);
             }

         else if {
         ???
         }


     }

}
CFC
  • 33
  • 7

2 Answers2

2

if-else always work.

You made a mistake in the if statement.

there is no ; for an if

if (num1 >= 1 && num1 <= 10) {//no semicolon
   System.out.println("Input = " + num1);
}
else if(num < 0) {//should have a condition
...
}
else
{
... 
}  

What happens if I put a semicolon at the end of an if statement?.


How do I ask the user again if the input is not in between 1 and 10?

Loop until you get what you want :)

Scanner sc = new Scanner(System.in);
int num = 0;
while(true)
{
 num = sc.nextInt();
 if(num > 0 && num < 11)
  break;
 System.out.println("Enter a number between 1 and 10");
}
System.out.println(num);
Community
  • 1
  • 1
Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
1

Since you are expecting a number between 1 to 10, but you don't know how many numbers you will get until you get a valid number, I'd suggest to use a while loop, like so:

import java.util.Scanner;
public class NumChecker {
    public static void main(String[] args){

        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number between 1 and 10: ");
        int num1 = in.nextInt();
        while (num1 < 1 || num1 > 10) {
            System.out.print("Invalid number, enter another one: ");
            num1 = in.nextInt();
        }
        System.out.println("Input = " + num1);
     }
}
noodlez040
  • 236
  • 2
  • 10