这段代码对我来说似乎完全没问题(CS101),但我的IDE会抛出错误"此方法必须返回boolean类型的结果"
我不想要任何有关如何简化我的代码的提示,或者只是想要解决原因的原因/解决方案
public static boolean validation(String correct1, String correct2)
{
Scanner in = new Scanner(System.in);
boolean correctInput = false;
String userInput;
while (correctInput == false)
{
System.out.print("Type in " + correct1 + " or " + correct2);
userInput = in.next();
if ( userInput.equals(correct1) )
{
return true;
}else if ( userInput.equals(correct2) )
{
return false;
}else
{
System.out.println("Try again!");
}
}
}
问题现已解决,任何人都有兴趣为什么我需要以下完整代码:
import java.util.*;
public class CheckingInput
{
public static void main(String args[])
{
System.out.println("What is 1+1?");
boolean answer = validation("two", "three");
if(answer == true)
{
System.out.print("Correct!");
}else if(answer == false)
{
System.out.print("Wrong!");
}
}
public static boolean validation(String correct1, String correct2)
{
Scanner in = new Scanner(System.in);
boolean correctInput = false;
String userInput;
while (correctInput == false)
{
System.out.print("Type in " + correct1 + " or " + correct2 + ": ");
userInput = in.next();
if ( userInput.equals(correct1) )
{
correctInput = true;
return true;
}else if (userInput.equals(correct2))
{
correctInput = true;
return false;
}else
{
System.out.println("Try again!");
correctInput = false;
}
}
return false;// Doesn't really matter, loop will never reach here
}
答案 0 :(得分:1)
我假设无限循环是故意的,因为您正在等待用户的回复,请尝试以下操作:
public static boolean validation(String correct1, String correct2)
{
Scanner in = new Scanner(System.in);
String userInput;
while (true)
{
System.out.print("Type in " + correct1 + " or " + correct2);
userInput = in.next();
if ( userInput.equals(correct1) )
{
return true;
}
else if ( userInput.equals(correct2) )
{
return false;
}
else
{
System.out.println("Try again!");
}
}
return false; // Doesn't really matter, loop will never reach here
}
答案 1 :(得分:0)
在循环退出的情况下,函数结束前缺少return true;
或return false
语句。