增加一个“;ID";没有具有起始值的对象的计数(java)
每次我运行这个程序来创建一个新对象时,它应该从1000开始,每次创建它时,增量为1。如何增加此数组的计数与数组的计数无关 现在,每次我运行程序时,它都会为每个输出1000的Id 请尽量简单,我不太懂java。谢谢 主程序增加一个“;ID";没有具有起始值的对象的计数(java),java,counter,Java,Counter,每次我运行这个程序来创建一个新对象时,它应该从1000开始,每次创建它时,增量为1。如何增加此数组的计数与数组的计数无关 现在,每次我运行程序时,它都会为每个输出1000的Id 请尽量简单,我不太懂java。谢谢 主程序 import javax.swing.JOptionPane; public class useConcert { private static Concert[] concert = new Concert[100]; private static int nu
import javax.swing.JOptionPane;
public class useConcert {
private static Concert[] concert = new Concert[100];
private static int numConcert = 0;
public static void main (String[] args){
String userInput = "";
boolean testResult;
do {
userInput = mainMenu();
if (userInput.equals("1")) {
do{
String artist = getStringInput("Artist or Group name?");
int month = getIntegerInput("Enter month in XX format ");
int day = getIntegerInput("Enter day in XX format ");
int year = getIntegerInput("Enter year in XXXX format");
int ticketCost = getIntegerInput("Enter cost per ticket ($25 - $250)");
int quantTickets = getIntegerInput("Enter Number of tickets available (Max 10,000)");
int concertId = 1000;
concert[numConcert++] = new Concert(artist,quantTickets,ticketCost,month,day,year,concertId);
}while (JOptionPane.showConfirmDialog(null, "Add another concert?")==JOptionPane.YES_OPTION);
} else if (userInput.equals("2")) {
listConcert();
}
} while (!userInput.equals("0"));
public static String concertList(){
String outputString = "";
for (int idx =0; idx < numConcert; idx++){
outputString += concert[idx].shortString() + "\n";
}
return outputString;
}
public static void listConcert() {
EZJ.dialog(concertList());
}
}
没有理由将concert ID与数组计数分开。事实上,数组计数将是一个非常好的concert ID。您只需修改此行即可:
concert[numConcert++] = new Concert(artist, quantTickets, ticketCost, month, day, year, numConcert);
即使将来必须通过concert id进行搜索,您也会使用它?实际上,现在我认为不需要concert id。如果需要,您可以使用数组索引。但是如何在1000开始数组索引?首先,使数组能够容纳1000个元素。其次,在开始时将
numConcert
变量更改为1000。第三,将此行更改为使用numConcert--
而不是numConcert++
。但请注意:在将来,如果您继续以这种方式开发,您的数组中的空间将不足,并且会出现ArrayIndexOutOfBoundsException
。我建议您了解数组列表,这样您就可以避免出现此问题。您还可以增加您的concertID:concert[numConcert++]=new concert(艺术家、quantTickets、票务成本、月、日、年、concertID++)代码>
concert[numConcert++] = new Concert(artist, quantTickets, ticketCost, month, day, year, numConcert);