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



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

我的代码要求:

  • while循环,即while(true(
  • isDigit((

我从这段代码开始,但我不知道如何实现isDigit方法。我认为它必须嵌套在while循环中。

while(input < 1 || input > 20){
System.out.println("Invalid number! Try again.");
input = s.nextInt();
s.nextLine();
}
return input;
}

我尝试过使用";如果";语句并使用另一个";而";循环,但不起作用。非常感谢。

您的while条件不正确,while(input < 1 || input > 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
}

这里的isDigit方法使用正则表达式[0-9]来检查字符是否在0到9的范围内,您可以在这里检查更多正则表达式https://www.w3schools.com/java/java_regex.asp


//check if input is valid number
public static 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]*");
}
}

我已经扩展了您的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);
}
}

输出:

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

我对使用两个静态函数

  1. 查找输入的数字是否为整数[isInteger],然后
  2. 强制用户输入一个介于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;
} 

相关内容

  • 没有找到相关文章

最新更新