Kalash Babu Acharya
Kalash Babu Acharya

Reputation: 53

How to restrict the user to enter number between certain range in java?

In Java, if you want to ask users, for example, to input numbers only between 1,000 and 100,000, the program would continue further. Otherwise, ask the user to input the number again in the given range.

Edit: Here, my program only tries to validate the input only once. How shall I make to ask the user to input until valid data(i.e between 1000-100000) is entered

public static void main(String args[]) {

    Scanner sc = new Scanner(System.in);    
    System.out.print("Principal:");
    double principal = sc.nextDouble();

    if(principal<1000 || principal >100000) {
        System.out.println("enter principal again:");
        principal = sc.nextDouble();        
    }
}

Upvotes: 0

Views: 13167

Answers (2)

import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;

class Myclass {

    static boolean isInteger(double number){
        return Math.ceil(number) == Math.floor(number); 
    }
    public static void main(String args[]) {

        Scanner in = new Scanner(System.in);    
        double num;
        do{
            System.out.print("Enter a integer between 1000 and 100000 : ");
            num = in.nextDouble();
        }
        while((num < 1000 || num > 100000)||(!isInteger(num)));

        System.out.println("Validated input  : "+num);

    }
}

Hope this helps you

Upvotes: 0

Gunjan Mehta
Gunjan Mehta

Reputation: 66

You can use do-while loop here as below

public static void main(String []args){
    Scanner in = new Scanner(System.in);
    int result;
   do {
       System.out.println("Enter value bw 1-100");
       result = in.nextInt();
   } while(result < 0 || result > 100);

    System.out.println("correct "+ result);

}

Upvotes: 1

Related Questions