我目前正试图通过使用GUI制作彩票计划。我无法弄清楚为什么方法getTicketNumbers()没有返回任何东西。它只是打印[]。
同样如此:
String output = "Name: " + name + "\nNumbers: " + ticketNumbers + "\n\n";
tickNumbers输出[],但名称成功打印出名称。
我在构造函数中的Ticket类中添加了一个System.out.print,以确认正在成功传递ArrayList,它是:
public Ticket(ArrayList<Integer> ticketNumbers, String name) {
this.ticketNumbers = ticketNumbers;
this.name = name;
System.out.print("Are the numbers being passed:" + ticketNumbers + "\n");
}
方法toString成功打印名称但是再次打印名为ticketNumbers的ArrayList。
private void enterLottoButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (nameInput.getText().equalsIgnoreCase("")) {
JOptionPane.showMessageDialog(null, "Please Enter Your Name", "Error", JOptionPane.ERROR_MESSAGE);
} else if (ticketNumbers.size() < 4) {
JOptionPane.showMessageDialog(null, "Please Enter Four Numbers", "Error", JOptionPane.ERROR_MESSAGE);
} else {
ticketList.add(new Ticket(ticketNumbers, nameInput.getText()));
JOptionPane.showMessageDialog(null, "You Successfully Entered! \n\nName: " + nameInput.getText() + "\nNumbers: " + ticketNumbers.toString());
ticketNumbers.clear();
numbersTextField.setText("");
nameInput.setText("");
numberOfPeopleLabel.setText(" People Entered: " + ticketList.size());
}
门票类:
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JOptionPane;
public class Ticket {
private String name;
private ArrayList<Integer> ticketNumbers = new ArrayList<>();
public Ticket(ArrayList<Integer> ticketNumbers, String name) {
this.ticketNumbers = ticketNumbers;
this.name = name;
System.out.print("Are the numbers being passed:" + ticketNumbers + "\n");
}
public String getName() {
return name;
}
public ArrayList<Integer> getTicketNumbers() {
return ticketNumbers;
}
public ArrayList<Integer> getSortedTicketNumbers() {
Collections.sort(ticketNumbers);
return ticketNumbers;
}
@Override
public String toString() {
String output = "Name: " + name + "\nNumbers: " + ticketNumbers + "\n\n";
return output;
}
}
如果需要,请完整编写代码: http://pastebin.com/7i8VWQLk和http://pastebin.com/iRd49Nc7
答案 0 :(得分:1)
看起来您正在复制对列表的引用,因此当您在一个地方清除它(或修改它)时,它会随处更改/清除。
尝试制作防御性副本。像:
ArrayList<Integer> tickets = new ArrayList<>(ticketNumbers)
答案 1 :(得分:1)
ticketNumbers.clear()
此行导致问题。正如您所说,在构造Ticket
对象期间,数据已在此行中正确传递:ticketList.add(new Ticket(ticketNumbers, nameInput.getText()));
。但你事后清理了它们。您需要克隆ticketList
。无论最佳实践如何,您都可以在Ticket
课程内完成。
private List<Integer> clonedTicketNumbersList = new ArrayList<Integer>();
public Ticket(ArrayList<Integer> ticketNumbers, String name) {
this.ticketNumbers = ticketNumbers;
this.name = name;
for(Integer ticketNum : ticketNumbers) {
clonedTicketNumbersList.add(ticketNum );
}
System.out.print("Are the numbers being passed:" + ticketNumbers + "\n");
}
@Override
public String toString() {
String output = "Name: " + name + "\nNumbers: " + clonedTicketNumbersList + "\n\n";
return output;
}