2013-09-20 3 views
0

Я хочу добавить все введенные пользователем данные, которые я только что получил, и поместить их в одно положение.Добавление нескольких объектов в массив

Scanner sc = new Scanner(System.in); 
int cit = 0; 

//cit = Integer.parseInt(sc.nextLine()); 

/*if statement to ensure a value greater than 0 and less than or equal to 50 is 
* entered. 
*/ 
//System.out.println(cit); 
System.out.println("Welcome to OswegoNote - your friendly Citation Manager."); 
boolean accepted = false; 
Index citationIndex; 
Citation currentCitation; 
while (!accepted) { 
    System.out.println("How many citations would you like to store today? (between 0 and 50):"); 
    cit = Integer.parseInt(sc.nextLine()); 
    int citcounter = cit; 
    if (cit <= 50) { 

     if (cit > 0) { 
      accepted = true; 
      citationIndex = new Index(cit); 

     } else { 
      System.out.println("Error: please enter a number between 0 and 50."); 
     } 

    } else { 
     System.out.println("Error: please enter a number between 0 and 50."); 
    }//end if <=50 

}//end while loop 



for (int i = 0; i < cit; i++) { 

    currentCitation = new Citation(""); 
    currentCitation.updateId(i); 

    System.out.println("Please enter publication name (or 'quit' to quit):"); 
    String name = sc.nextLine(); 
    currentCitation.setName(name); 


    System.out.println("Please enter the date of publication (in mm/dd/yyyy format) (or 'quit' to quit):"); 
    String pubDate = sc.nextLine(); 
    currentCitation.setDateOfPublication(pubDate); 



    //while (accepted = true) { 
    System.out.println("How many authors are there? (max 3):"); 
    int numAuthors = Integer.parseInt(sc.nextLine()); 
    //currentCitation.numOfAuthors = numAuthors; 
    if (numAuthors <= 3 && numAuthors > 0) { 
     for (int a = 0; a < numAuthors; a++) { 
      System.out.println("Enter the name of author #" + (a+1) + ". (FirstName MI. LastName) (or 'quit' to quit):"); 
      String authorName = sc.nextLine(); 
      currentCitation.addAuthor(authorName); 
     } 
     accepted = false; 
     //break; 
    } else { 
     System.out.println("Error: Please enter a number between 0 and 3."); 
    } //end if 
    //} 



    System.out.println("Where was it published? (or 'quit' to quit):"); 
    String pubPlace = sc.nextLine(); 
    currentCitation.setWherePublisher(pubPlace); 

    System.out.println("What is the publisher's name? (or 'quit' to quit):"); 
    String publisher = sc.nextLine(); 
    currentCitation.setPublisher(publisher); 

    //while (accepted = true) { 
    System.out.println("How many keywords would you like to add?(max 5) (or 'quit' to quit):"); 
    int numKeywords = Integer.parseInt(sc.nextLine()); 
    if (numKeywords <= 5 && numKeywords > 0) { 
     for (int k = 0; k < numKeywords; k++) { 
      System.out.println("Enter keyword #" + (k+1) + ". (or 'quit' to quit)"); 
      String keyW = sc.nextLine(); 

      currentCitation.addKeyword(keyW); 
     } 
     accepted = false; 
     //break; 
    } else { 
     System.out.println("Error: Please enter a number between 0 and 5."); 
    } //end if 
    //} 

    System.out.println("This is your Citation:"); 
    System.out.println("Name: " + currentCitation.getName()); 
    System.out.print("Author(s): "); 

    for (int s = 0; s <= numAuthors - 1; s++) { 
     if ((numAuthors - 1) > s) { 
     System.out.print(currentCitation.authors[s] + ", "); 
    } else { 
      System.out.println(currentCitation.authors[s]); 
     } 
    } 
    System.out.println("Date of Publication: " + currentCitation.getDateOfPublication()); 
    System.out.println("Name of Publisher: " + currentCitation.getPublisher()); 
    System.out.println("Publication Place: " + currentCitation.getWherePublisher()); 

    System.out.print("Keywords: "); 
    for (int s = 0; s <= numKeywords - 1; s++) { 
     if ((numKeywords - 1) > s) { 
      System.out.print(currentCitation.keywords[s] + ", "); 
     } else { 
      System.out.println(currentCitation.keywords[s]); 
     } 

    } 
    System.out.println("Would you like to save this? (yes or no or 'quit' to quit):"); 
    String answer = sc.nextLine(); 
    if (answer.equalsIgnoreCase("no")) { 

    } else { 
     citationIndex[i] = {currentCitation.authors, currentCitation.keywords, currentCitation.ID, currentCitation.dateOfPublication, currentCitation.name, currentCitation.publisher, currentCitation.wherePublisher}; 
    } 

}// end for 

Извините за весь основной метод. Я не очень хорошо разбираюсь в Java, поэтому я не знаю, как я мог бы описать свою ситуацию.

+0

Я пытаюсь добавить все входные данные в citationIndex []. – user2800960

+1

Можете ли вы описать проблему, с которой вы столкнулись, более подробно? – Dukeling

+0

В чем ваш вопрос? Очевидно, никто не будет читать весь ваш код, не зная, что именно искать. –

ответ

0

Используйте ArrayList вместо массива, а затем добавить несколько элементов к нему с помощью addAll:

Если элементы, которые вы хотите добавить к нему еще не в коллекции, поместите их в один первый:

mylist.addAll(Arrays.asList(1, 2, 3));

Или вы можете добавить их по одному за раз:

mylist.add(1); 
mylist.add(2); 
mylist.add(3); 

ОТКАЗ: Я только бр был ваш код, потому что я не хотел его читать. Я в основном отвечаю, основываясь на названии вашего вопроса.

+0

Нам не разрешено использовать ArrayList для этого задания. – user2800960

+0

Что делает назначение, так это получение пользователем ввода (имя книги, издателя, дата публикации, ключевые слова, ID # и т. Д.), И после того, как мы получим весь вход, мы должны поместить его в массив, содержащий все данные цитирования – user2800960

+0

принимают два массива в процессе сбора информации, ключевых слов [] и авторов []. – user2800960

Смежные вопросы