如何读取二维数组索引?来自java中的文件(IE:Coords)

发布于 2025-01-03 14:32:32 字数 577 浏览 0 评论 0原文

我正在为我的计算机班编写一个生命游戏程序,我已经拥有了一切都很好(虽然我希望现在使用不同的结构,但是哦,好吧)。我遇到的问题是我无法正确读取我们的输入文件。它是这样设置的:第一个数字是生命游戏棋盘的大小,然后接下来的行是由空格分隔的整数对,显示哪些细胞以生命开始。然后以-1 -1结束即可。我尝试了多种方法,但无法让它正确读取。我包含了我尝试的第一种方法的代码,该方法只涉及使用 Scanner

ex:

5

4 1

2 3

-1 -1
        int x;
        Scanner in = new Scanner (new File(file));
        x= in.nextInt();
        char[][] board= new char[x][x];
            while(in.hasNext())
              {
                if(in.nextInt() != -1)
                board[in.nextInt()][in.nextInt()]='X';
                }//end while

I am writing a Game of life program for my cs class, and I have all that well and good (although I wished I used a different structure now, but oh well). The problem I am having is that I cant read our input file correctly. It is set up as such: 1st number is the size of the board for the game of life, then the following lines are pairs of integers separated by a space that show what cells start with life. Then ending in -1 -1 to end it. I have tried several ways and I just cant get it to read it in correctly. I included code for the first way I tried which just involved using Scanner

ex:

5

4 1

2 3

-1 -1
        int x;
        Scanner in = new Scanner (new File(file));
        x= in.nextInt();
        char[][] board= new char[x][x];
            while(in.hasNext())
              {
                if(in.nextInt() != -1)
                board[in.nextInt()][in.nextInt()]='X';
                }//end while

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

桜花祭 2025-01-10 14:32:32

您的问题在这里:

            if(in.nextInt() != -1)
                board[in.nextInt()][in.nextInt()]='X';

当您在 if 语句中调用 in.nextInt() 时,您将扫描器移至下一个 int。这样,每个循环调用都会向前移动三个整数,而不是两个。

将第一个 in.nextInt() 设置为一个变量,并在 if 语句中使用该变量和棋盘的第一个坐标。这样您就不会将扫描仪移动得太远。

Your problem is here:

            if(in.nextInt() != -1)
                board[in.nextInt()][in.nextInt()]='X';

When you call in.nextInt() in the if statement, you move the scanner on to the next int. That way, each loop call you move three integers forward, rather than two.

Set the first in.nextInt() to a variable and use the variable in the if statement and the first coordinate of the board. That way you won't move the scanner too far.

未蓝澄海的烟 2025-01-10 14:32:32

对 in.nextInt() 的调用次数过多。每次调用此函数都会使扫描仪向前移动。

因此,通过 if 语句,您正在读取第一个坐标 int,并将其与 -1 进行比较。
然后你去读另一个 int,这是第二个坐标,然后是另一个 int...它应该抛出 NoSuchElementException

You have too many calls to in.nextInt(). Each call to this moves the Scanner onwards.

So, with your if statment you are reading the first co-ordinate int, comparing it to -1.
You then go read another int, which is the second co-ordinate, then yet another int... which should be throwing a NoSuchElementException

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文