Select
我这样做是为了确保我的长度为14.但是我的程序还要求它只是数字。它也需要是一个字符串。我不想解析int,如果输入了一封信,我希望我的程序String roulette = keyboard.next();
if (roulette.length()!=14)
{
System.out.print("Error: 14 digits only");
System.exit(1);
}
。有没有办法做到这一点?
我在这里https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html和https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html,但无法找到我正在寻找的内容
答案 0 :(得分:3)
您可以使用简单的正则表达式检查:
if(roulette.matches("[0-9]{14}")) {
// has length 14 and only digits
} else {
// wrong format
}
这将检查长度和是否仅使用数字。
进一步阅读正则表达式:https://docs.oracle.com/javase/tutorial/essential/regex/
答案 1 :(得分:0)
您使用Java正则表达式:
String pattern1 = "\\d{14}";
Pattern p = Pattern.compile(pattern1);
Matcher m = p.matcher(roulette);
//exit if all 14 not integers, or any non-integer present
if(!m.find())
System.exit(1);
答案 2 :(得分:0)
使用正则表达式进行匹配,使用扫描仪进行输入。
public static void main(String[] args) {
String regex = "\\d+";
Scanner s=new Scanner(System.in);
while(s.hasNext())
{
String text=s.next();
if(text.matches(regex))
{
System.out.println("Input Strings only");
}
else
{
System.out.println(text);
//break;
}
}
答案 3 :(得分:0)
我将在此处添加此内容,以便通过使用Character.isDigit
来展示我的意思。我之所以建议,因为在使用Java的Clojure中,这很容易,因为它有一个every?
方法,可以检查集合中的所有内容是否满足谓词(在这种情况下为Character.isDigit
)。在Clojure中,这只是:
(every? #(Character/isDigit %) "1234")
很漂亮。
不幸的是,对于在Java中工作的类似方法,您需要将String转换为char数组,然后转换为ArrayList,然后转换为流,并在其上调用allMatch
。相反,这是一个使用循环的手动方式:
import java.util.*;
public class Main {
public static boolean areAllNums (String numStr) {
// Loop over each character...
for (char d : numStr.toCharArray()) {
//And if we find a non-digit, return false;
if (!Character.isDigit(d)) {
return false;
}
}
// If we made it here, all the chars were digits
return true;
}
public static void main(String[] args) {
System.out.println(Arrays.asList(
areAllNums("1234"), areAllNums("12g4")));
// Prints [true, false]
}
}
答案 4 :(得分:0)
我不久前在SO上找到了(惊讶没人提到):
public static boolean isValid(String str) {
try {
Double.parseDouble(str);
return str.length() == 14;
} catch(NumberFormatException e) {
return false;
}
}