简体   繁体   中英

How to check if the System.in contains only numbers

Have a task to get N numbers from console, find the longest and the shortest ones and their length. The task is not difficult and works correctly, but I decided to make a check, if the console input corresponds the conditions of the task:

  • Are there only Integer numbers.
  • Are the exactly N numbers, not more/less.

I decided to write a boolean method isInputCorrect(), which would take the Scanner and check if the input is correct, but it doesn't work correctly.

public static void main(String[] args) {
        int n = 5;
        Scanner sc = new Scanner(System.in);
        do {
            System.out.println("Hello, please enter " + n + " integer numbers:");
            while (!isInputCorrect(sc,n)){
                System.out.println("Wrong! Try again:");
                sc.next();
            }
        } while (!isInputCorrect(sc, 5));
        String scLine = sc.nextLine();
        String[] arr = scLine.split("\\s+");
        String maxLengthNum = arr[0];
        String minLengthNum = arr[0];
        for (int i = 1; i < arr.length; i++){
            if (maxLengthNum.length() < arr[i].length()){
                maxLengthNum = arr[i];
            }
            if (minLengthNum.length() > arr[i].length()){
                minLengthNum = arr[i];
            }
        }
        String equalMaxNum = "";
        String equalMinNum = "";
        int countMax = 0;
        int countMin = 0;
        for (String s : arr){
            if (maxLengthNum.length() == s.length()){
                countMax += 1;
                equalMaxNum += s + " ";
            }
            if (minLengthNum.length() == s.length()){
                countMin += 1;
                equalMinNum += s + " ";
            }
        }
        if (countMax > 1){
            System.out.println("The longest numbers are: " + equalMaxNum + " Their length is: " + maxLengthNum.length());
        }
        else {
            System.out.println("The longest number is: " + maxLengthNum + " Its length is: " + maxLengthNum.length());
        }
        if (countMin > 1){
            System.out.println("The shortest numbers are: " + equalMinNum + " Their length is: " + minLengthNum.length());
        }
        else {
            System.out.println("The shortest number is: " + minLengthNum + " Its length is: " + minLengthNum.length());
        }
    }
    public static boolean isInputCorrect(Scanner sc, int n){
        boolean flag = true;
        for (int i = 0; i < n; i++){
            if (sc.hasNextInt()){
                sc.next();
            }else {
                flag = false;
                break;
            }
        }
        return flag;
    }

EDIT This code still doesn't work. I realize, that the problem is in isDigit(). And exactly in regular conditions in last if statement. It is something like this:

public static boolean isDigit (String input, int n){
    String[] arr = input.split("\\s+");
    boolean flag = false;
    if (arr.length != n){
        flag = false;
    }
    else {
        for (String s : arr) {
            if (s.startsWith("-")) {
                if (s.substring(1).matches("[0-9]*")) {
                    flag = true;
                }
            } else if (s.matches("[0-9]*")) {
                flag = true;
            } else {
                flag = false;
            }
        }
    }
    return flag;
}

This method takes the console input as a string, then it checks, how many numbers(strings) does it contain, are there any negative numbers and so on. But it can be applied only for substrings(words without whitespace). In my case it can be applied to arr[i].

So I modified it to split String into array[] and tried to check every single element. I've got:

public static boolean isDigit (String input, int n){
    String[] arr = input.split("\\s+");
    boolean flag = false;
    if (arr.length != n){
        flag = false;
    }
    else {
        for (String s : arr) {
            if (s.startsWith("-")) {
                if (s.substring(1).matches("[0-9]*")) {
                    flag = true;
                }
            } else if (s.matches("[0-9]*")) {
                flag = true;
            } else {
                flag = false;
            }
        }
    }
    return flag;
}

but it returnes true even when input is: 1 3213 w 15 3 I can't understand, what is the problem? The full code is:

public static void main(String[] args) {
            int n = 5;
            boolean validInput = false;
            String input;
            do {
                System.out.println("Please enter " + n + " integer numbers:");
                Scanner sc = new Scanner(System.in);
                input = sc.nextLine();
                if (isDigit(input, n)) {
                    validInput = true;
                } else {
                    System.out.println("Wrong input! Try again: ");
                }
            }
            while (!validInput);
    
            String[] arr = input.split("\\s+");
    
            String maxLengthNum = arr[0];
            String minLengthNum = arr[0];
            for (int i = 1; i < arr.length; i++){
                if (maxLengthNum.length() < arr[i].length()){
                    maxLengthNum = arr[i];
                }
                if (minLengthNum.length() > arr[i].length()){
                    minLengthNum = arr[i];
                }
            }
    
            String equalMaxNum = "";
            String equalMinNum = "";
    
            int countMax = 0;
            int countMin = 0;
    
            for (String s : arr){
                if (maxLengthNum.length() == s.length()){
                    countMax += 1;
                    equalMaxNum += s + " ";
                }
                if (minLengthNum.length() == s.length()){
                    countMin += 1;
                    equalMinNum += s + " ";
                }
            }
            if (countMax > 1){
                System.out.println("The longest numbers are: " + equalMaxNum + " Their length is: " + maxLengthNum.length());
            }
            else {
                System.out.println("The longest number is: " + maxLengthNum + " Its length is: " + maxLengthNum.length());
            }
            if (countMin > 1){
                System.out.println("The shortest numbers are: " + equalMinNum + " Their length is: " + minLengthNum.length());
            }
            else {
                System.out.println("The shortest number is: " + minLengthNum + " Its length is: " + minLengthNum.length());
            }
        }
    
        public static boolean isDigit (String input, int n){
        String[] arr = input.split("\\s+");
        boolean flag = false;
        if (arr.length != n){
            flag = false;
        }
        else {
            for (String s : arr) {
                if (s.startsWith("-")) {
                    if (s.substring(1).matches("[0-9]*")) {
                        flag = true;
                    }
                } else if (s.matches("[0-9]*")) {
                    flag = true;
                } else {
                    flag = false;
                }
            }
        }
        return flag;
    }

SOLVED

Thanks to everybody, your help was really usefull. I finally found the problem It was in isDigit() method. It was checking out every element of array, and switched a flag according to the last result. I wrote "break" to stop the further checking if there was at least one false flag in loop.

public static boolean isDigit (String input, int n){
        String[] arr = input.split("\\s+");
        boolean flag = false;
        if (arr.length != n){
            flag = false;
        }
        else{
            for (String s: arr){
                if (s.startsWith("-")) {
                    if (s.substring(1).matches("[0-9]*")){
                        flag = true;
                    }
                    else {
                        flag = false;
                        break;
                    }
                }
                else {
                    if (s.matches("[0-9]*")){
                        flag = true;
                    }
                    else {
                        flag = false;
                        break;
                    }
                }
            }
        }
        return flag;
    }

You may use regular expressions to verify that the input contains only integer numbers:

int n = 5;
// ... your current code

String scLine = sc.nextLine();
if (!scLine.matches("\\d+(?:\\s+\\d+)*")) {
    throw new IllegalArgumentException("input contained non-integers");
}

String[] arr = scLine.split("\\s+");
if (arr.length != n) {
    throw new IllegalArgumentException("found " + arr.length + " number inputs but expected " + n + ".");
}

you can check if input string has only numbers as below

public  boolean isDigit(String input) {

        if (input == null || input.length() < 0)
            return false;
        input = input.trim();
        if ("".equals(input))
            return false;
        if (input.startsWith("-")) {
            return input.substring(1).matches("[0-9]*");
        } else {
            return input.matches("[0-9]*");
        }
    }

EDIT:

allowing user to re-enter untill valid number is entered

boolean validInput = false;
do
{
  System.out.println("Enter the number ");
   // get user input
   String input  sc.nextLine();
  if(isDigit(input))
    validInput  = true;
  else
    System.out.println("Enter valid Number");
}
while (!validInput );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM