我正试图让我的程序以我想要的方式工作。当我进入 switch 语句时,我想让用户输入一个值并转到相应的用户创建方法。在其中一个用户创建的方法中,我有一个随机布尔值返回给主方法。我希望我的程序仅在值为 true 并且仅针对我访问的一种方法而不是所有方法时才 println“key is here”。因为当我运行程序时,它会遍历 if 语句中的所有方法,而不仅仅是我想要的。有人可以帮帮我吗?我想让用户创建的方法返回 nextBoolean 并让 println“key is here”仍然在 main 方法中。有没有办法做到这一点?提前致谢。我是这方面的初学者:) 这是代码:
import java.util.*;
import java.util.Random;
public class JavaGameSearchHouse
{
public static Scanner console = new Scanner(System.in);
public static boolean keyValue;
public static Random keyVal = new Random();
public static void main(String[] args)
{
String roomValue;
int counter;
int keepGoing = 0;
do{
System.out.println("Lets search this house for the key");
roomValue = console.next();
switch(roomValue.toLowerCase())
{
case "kitchen": kitchenMethod();
break;
case "bedroom": bedroomMethod();
break;
case "familyRoom": familyRoomMethod();
break;
case "livingRoom": livingRoomMethod();
break;
case "bathroom": bathroomMethod();
break;
case "basement": basementMethod();
break;
default: System.exit(0);
}
if(kitchenMethod())
System.out.println("Key is here1");
if(bedroomMethod())
System.out.println("Key is here2");
if(familyRoomMethod())
System.out.println("Key is here3");
if(livingRoomMethod())
System.out.println("Key is here4");
if(bathroomMethod())
System.out.println("Key is here5");
if(basementMethod())
System.out.println("Key is here6");
System.out.println("press 1 to search again");
keepGoing = console.nextInt();
}while(keepGoing == 1);
}
public static boolean kitchenMethod()
{
return keyVal.nextBoolean();
}
public static boolean bedroomMethod()
{
return keyVal.nextBoolean();
}
public static boolean familyRoomMethod()
{
return keyVal.nextBoolean();
}
public static boolean livingRoomMethod()
{
return keyVal.nextBoolean();
}
public static boolean bathroomMethod()
{
return keyVal.nextBoolean();
}
public static boolean basementMethod()
{
return keyVal.nextBoolean();
}
}