gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:00:35 25 4
gpt4 key购买 nike

我正在执行一项任务,其中涉及使用 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);
}

}
}

最佳答案

您从未使用实际的文件初始化扫描仪。请尝试使用以下代码:

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

关于java - 为什么扫描仪和 fillRect 无法识别我的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33362119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com