gpt4 book ai didi

java - 正确的代码无法编译?

转载 作者:行者123 更新时间:2023-12-01 13:48:11 26 4
gpt4 key购买 nike

这段代码对我来说似乎完全没问题(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
}

最佳答案

我假设无限循环是故意的,因为您正在等待用户的响应,因此请尝试以下操作:

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
}

关于java - 正确的代码无法编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20182955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com