簡體   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