gpt4 book ai didi

java - 在没有具有起始值的对象的情况下增加 "ID"计数 (java)

转载 作者:行者123 更新时间:2023-12-01 13:58:36 26 4
gpt4 key购买 nike

每次我运行这个程序来创建一个新对象时,它应该从 1000 开始,并且每次创建时都会递增 1。如何增加这个独立于数组计数的计数。

现在每次我运行该程序时,它都会输出 1000 的 Id

请尽可能简单,我不太了解java。谢谢

主程序

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

类别

public class Concert {
private String artist = "";
private int quantTickets = 0;
private int ticketCost = 0;
private int month = 0;
private int day = 0;
private int year = 0;
private int numConcert = 0;
private int concertId = 1000;

public Concert(String artist, int quantTickets, int ticketCost, int month, int day, int year, int concertId){
this.artist = artist;
this.quantTickets = quantTickets;
this.ticketCost = ticketCost;
this.month = month;
this.day = day;
this.year = year;
this.concertId = concertId;
}

public void setConcertId (int concertId){
concertId++;
this.concertId = concertId;
}

public String shortString(){
return " " + artist + " " + getConcertId();
}

最佳答案

没有理由将音乐会 ID 与数组计数分开。事实上,数组计数将是一个非常好的音乐会 ID。您只需修改此行即可:

concert[numConcert++] = new Concert(artist, quantTickets, ticketCost, month, day, year, numConcert);

关于java - 在没有具有起始值的对象的情况下增加 "ID"计数 (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19484206/

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