输入只能是字符串 [英] Input can only be string

查看:65
本文介绍了输入只能是字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个JOptionpane,用户可以在其中输入他的名字.所以它不能为空,也不能为数字

I'm making a JOptionpane where the user can has to enter hes name. So it can't be empty and it can't be a number

空白部分正在工作,但现在我必须找到数字部分的解决方案

The empty part is working but now I have to find a solution for the number part

正如您在我的代码中看到的那样,我做了一个while循环来检查"naam"是否不为空.现在,我需要找到一种方法来检查"naam"是否不是数字.

As you can see in my code I made a while loop to check if "naam" isn't empty. Now I need to find a way to check if "naam" isn't a number.

String naam = JOptionPane.showInputDialog("Geef uw naam in: ");

while (naam.equals("")) {
   JOptionPane.showMessageDialog(null, "Geef een naam in", "Geef naam", JOptionPane.ERROR_MESSAGE);
   naam = JOptionPane.showInputDialog("Geef uw naam in: ");

推荐答案

您可以使用正则表达式检查它是否包含任何数字.Java中的正则表达式"\\ D"代表非数字,"+"代表1或更大.因此,您可以将while循环更改为:

You can use regex to check if it contains any digits. The regex "\\D" in java stands for a non-digit, and "+" stands for 1 or more. So you can change your while loop to:

while (!naam.matches("\\D+"))

这将包括空等于检查,因为您需要至少有一个非数字来匹配它.

This will include the empty equals check, as you need to have at least one non-digit for it to match.

这篇关于输入只能是字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆