我的问题是如何使用char字段来描述一个流派,如果流派是多个字符,如:间谍或幽默。由于字符只有1个字符,这是如何工作的?ArrayLists和char字段
我需要我的小说类中的char字段,它可以描述小说的流派。
以下之后我在一个文件中创建 “books.dat”
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航空随机数据我的代码250
0双目198幽默
1楼ootball 434个体育400
1高尔夫432体育307
我想这样的输出:
名称:雷霆万钧页数:245类型:间谍
名称:黄金眼页数:289类型:间谍
名称:飞机页数:456主题:航空插图:250
名称:Jocularity页数:198类型:幽默
名称:足球页数:434主题:体育插图:400
名称:高尔夫页数:432主题:体育插图:307
总页数:在java中2054
为什么它必须是一个'char'? –