java - 验证方法中的输入
问题描述
我是java新手,目前正在尝试学习它!
我对方法有疑问,下面是我的代码示例。
import java.util.*;
public class test
{
public static void main(String[] args)
{
char key;
Scanner info = new Scanner(System.in);
System.out.print("Enter Keyword: ");
key = info.next().charAt(0);
while(key!='W'&&key!='w'&&key!='M'&&key!='m')
{
System.out.println("Invalid Keyword");
System.out.print("Enter Keyword");
key = info.next().charAt(0);
}
System.out.print("Valid key");
}
public static char validKey(char key)
{
///i want the while validation to go here instead of in the main
}
}
- 正如我在代码中所写,有没有办法在 validKey 方法中而不是在 main 方法中验证密钥?
- 有没有办法让我不必在while条件中指定'w'和'W'?
对不起,如果我不能很好地解释它,提前谢谢!
解决方案
- 如果要检查是否
key
正确,可以执行以下操作:
import java.util.*;
public class test
{
public static void main(String[] args)
{
char key;
Scanner info = new Scanner(System.in);
System.out.print("Enter Keyword: ");
key = info.next().charAt(0);
while(!validKey(key))
{
System.out.println("Invalid Keyword");
System.out.print("Enter Keyword");
key = info.next().charAt(0);
}
System.out.print("Valid key");
}
public static boolean validKey(char key)
{
if(Character.toLowerCase(key)!='w' && Character.toLowerCase(key)!='m') {
return true;
} else {
return false;
}
}
}
- 这取决于。如果案例大小不重要,您可以尝试以下操作:
while(Character.toLowerCase(key)!='w' && Character.toLowerCase(key)!='m')
{
...
}
如果我的回答对您有帮助,请回信;)
推荐阅读
- html - 如何在下拉内容中删除悬停边框?
- node.js - 如何解决 promiss.all() 并希望删除一个级别的对象
- node.js - 将 PM2 与 docker 一起使用
- javascript - JQuery 可拖动内容 - 显示选中
- java - PowerMock expectNew 不会返回模拟实例
- python - Python 模块应该如何使用代码生成?
- javascript - 如何使用JavaScript单击删除和添加css动画属性
- python-3.x - 如何在文件中找到前五个结果的总和
- php - 使用 TCPDF 将多个具有透明度的图像分层
- python - 从子包运行 Python 测试