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
158 views
in Technique[技术] by (71.8m points)

java - For loop won't kick out

This is some code I'm working on for an assignment. Say I would like to make three tables(Just a random number. The number of tables can be any number, as long as it's not over 100). Why won't the loop kick out after entering the values of the third table. Also there is a max limit set for the number of tables that can be created.

import javax.swing.JOptionPane;

class MakeTables
{
    private static final int MAX_NUMBER_TABLES = 100;
    public static void main(String[] args)
    {
        Table[] tables = new Table[MAX_NUMBER_TABLES];
        for (int i = Integer.parseInt(JOptionPane.showInputDialog("How many tables would you like to create?")); i < tables.length; i++)
        {
            tables[i] = new Table();
            if (tables[i] != null)
            {
                tables[i].setHeight(Double.parseDouble(JOptionPane.showInputDialog("Enter height:")));
                tables[i].setWeight(Double.parseDouble(JOptionPane.showInputDialog("Enter weight:")));
                tables[i].setColor(JOptionPane.showInputDialog("Enter color:"));
                tables[i].setNumberOfLegs(Integer.parseInt(JOptionPane.showInputDialog("Enter number of legs:")));
                JOptionPane.showMessageDialog(null,(tables[i].toString()));
            } // end if
        } // end for
    } // end main
} // end class
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
for (int i = Integer.parseInt(JOptionPane.showInputDialog("How many tables would you like to create?")); i < tables.length; i++)

Here, the loop counter i is initially set to 3 (or whatever the user enters). Then the loop keeps going until i = 100. So that's why it's not working as you expect.

Set the counter to 0 initially, then break the loop when the counter reaches the user-specified limit OR the size of the array. Better yet, don't create the array until you know the user-specified limit.


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

...