안녕하세요. 내 ArrayList에 항목을 인쇄하는 데 문제가 있습니다. 내 PatronBorrow 메서드에서 인쇄 할 수 있지만 PatronList 및 PatronReturn에서는 아무것도 인쇄하지 않습니다. 누구든지 코드에 무엇이 잘못되었는지 말해 줄 수 있습니까? 당신이 Patron
때마다 새로운 (빈)을 만들고있는 Patron
클래스를 사용하여 루프에서 매우ArrayList가 객체를 저장하지 않습니다.
package proj1;
import java.util.ArrayList;
import java.util.List;
public class Patron {
private int id;
private Book book;
private List<Book> books;
public Patron(int id){
this.id = id;
books = new ArrayList<Book>();
}
public int getID(){
return id;
}
public List<Book> getBooks(){
return books;
}
public void PatronBorrow(String b){
book = new Book(b);
books.add(book);
System.out.println("Patron " + id + " has borrowed " + book.getTitle());
}
public void PatronReturn(String b){
for(Book book : books){
if(book.getTitle().equals(b)){
books.remove(book);
System.out.println("Patron " + id + " has borrowed " + book.getTitle());
}
}
}
public void PatronList(){
for(Book b : books){
System.out.println("Patron " + id + " has borrowed " + books.size() + " item(s)");
System.out.println(b);
}
}
}
package proj1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Project1 {
public static boolean isNumeric(String str){
for(char c : str.toCharArray()){
if(Character.isDigit(c)){
return true;
}
}
return false;
}
public static void main(String[] args){
String command;
String line;
Patron patron;
int patronID;
String title;
String newTitle;
String infile = args[0];
if (args.length != 1){
throw new IllegalArgumentException("Enter in file name");
}
try{
Scanner file = new Scanner(new FileInputStream(infile));
while(file.hasNext()){
command = file.next();
if(isNumeric(command)){
patronID = Integer.parseInt(command);
patron = new Patron(patronID);
command = file.next();
if(command.equals("borrow")){
title = file.nextLine();
newTitle = title.substring(2, title.length() - 1);
patron.PatronBorrow(newTitle);
}else if(command.equals("return")){
title = file.nextLine();
newTitle = title.substring(2, title.length() - 1);
patron.PatronReturn(newTitle);
}else if(command.equals("list")){
patron.PatronList();
}
}else{
}
}
}catch (FileNotFoundException e) {
System.out.println("File not found" + e.getMessage());
System.exit(0);
}
}
}
왜 PatronList에 아무 것도 인쇄하지 않을 것입니다. Patron 객체를 다시 초기화하지 않거나 책 객체를 추가하기 전에 메소드를 호출 할 수 있습니까? –
이러한 메소드를 호출하는 방법에 따라 클래스의 마지막 두 메소드가 빈 목록을 반복하도록 바인딩됩니까? 또한 PatronReturn에서 추가하는 유일한 책을 삭제한다는 사실에 유의하십시오. 성취하고자하는 것은 무엇입니까? –
질문에 main 메소드를 추가하여이 클래스를 호출하는 코드를 볼 수 있습니까? – Jyro117