用户输入了数组大小的输入,但数组大小不等于用户输入

时间:2016-03-30 18:05:29

标签: java

有谁可以告诉我为什么数据定义类中titles数组的数组大小不等于从实现类传入并在数据定义类中设置为实例变量的用户输入的值? / p>

这是数据定义类。

public class Photograph { 

   private int maxTakes;

   public Photograph() {
      this.titles = new String[this.maxTakes];
      numPhotosTaken = 0;
   }

   public void setMaxTakes(int maxTakes) {
      this.maxTakes = maxTakes;
   }

   public boolean setTitle(String title) {
      if (this.numPhotosTaken < this.titles.length) {
         this.titles[numPhotosTaken] = title;
         numPhotosTaken++;
         return true;
      }
      else {
         return false;
      }
   }
}

这是实现类。

import javax.swing.JOptionPane;

public class MakePhotographs {
   public static void main (String[] args) {
      Photograph photo;
      do {
         photo = create();
      } while (JOptionPane.showConfirmDialog(null, "Enter another couple?") == JOptionPane.YES_OPTION);
   }

   private static Photograph create() {
      Photograph photo = new Photograph();
      photo.setMaxTakes(Integer.parseInt(JOptionPane.showInputDialog("Enter maximum number of photos to take")));

      do {
         String title = JOptionPane.showInputDialog("Enter title of photo");
         if (!photo.setTitle(title)) {
            JOptionPane.showMessageDialog(null, "No more photos allowed!");
         }   
      } while (JOptionPane.showConfirmDialog(null, "Enter another photo?") == JOptionPane.YES_OPTION);
      return photo;
   }
}

2 个答案:

答案 0 :(得分:2)

创建一个接受maxTakes值并使用它的构造函数:

Photograph photo = new Photograph(Integer.parseInt(JOptionPane.showInputDialog("Enter maximum number of photos to take")));

您不再需要setMaxTakes,因为它已在构造函数中设置。

class Photograph { 

    private int maxTakes;
    private String[] titles;
    private int numPhotosTaken;

    public Photograph(int maxTakes) {
        this.maxTakes = maxTakes;
        this.titles = new String[maxTakes];
        numPhotosTaken = 0;
    }

    public boolean setTitle(String title) {
        if (this.numPhotosTaken < this.titles.length) {
            this.titles[numPhotosTaken] = title;
            numPhotosTaken++;
            return true;
        }
        else {
            return false;
        }
    }
}

答案 1 :(得分:1)

您可以在致电setMaxTakes()之前创建阵列。在您创建长度为maxTakes的数组后,更改maxTakes的值无法实现任何目标。

您需要将setMaxTakes()的方法更改为以下内容:

public void setMaxTakes(int maxTakes) {
    titles = new String[maxTakes];
}

或者使用@Gremash here发布的答案(这是正确的方法)。