내 질문은 장르가 여러 문자 (예 : Spy 또는 Humor) 인 경우 장르를 설명하는 데 char 필드를 어떻게 사용합니까? char는 1 문자 밖에 없으므로 어떻게 작동합니까?ArrayLists 및 char 필드
소설의 장르를 설명 할 수있는 소설 수업 내에 char 필드가 필요합니다. 다음은
는 내 코드는 내가import java.util.ArrayList;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("books.dat");
Scanner s = new Scanner(file);
ArrayList<Book> books = new ArrayList<Book>();
while(s.hasNext()){
if(s.nextInt() == 0){//novels
//create novel book
Novel n = new Novel();
read(s, n);
n.code = 0;
Book.totalPages(n.pages);
books.add(n);
}
}
for(int i = 0; i < books.size(); i++){
print(books.get(i));
}
}
public static void read(Scanner sc, Novel no){
no.name = sc.next();
no.pages = sc.nextInt();
no.genre = sc.next().trim().charAt(0);
//Im having scanner take
//the first letter of the genre and record it,
//but there will be a problem when two genres
//start with the same letter, how can i distinguish between the two?
}
public static void print(Book b){
if(b.code == 0){
System.out.printf("Name:%-15s Pages:%-10d Genre:%-10s \n",
b.getName(), b.getPages());
}
}
}
public class Book {
String name;
int pages;
int code;
static int total = 0;
public Book() {
pages = 0;
name = "";
code = -1;
}
public static void totalPages(int pages){
total += pages;
}
public int getPages(){
return pages;
}
public String getName(){
return name;
}
}
public class Novel extends Book {
public char genre;
public Novel(){
}
public char getGenre(){
return genre;
}
}
0 선더 (245) 스파이
0 골든 289 스파이
1 항공기 456 항공 "books.dat"파일에 생성 된 임의의 데이터 뒤에 250
0 유성 198 유머
1F ootball (434 개) 스포츠 (400)
1 골프 (432) 스포츠 (307)
나는이 출력을 원하는 :
이름 : 선더 페이지 : 245 장르 : 스파이
이름 : 골든 페이지 : 289 장르 : 스파이
이름 : 비행기 페이지 : 456 주제 : 항공 일러스트 : 250
이름 : Jocularity 페이지 : 198 장르 : 유머
이름 : 축구 페이지 : 434 제목 : 스포츠 일러스트 : 400
이름 : 골프 페이지 : 432 제목 : 스포츠 일러스트 : (307)
총 페이지 : 자바에서 2054
는 이유는'char'해야 않는 등? –