gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:42:14 25 4
gpt4 key购买 nike

谁能告诉我为什么数据定义类中标题数组的数组大小不等于用户输入的从实现类传入并在数据定义类中设置为实例变量的值?

这是数据定义类。

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;
}
}

最佳答案

创建一个接受 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;
}
}
}

关于java - 用户输入了数组大小,但数组大小不等于用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36316405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com