Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...