Java 验证用户输入的信件
我这里有我的代码,我试图检查用户是否输入Y或N以获得switch语句,但是即使我写Y或N,它也会给我错误消息,我做错了什么?提前谢谢Java 验证用户输入的信件,java,string,validation,Java,String,Validation,我这里有我的代码,我试图检查用户是否输入Y或N以获得switch语句,但是即使我写Y或N,它也会给我错误消息,我做错了什么?提前谢谢 public void anotherAction() throws IOException{ System.out.println(); System.out.println("Would you like to perform an additional action? 'Y' or 'N'"); while(!reader.hasNe
public void anotherAction() throws IOException{
System.out.println();
System.out.println("Would you like to perform an additional action? 'Y' or 'N'");
while(!reader.hasNextLine()){
System.out.println("Enter either 'Y' or 'N'");
}
String response =reader.nextLine().toUpperCase();
while(response != "Y" || response != "N"){
System.out.println("Enter 'Y' or 'N'");
response = reader.nextLine();
continue;
}
switch(response){
case "Y":
cc.getCommand(this.makeOption());
break;
case "N":
System.out.println("Exiting System...");
break;
}
}
您应该使用
equals()
来比较字符串。上述答案是正确的,但您可能希望尽量减少使用主要函数进行字符串比较的次数(这很快就会变得难以维护,并且您有一个将用户输入封装为bool的绝佳机会)
从长远来看,这样的事情可能会对你有所帮助
public void anotherAction() throws IOException
{
System.out.println();
System.out.println("Would you like to perform an additional action? 'Y' or 'N'");
if (getAction())
{
cc.getCommand(this.makeOption());
}
else {
System.out.println("Exiting System...");
}
}
private bool getAction()
{
while(true)
{
System.out.println("Enter either 'Y' or 'N'");
String response =reader.nextLine().toUpperCase();
if (response.equals("Y")) {
return true;
}
else if (response.Equals("N")) {
return false;
}
else {
System.out.println("Wrong input, please try again...");
}
}
}
响应!=“Y”| |响应!=“N”
-错了。怎么办??我要移除它吗?还是我写的不一样?String response=reader.nextLine()
while(!response.equalsIgnoreCase(“Y”)| |!response.equalsIgnoreCase(“N”){…}
你会发现控制台类也更容易使用。我可能只是切换到控制台,因为它不工作,我按照Lion告诉我的做了更改,它也会这样做,还有什么不合适的地方吗?我想通过查看您的代码,我已经把它弄得很复杂了,但是在使用IF语句验证输入时,我没有很好的经验