我在做什么:在下面的代码片段中,我打印出条形图的 X 轴,这取决于不同长度的单词数量。例如,最大字的长度为 6,因此 X 轴沿底部有 1、2、3、4、5、6。
问题是什么:代码完全正常,但是我的paint方法返回了一个错误。
我已经尝试过:通过将代码块制作成在paint方法中调用的方法来隔离导致问题的代码行。
使用的变量:
lengthCountArray.length(数组长度表示底部有多少个数字)
int canvasWidth = 410;
int inferiorLeftCornerX = 50; // this the the x point of the left corner on the x axis
int inferiorLeftCornerY = 470; // this the the y point of the left corner on the x axis
int barWidth = canvasWidth / lengthCountArray.length; // this calculates the distance for the bars
int posLabelX = barWidth / 2; // this puts the label in the centre of the bars by halving it
posLabelX = inferiorLeftCornerX - posLabelX; // this is so that the initial number isn't indented twice
for (int a = 1; a < (lengthCountArray.length+1); a++){
posLabelX = posLabelX + barWidth;
g.drawString(String.valueOf(a), posLabelX, inferiorLeftCornerY);
}
导致问题的行是“int barWidth = canvasWidth / lengthCountArray.length; // 这会计算条的距离”(第 122 行)。
返回以下错误:
Exception in thread "AWT-EventQueue-1" java.lang.ArithmeticException: / by zero
at java_assignment.JavaAppletMain.paint(JavaAppletMain.java:122)
at sun.awt.RepaintArea.paintComponent(RepaintArea.java:264)
at sun.lwawt.LWRepaintArea.paintComponent(LWRepaintArea.java:54)
at sun.awt.RepaintArea.paint(RepaintArea.java:240)
at sun.lwawt.LWComponentPeer.handleJavaPaintEvent(LWComponentPeer.java:1267)
at sun.lwawt.LWComponentPeer.handleEvent(LWComponentPeer.java:1150)
at java.awt.Component.dispatchEventImpl(Component.java:4937)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
在导致 StackOverflow 之前,我一直在尝试解决这个问题几个小时,所以如果您需要更多信息,请随时询问!
感谢您查看我的问题。