为什么扫描仪和fillRect无法识别我的变量?

时间:2015-10-27 07:29:15

标签: java

我正在处理一项任务,该任务涉及使用x / y坐标在500px * 500px JFrame上的某些位置绘制内容。我可以让程序绘制一个位置,但它完全忽略了它通过扫描仪从输入文件接收的信息,只是在左上角绘制矩形。更改towers.txt中的值不会出于某种原因。我的代码出了什么问题?

第一档......

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 个答案:

答案 0 :(得分:1)

您从未使用实际Scanner初始化File。请尝试使用此代码:

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));
}