0

每次我运行这个程序来创建一个新对象时,它应该从 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();
}
4

1 回答 1

1

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

concert[numConcert++] = new Concert(artist, quantTickets, ticketCost, month, day, year, numConcert);
于 2013-10-20T23:46:55.390 回答