driver类、inputoutput类和numberValidator类。用户使用j选项窗格弹出框输入数字1-8,如果输入的不是1-8,则应该显示错误消息。如果数字是1-8,则其余代码(未在此处编写)将继续运行。我收到了错误,有人看到我哪里错了吗?
///Driver class (excludes package)////
public class Driver {
public static void main(String[] args) {
InputOutput inputoutput = new InputOutput();
inputoutput.displayMenu();
}
}
///InputOutput class (excludes package and import for JOptionPane)///
public class InputOutput {
public int displayMenu()
{
String stringChoice = JOptionPane.showInputDialog("Restaurant:\n"
+ "1. Pancakes: $10.00\n"
+ "2. Bananas: $1.00\n"
+ "3. Bread: $2.00\n");
if (numberValidator.isNumeric(stringChoice)){
choiceNumber = Integer.parseInt(stringChoice);
}
return choiceNumber;
}
///numberValidator class code (excludes package)///
public class numberValidator {
public boolean isNumeric(String str)
{
boolean valid = true;
String regex = "[1-8/.]*";
valid = str.matches(regex);
return valid;
}
}
发布于 2012-04-14 12:29:33
您得到的错误是什么?无论用户选择什么,它都会继续运行吗?在下面的代码中,我添加了一个else
,如果选择的值不是数字,它将重新运行displayMenu()
方法。
public class InputOutput {
public int displayMenu()
{
String stringChoice = JOptionPane.showInputDialog("Restaurant:\n"
+ "1. Pancakes: $10.00\n"
+ "2. Bananas: $1.00\n"
+ "3. Bread: $2.00\n");
if (numberValidator.isNumeric(stringChoice)){
choiceNumber = Integer.parseInt(stringChoice);
}
else {
return displayMenu();
}
return choiceNumber;
}
但是对于您的问题,使用选项的下拉列表不是更好吗?
String[] options = new String[]{"Pancakes: $10.00","Bananas: $1.00","Bread: $2.00"}
int chosenIndex = JOptionPane.showOptionDialog(null, "Choose a menu item", "Menu", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
String chosenValue = options[chosenIndex];
发布于 2012-04-14 12:19:42
可能你的意思是:String regex = "[1-8]\."
--即间隔1-8中的一个数字,后面跟着一个点?
发布于 2012-04-14 12:21:18
您可以将正则表达式简化为String regex = "[1-8]";
。
这意味着您的正则表达式只能接受从1到8的数字。
致以问候。
编辑:
对于您的错误:
您从未初始化过numberValidator
,因此编译器会看到您想要在没有numberValidator实例的情况下访问isNumeric方法,并看到medthod isNumeric没有关键字static。这就是为什么它会告诉你消息错误的原因。
在if语句中进行如下更改以更正您的问题:
if ( new numberValidator().isNumeric(stringChoice))
或者让你的方法成为静态的isNumeric()
。
顺便说一下:类名必须以大写字母开头。
https://stackoverflow.com/questions/10150928
复制相似问题