猿问

Java ArrayList 循环问题

我在eclipse上用java编写一个垄断式的游戏。我目前正在研究一种方法,该方法允许玩家循环通过自己的方格并选择要开发的方格。


for (int loop2 = 0; loop2 < currentPlayer.getOwnedSquares().size(); loop2++) {


    count++;


    System.out.println("Would you like to develop this property " + count + ". " 

    + currentPlayer.getOwnedSquares().get(loop2).getName() + " (y/n)");


    propertyChoice = scanner.nextLine();


    if (propertyChoice.equalsIgnoreCase("Y")) {

            break;

        }else if (propertyChoice.equalsIgnoreCase("N")) {


            continue;

        }

    }

System.out.println("Please choose a development option");

System.out.println("1.Buy a start-up");

System.out.println("2.Buy a global corporation");

int option = scanner.nextInt();

我无法让循环一次只显示一个拥有的方格,因此玩家可以选择是/否想要开发哪个方格。如果玩家选择“N”,则循环将呈现数组中的下一个拥有的属性,玩家将做出另一个决定,依此类推。如果玩家选择“Y”,则循环将中断并继续前进所选自有广场的发展选择。


任何有关如何实现这一点的建议将不胜感激。


慕慕森
浏览 89回答 3
3回答

精慕HU

您必须将用户输入检查移出循环,因此算法如下所示:循环打印所有拥有的方块。询问用户(在循环之外)他想要开发哪个方格。例如,用户可以简单地提供一个正方形的位置编号,您可以通过currentPlayer.getOwnedSquares().get(Integer.valueOf(userInput));用选定的正方形做任何你需要的事情。

MMTTMM

我只是修改了代码进行测试,它可以按您的意愿工作。我认为您还没有分享其他问题。import java.util.Scanner;public class Test {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; int count=0;&nbsp; &nbsp; &nbsp; &nbsp; String propertyChoice;&nbsp; &nbsp; &nbsp; &nbsp; Scanner scanner = new Scanner(System.in);&nbsp; &nbsp; &nbsp; &nbsp; for (int loop2 = 0; loop2 < 5; loop2++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Would you like to develop this property " + count&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;+ " (y/n)");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; propertyChoice = scanner.nextLine();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (propertyChoice.equalsIgnoreCase("Y")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else if (propertyChoice.equalsIgnoreCase("N")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Please choose a development option");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("1.Buy a start-up");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("2.Buy a global corporation");&nbsp; &nbsp; }}输出:Would you like to develop this property 1 (y/n)nWould you like to develop this property 2 (y/n)nWould you like to develop this property 3 (y/n)yPlease choose a development option1.Buy a start-up2.Buy a global corporationProcess finished with exit code 0

一只甜甜圈

尝试scanner.nextLine();立即投入propertyChoice = scanner.nextLine();编辑:如果这不起作用,请注意第二个块else周围没有括号。if我不知道这是否可行,因为我没有看到您所指的课程,也不能说有错误。您显示的代码似乎没有任何其他问题。
随时随地看视频慕课网APP

相关分类

Java
我要回答