2016-11-14 66 views
0

在我的学校,我们一直负责编码“战舰的完美游戏”。为此,我们会得到一个文件ships.txt,我们必须扫描并查找任何船舶,A,P,B,S或C,并打印出它们的位置。这是文件(10×10):文件扫描器跳过线

..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的打印out:

(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) 

我最好的猜测是t扫描仪正在跳过第五行,但对于我的生活,我无法弄清楚为什么或如何修复它。有人可以帮忙吗?

+0

您应该仔细检查您的预期输出。请记住,你的代码工作**基于**(循环索引)! – Paul

+1

您的程序正在打印出正确的坐标。你“知道”答案看起来不正确。 – Joe

+0

这几乎是正确的,但1)应该有17个产出bc有17艘船和2)没有船在第7排巡逻船(PP)在第8排,最后3)0是第一排和列。 – Jason

回答

0

随着一点点的调整,以代码:

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