我的代码不会在循环中执行代码块

时间:2013-11-02 17:47:37

标签: java loops

import java.awt.*;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.applet.Applet;
import java.util.Scanner;

public class Histogram extends Applet{
static int [] scores= {13,30,23,8};
static int [] minInterval = {0,25,50,75};
static int [] maxInterval = {25,50,75,100};
public void paint (Graphics g){
    int max = 0; 
    for (int i = 0; i < scores.length; i++) {
        if (max < scores[i]) {
            max = scores[i];
        }
    }

    Graphics2D g2 = (Graphics2D)g;
    Point2D.Double Yi = new Point2D.Double(50,50);
    Point2D.Double Yf = new Point2D.Double(50,30*scores.length);
    Line2D.Double Y = new Line2D.Double (Yi,Yf);
    Point2D.Double Xi = new Point2D.Double(50,50);
    Point2D.Double Xf = new Point2D.Double(50+(8*max),50);
    Line2D.Double X = new Line2D.Double (Xi,Xf);
    int x = 8*max;
    //Draw the "Score"
    int headerX = 50+(x/(max/5))*((max/5)-1);
    g2.drawString("Histogram of Student Scores",(headerX),30);
    for(int i=0;i<=max/5;i++){
        int j = (i)*5;
        if(i<max/5)
            g2.drawString(String.format("%d",j),50+(x/(max/5))*i,50);
        else
            g2.drawString(String.format("Number of Students"),50+(x/(max/5))*i,50);

    }
    for(int i=0;i<=maxInterval.length;i++){
        if(i != maxInterval.length-1 )
            g2.drawString(String.format("[%d,%d)",minInterval,maxInterval),20,60+(30)*i);
        else if(i == maxInterval.length-1)
            g2.drawString(String.format("[%d,%d]",minInterval,maxInterval),20,60+(30)*i);
        else
            g2.drawString("Score Ranges",20,60+(30)*i);
    }
    g2.draw(X);
    g2.draw(Y);
}

}

我的问题是代码没有进入第三个循环。但是当我在另一个循环中测试循环时

方法。它有点工作。所以我不知道接下来该做什么。我想知道它为什么没有

执行该代码块。

提前谢谢。

1 个答案:

答案 0 :(得分:0)

您将一个数组作为参数提供给String.format("...", , )(而不是int,您可以通过查找数组中的元素(可能是索引i)来获得。< / p>

因为它是String.format的参数,所以很可能没有得到编译器或IDE警告。

因此,如果你修复了这个问题,那么代码就像这样,你可以从那里开始。

    for (int i = 0; i <= maxInterval.length; i++) {
        if (i != maxInterval.length - 1)
            g2.drawString(String.format("[%d,%d]", minInterval[i], maxInterval[i]), 20, 60 + (30) * i);
        else if (i == maxInterval.length - 1)
            g2.drawString(String.format("[%d,%d]", minInterval[i], maxInterval[i]), 20, 60 + (30) * i);
        else
            g2.drawString("Score Ranges", 20, 60 + (30) * i);
    }