2015-10-27 70 views
0

我正在处理一个任务,该任务涉及使用x/y坐标在500px * 500px JFrame上的特定位置绘制东西。我可以让程序绘制一个位置,但是它完全忽略了它通过扫描仪从输入文件接收到的信息,而只是在左上角绘制矩形。由于某些原因,更改towers.txt中的值不做任何事情。我的代码有什么问题?为什么我的变量不能被scanner和fillRect识别?

第一个文件...

public class Main { 
    public static void main(String[] args) throws FileNotFoundException { 
     File towers = new File("towers.txt"); 
     File readings = new File("readings.txt"); 
     Scanner towers1 = new Scanner("towers"); 
     Scanner readings1 = new Scanner("readings"); 
     ArrayList<Integer> towerPos = new ArrayList<Integer>(); 
     ArrayList<Integer> readingPos = new ArrayList<Integer>(); 

     while(towers1.hasNextDouble()) { 
      towerPos.add((int)towers1.nextDouble()); 
     } 

     while(readings1.hasNextDouble()) { 
      readingPos.add((int)readings1.nextDouble()); 
     } 


     JFrame f = new JFrame("Cellphone Coverage"); 
     f.setVisible(true);  
     f.setSize(500, 500); 
     f.setDefaultCloseOperation(
      JFrame.EXIT_ON_CLOSE); 
     f.add(new CoveRage(towerPos, readingPos)); 

    } 
} 

第二个文件...

public class CoveRage 
extends JComponent { 

    private ArrayList<Integer> readingPos; 
    private ArrayList<Integer> towerPos; 
    int xAxis; 
    int yAxis; 

    public CoveRage(ArrayList<Integer> towerPos, ArrayList<Integer> readingPos) { 
     this.towerPos = towerPos; 
     this.readingPos = readingPos; 
     } 

    public void paintComponent(Graphics g) { 
     Graphics2D g2 = (Graphics2D) g.create(); 
     for (int j = 0; j < towerPos.size(); j += 2) { 
      int xAxis = towerPos.get(j)/10; 
      int yAxis = towerPos.get(j + 1)/10; 
      g2.setColor(Color.black); 
      g2.fillRect(xAxis, yAxis, 5, 5); 
     } 

    } 
} 

回答

1

你永远不与实际File初始化Scanner。试试这个代码,而不是:

public static void main(String[] args) throws FileNotFoundException { 
    File towers = new File("towers.txt"); 
    File readings = new File("readings.txt"); 
    Scanner towers1 = new Scanner(towers);  // remember to initialize 
    Scanner readings1 = new Scanner(readings); // the Scanner with the file 
    ArrayList<Integer> towerPos = new ArrayList<Integer>(); 
    ArrayList<Integer> readingPos = new ArrayList<Integer>(); 

    while(towers1.hasNextDouble()) { 
     towerPos.add((int)towers1.nextDouble()); 
    } 

    while(readings1.hasNextDouble()) { 
     readingPos.add((int)readings1.nextDouble()); 
    } 

    JFrame f = new JFrame("Cellphone Coverage"); 
    f.setVisible(true);  
    f.setSize(500, 500); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f.add(new CoveRage(towerPos, readingPos)); 
} 
+0

感谢您的答复,但是我改变了对目的,因为我得到这个错误“异常线程‘main’java.io.FileNotFoundException:towers.txt(系统无法找到文件指定)“,我现在正在更改我的代码后再次得到它。该文件位于正确的目录中,我相信这很奇怪。 –

+0

我在声明文件位置“System.out.println(new File(”。“)。getAbsoluteFile());”并打印出文件所在的位置。 –

+0

@pabloescobrah你需要把文件的完整位置。如果你的代码是作为一个Java控制台应用程序运行的(我猜测),那么你可以尝试类似'new File(“C:\ Users \ pablo \ towers.txt”)',假设文件'“towers.txt” '位于C:驱动器上的那个位置。 –

相关问题