Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

How can I draw a string array in Java which changes contents on each loop?

I want to print a quiz to my GUI using my draw method which changes depending on how many times it is looped through, but the way I'm doing it does not print the String[] fruit to the screen. I assume because its not registering the loop I'm trying to make with the time value(?) but I can't figure out why.

public class Fruit {

    private String[] fruit = {};

    public void draw(Graphics2D g) {
        int time = 0;

        for (int i = 0; i < fruit.length; i++) {
            g.drawString(fruit[i], 100, 100);
        }

        if(time == 0){
            String[] fruit = {
                "Apples",
                "Pears"
            };
        }
        else if(time == 1){
            String[] fruit = {
                "Bananas",
                "Kiwi"
            };
        }
        time++;
    }
}
question from:https://stackoverflow.com/questions/65864366/how-can-i-draw-a-string-array-in-java-which-changes-contents-on-each-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's at least two things wrong with that code.

  1. You redeclare the name 'fruit' in two different local scopes, neither of which has anything to do with the member variable named 'fruit'. The member 'fruit' will never change from the empty array it was initialized to. Possibly you just mean 'fruit = ...' rather than 'String[] fruit = ...'.

  2. You set local variable 'time = 0' at the top of the draw() method, and there's nothing to change it. Therefore at the point you test whether it's 0 or 1, it's always 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...