多阵列输入

时间:2015-09-21 10:12:58

标签: java arrays for-loop

我无法创建一个循环来为多阵列添加小时数。当我使用方法小时时出现错误。我怀疑我的for循环没有捕获输入。

import javax.swing.JOptionPane;

public class Gain 
{
    // Defining array names.
    String[] name = {"A", “B”, “C”, “D”, “E”, “F”, “G”, “H”, “I”, “L”}; 
    int[][] hours = new int[10][3];

    public final int Hours() 
    {
    boolean canceled = false;
    for (int index = 0; index < name.length; index++) {
        JOptionPane.shoeMessageDialog(“Please enter " + name[index] + “’s hours”);
            for (int x = 0; x <= hours.length; x++)
               for (int y = 0; y <= hours[x].length; y++)
        Integer value = promptForInt(artist[index] + “’s first hour: ”);
        if (value != null) {
          while (value < 0)
        {
            JOptionPane.showMessageDialog(null, "Please positive figures." + "\nPlease try again.");
            value = promptForInt(name[index] + “’s first hour: ”);
        }
            pay[x][y] = value;
        } else {
            canceled = true;
            break;
        }
    }

    public static void main(String[] args) // Main program
    {
        for (int x = 0; x <= name.length; x++)
           for (int y = 0; y <= hours.length; y++)
              System.out.println(x, y);
    }

1 个答案:

答案 0 :(得分:0)

尝试添加括号,如下所示:

import javax.swing.JOptionPane;

public class Gain 
{
    // Defining array names.
    String[] name = {"A", “B”, “C”, “D”, “E”, “F”, “G”, “H”, “I”, “L”}; 
    int[][] hours = new int[10][3];

    public final int Hours() 
    {
        boolean canceled = false;
        for (int index = 0; index < name.length; index++)
        {
            JOptionPane.shoeMessageDialog("Please enter " + name[index] + "’s hours");
            for (int x = 0; x <= hours.length; x++)
            {
                for (int y = 0; y <= hours[x].length; y++)
                {
                    Integer value = promptForInt(artist[index] + “’s first hour: ”);
                    if (value != null)
                    {
                        while (value < 0)
                        {
                            JOptionPane.showMessageDialog(null, "Please positive figures." + "\nPlease try again.");
                            value = promptForInt(name[index] + “’s first hour: ”);
                        }
                        pay[x][y] = value;
                    } 
                    else
                    {
                        canceled = true;
                        break;
                    }
                }
            }

        }
    }

    public static void main(String[] args) // Main program
    {
        for (int x = 0; x <= name.length; x++)
           for (int y = 0; y <= hours.length; y++)
              System.out.println(x, y);
    }

虽然在之后只有一行代码(例如在main方法中)时避免使用for循环中的括号,但是当你有一个整块时,你需要使用它们,就像Hours()方法中的情况一样。就个人而言,我喜欢一直使用括号,因为它使代码更具可读性,但这只是我。 :)