我必须编写一个解决农民,玉米,鹅和狐狸问题的程序。虽然我知道如何在脑海中解决这个问题但我知道问题的规则(就像鹅不能留在狐狸身上或者它会被吃掉)我对如何在代码中表示规则感到困惑。
答案 0 :(得分:1)
通常情况下,我不会提供一个措辞不好的问题的解决方案,但如果我理解正确的话,我发现它是一个有趣的问题。请确保下次还提供一些源代码,以便我们看到您尝试过的内容。(查看https://stackoverflow.com/help/how-to-ask,了解如何提出一个好问题)
public static void main(String[] args)
{
//scanner object for user input
Scanner input=new Scanner(System.in);
//define objects
//Use true and false to determine the side
boolean farmer=false;
boolean fox=false;
boolean goose=false;
boolean corn=false;
//Show rules
System.out.println("Welcome to the Farmer, Goose, Fox, Corn Problem.");
System.out.println("The Fox and Goose cannot be left alone.");
System.out.println("The Goose and Corn cannot be left alone.");
System.out.println("You may only bring one object across the river at a time.");
//loop flag
boolean isFinished=false;
while(!isFinished)
{
//show objects on the same side as the farmer
System.out.println("\nThe objects on your side of the river are:");
if(farmer==fox)
{
System.out.println("1.Fox ");
}
if(farmer==goose)
{
System.out.println("2.Goose ");
}
if(farmer==corn)
{
System.out.println("3.Corn ");
}
System.out.println("4.Nothing ");
//get user selection and validate
//just makes sure that the object is on the same side as the farmer
//if true move the object then test if valid after switch
boolean isValidInput=false;
int userSelection;
do
{
System.out.print("\nEnter the number for the object you wish to move:");
userSelection=input.nextInt();
if(userSelection==1)
{
if(fox==farmer)
{
farmer=!farmer;
fox=!fox;
isValidInput=true;
}
}
else if(userSelection==2)
{
if(goose==farmer)
{
farmer=!farmer;
goose=!goose;
isValidInput=true;
}
}
else if(userSelection==3)
{
if(corn==farmer)
{
farmer=!farmer;
corn=!corn;
isValidInput=true;
}
}
else if(userSelection==4)
{
farmer=!farmer;
isValidInput=true;
}
else
{
isValidInput=false;
}
}while(!isValidInput);
//check solution
boolean isValid=false;
if((fox==goose && farmer!=fox))
{
System.out.println("\nFox and goose cannot stay together.");
}
else if(goose==corn && farmer!=goose)
{
System.out.println("\nGoose and corn cannot stay together.");
}
else
{
isValid=true;
}
//if the solution is not valid switch objects back and request user input again
if(!isValid)
{
if(userSelection==1)
{
if(fox==farmer)
{
farmer=!farmer;
fox=!fox;
isValidInput=true;
}
}
else if(userSelection==2)
{
if(goose==farmer)
{
farmer=!farmer;
goose=!goose;
isValidInput=true;
}
}
else if(userSelection==3)
{
if(corn==farmer)
{
farmer=!farmer;
corn=!corn;
isValidInput=true;
}
}
else if(userSelection==4)
{
farmer=!farmer;
isValidInput=true;
}
else
{
isValidInput=false;
}
}
//check if final solution achieved
if(fox && goose && corn && farmer)
{
System.out.println("\nYou Win, Good Job!!!");
isFinished=true;
}
}//end while
} //end main