如何检查整数字符串



我应该编写一个程序,该程序接受表示整数的字符串作为输入,如果每个字符都是数字0-9,则输出yes。

我已经翻阅了我的章节,浏览了谷歌,但我仍然遇到了麻烦。我知道我的代码一团糟,但我迷路了。我可能有一些零碎的正确或错误,但这就是我所拥有的。

import java.util.Scanner; 
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userString;
// Add more variables as needed
userString = scnr.next();
boolean check1 = Character.isDigit(userString);

while (check1 = True) {
System.out.println ("Yes");
}
System.out.println ("No");

我哪里错了?

您可以使用正则表达式:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
// your input, can also be from a scanner
String input = "1234567890";
// regex pattern to match a string that consists only of numbers and is also not empty
String regex = "^[0-9]+$";
// to match negative numbers as well: "^[\-]?[0-9]+$"
// create a pattern object
Pattern pattern = Pattern.compile(regex);
// create a matcher object
Matcher matcher = pattern.matcher(input);
// check if the input matches
if (matcher.find()) {
System.out.println("It's a number, yay!");
};

正则表达式是如何工作的:

  • ^匹配输入的开头,以确保数字字符之前没有任何内容
  • [0-9]+告诉它匹配范围0-9一次或多次(+(,这也确保空字符串不匹配
  • $匹配字符串的末尾,以确保匹配后没有非数字

如果您也想匹配负数,正则表达式中还有一个额外的部分:[\-]?如果有,则匹配一个减号;如果没有,则不匹配(?(

https://www.tutorialspoint.com/java/java_regular_expressions.htm

也有可能是你尝试的方式:

// open a scanner
Scanner scanner = new Scanner(System.in);
// read user input from the scanner
String input = scanner.next();
// assume it is a number until we find a non-digit character below
String isNumber = true;
// loop over each character of the user input
for (char character : input) {
// check if the character is not a digit
if (!Character.isDigit(character)) {
System.out.println("NOT a number: ", character);
// set the is number variable to false
isNumber = false;
// break the loop, because it cannot be a number because we already found a non-digit
break;
};
};
System.out.println("Is it a number? ", isNumber);
正如人们在评论中指出的那样,您的代码中存在一些错误。Character.isDigit无法使用String。您需要使用的是Integer.parseInt(...)。你可以把它放在一个试接球区;如果解析成功则打印"是",如果抛出异常则打印"否":
userString = scnr.next();
try {
int parsedValue = Integer.parseInt(userString);
// Do something with parsedValue
System.out.println("Yes");
} catch (NumberFormatException numberFormatException) {
System.out.println("No");
}

相关内容

  • 没有找到相关文章

最新更新