繁体   English   中英

文件扫描仪跳过行

[英]File Scanner skipping over line

在我学校,我们的任务是编写“完美的战舰游戏”。 为此,我们给了一个文件Ships.txt,我们必须对其进行扫描并查找任何A,P,B,S或C船,并打印出它们的位置。 这是文件(10x10):

..CCC.....
..........
...A.....B
...A.SSS.B
...A.....B
...A......
..........
.......PP.
..........
..........

这是我拥有的代码:

import java.util.Scanner;
import java.io.*;
public class BattleShip{
    public static void main(String[] args)throws IOException{
        Scanner scf = new Scanner(new File("ships.txt"));
        String line = "p";

        for(int c = 0; c<10;c++){
            line = scf.nextLine() + " ";

            for(int h = 0;h<10;h++){

                boolean isShip =          line.substring(h,h+1).equalsIgnoreCase(".");
                if(isShip == false){
                    System.out.println(c + "," + h);

                }
            }
        }
    }
}

我知道答案是:

(0,2)
(0,3)
(0,4)
(2,3)
(2,9)
(3,3)
(3,5)
(3,6)
(3,7)
(3,9)
(4,3)
(4,9)
(5,3)
(5,9)
(6,3)
(8,7)
(8,8)

问题是Eclipse会打印出:

(0,2)
(0,3)
(0,4)
(2,3)
(2,9)
(3,3)
(3,5)
(3,6)
(3,7)
(3,9)
(4,3)
(4,9)
(5,3)
(7,7)
(7,8)

我最好的猜测是扫描仪正在跳过第五行,但是对于我一生来说,我不知道为什么或如何解决它。 有人可以帮忙吗?

稍微调整一下代码:

import java.util.Scanner;
import java.io.*;
public class BattleShip{
    public static void main(String[] args)throws IOException{
        Scanner fileScanner= new Scanner(new File("ships.txt"));
        String line;

        for(int row = 0; row < 10; row++){
            line = fileScanner.nextLine() + " ";

            for(int column = 0; column < 10; column++){

                boolean isShip = line.substring(column, column + 1).equalsIgnoreCase(".");

                if(isShip == false){
                    System.out.print(row + "," + column + "\t");
                }
                else{
                    System.out.print(".\t");
                }
            }
            System.out.println("");
        }
        fileScanner.close();
    }
}

您将获得以下输出:

.   .   0,2 0,3 0,4 .   .   .   .   .   
.   .   .   .   .   .   .   .   .   .   
.   .   .   2,3 .   .   .   .   .   2,9 
.   .   .   3,3 .   3,5 3,6 3,7 .   3,9 
.   .   .   4,3 .   .   .   .   .   4,9 
.   .   .   5,3 .   .   .   .   .   .   
.   .   .   .   .   .   .   .   .   .   
.   .   .   .   .   .   .   7,7 7,8 .   
.   .   .   .   .   .   .   .   .   .   
.   .   .   .   .   .   .   .   .   .   

它基本上是相同的代码逻辑,只是在这里和那里添加了一些换行符,点和制表符,使其看起来更加清晰。

显然,输出正确,并且没有跳过任何行。

给出的答案似乎是错误的,而不是日食:p

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM