如何将其放入工作代码中以验证用户输入(Java)?

如何将其放入工作代码中以验证用户输入(Java)?,java,eclipse,validation,while-loop,Java,Eclipse,Validation,While Loop,我是初学者程序员。我试图写一个代码,要求用户输入必须是数字1-20,并且不是字母 对我的代码的要求: while循环,即while(真) isDigit() 我从这段代码开始,但我不知道如何实现isDigit方法。我假设它必须嵌套在while循环中 while(input < 1 || input > 20){ System.out.println("Invalid number! Try again."); input

我是初学者程序员。我试图写一个代码,要求用户输入必须是数字1-20,并且不是字母

对我的代码的要求:

  • while循环,即while(真)
  • isDigit()
我从这段代码开始,但我不知道如何实现isDigit方法。我假设它必须嵌套在while循环中

    while(input < 1 || input > 20){
        System.out.println("Invalid number! Try again.");
        input = s.nextInt();
        s.nextLine();
    }
    return input;
}
while(输入<1 | |输入>20){
System.out.println(“无效数字!请重试。”);
输入=s.nextInt();
s、 nextLine();
}
返回输入;
}

我尝试过使用“if”语句和另一个“while”循环,但没有成功。非常感谢。

您的while条件不正确,
while(输入<1 | |输入>20)
正在检查数字是否小于1且大于20

这个问题有两个部分,1。检查输入是否为有效数字,2。检查数字是否在范围内

public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        boolean validInput = false;
        do
        {
            System.out.println("Enter valid number ");
            // get user input
            String input =  sc.nextLine();

            if(isDigit(input)) {
                int inputNumber = Integer.parseInt(input);
                //check if number is in the range of 1 to 20
                boolean isInRange = (inputNumber > 1) && (inputNumber < 20);
                validInput  = true;
                if(isInRange) {
                    System.out.println(input+" is valid Number and in the range of 1 to 20");
                }
                else {
                    System.out.println(input+" is valid Number But Not in the range of 1 to 20");
                }
            }
            else {
                System.out.println(input+" is invalid Number");
            }
        }
        while (!validInput ); // continues untill valid input is entered

    }

我已经扩展了
while()
,使用StringUtils提供的
isNumeric()
来检查输入是否为数值。此函数用于检查CharSequence是否仅包含Unicode数字,从而降低代码显式检查数值的复杂性

import java.io.*;
import java.util.*;

import static org.apache.commons.lang3.StringUtils.isNumeric;

public class Solution {
    public static void main(String[] args) throws IOException {

        int result = isDigit();
        System.out.println("Result is: " + result);
    }

    public static int isDigit() {
        // Create a Scanner object
        Scanner s = new Scanner(System.in);
        System.out.println("Enter number");
        // Accept input in String
        String input = s.next();

        /**
         * Check if input is numeric and between 1 and 20.
         * Otherwise, accept new input from user.
         */
        while (!isNumeric(String.valueOf(input))
            || Integer.parseInt(input) < 1 || Integer.parseInt(input) > 20) {
            System.out.println("Invalid number! Range should be between 1 and 20. Try     again.");
            input = s.next();
            s.nextLine();
        }

        // Return numeric value which is between 1 and 20
        return Integer.parseInt(input);
    }
}

我使用两个静态函数来

  • 查找输入的数字是否为整数[isInteger]和
  • 强制用户输入介于1和20之间的数字
  • 由于您是初学者,在检查用户输入的是数字时,我没有使用正则表达式

    Scanner scanner = new Scanner(System.in);
    
    public static void main(String[] args) {
        System.out.println("Enter an integer number between 1 and 20");
        String userInput = scanner.nextLine();
    
        int requiredInput = validateAndGetNumber(userInput);
    
        /*
          Now, do whatever you want to do with this requiredInput
        */
    }
    
    public static int validateAndGetNumber(String input) {
            
        if (isInteger(input)) {
            int num = Integer.parseInt(input);
    
            if (num >= 1 && num <= 20) 
                return num;
            else {
                System.out.println("Number is not in range 1-20. Please try again.");
                input = scanner.nextLine();
                return validateAndGetNumber(input);
            }
        }
            
        System.out.println("Input is not an integer number. Please try again.");
        input = scanner.nextLine();
        return validateAndGetNumber(input);
    }
    
    public static boolean isInteger(String str) {
        if (str == null) {
            return false;
        }
        int length = str.length();
        if (length == 0) {
            return false;
        }
        int i = 0;
        if (str.charAt(0) == '-') {
           System.out.println("Negative value is invalid for this property.");
           return false;
        }
    
        for (; i < length; i++) {
            char c = str.charAt(i);
    
            if ((c < '0' || c > '9') && c != '-') {
                return false;
            }
        }
        return true;
    } 
    
    Scanner Scanner=新的扫描仪(System.in);
    公共静态void main(字符串[]args){
    System.out.println(“输入一个介于1和20之间的整数”);
    字符串userInput=scanner.nextLine();
    int requiredInput=validateAndGetNumber(用户输入);
    /*
    现在,用这个必需的输入做任何你想做的事情
    */
    }
    公共静态int validateAndGetNumber(字符串输入){
    if(isInteger(输入)){
    int num=Integer.parseInt(输入);
    如果(num>=1&&num'9')&&c!='-'){
    返回false;
    }
    }
    返回true;
    } 
    
    鉴于原始海报是Java开发新手,最好解释一下此解决方案使用正则表达式:)@Gavin更新了答案以包含正则表达式的详细信息
    Enter number
    30
    Invalid number! Range should be between 1 and 20. Try again.
    -10
    Invalid number! Range should be between 1 and 20. Try again.
    abc
    Invalid number! Range should be between 1 and 20. Try again.
    10
    Result is: 10
    
    Scanner scanner = new Scanner(System.in);
    
    public static void main(String[] args) {
        System.out.println("Enter an integer number between 1 and 20");
        String userInput = scanner.nextLine();
    
        int requiredInput = validateAndGetNumber(userInput);
    
        /*
          Now, do whatever you want to do with this requiredInput
        */
    }
    
    public static int validateAndGetNumber(String input) {
            
        if (isInteger(input)) {
            int num = Integer.parseInt(input);
    
            if (num >= 1 && num <= 20) 
                return num;
            else {
                System.out.println("Number is not in range 1-20. Please try again.");
                input = scanner.nextLine();
                return validateAndGetNumber(input);
            }
        }
            
        System.out.println("Input is not an integer number. Please try again.");
        input = scanner.nextLine();
        return validateAndGetNumber(input);
    }
    
    public static boolean isInteger(String str) {
        if (str == null) {
            return false;
        }
        int length = str.length();
        if (length == 0) {
            return false;
        }
        int i = 0;
        if (str.charAt(0) == '-') {
           System.out.println("Negative value is invalid for this property.");
           return false;
        }
    
        for (; i < length; i++) {
            char c = str.charAt(i);
    
            if ((c < '0' || c > '9') && c != '-') {
                return false;
            }
        }
        return true;
    }