2013-10-13 34 views
-1

我的问题是如何使用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

+1

为什么它必须是一个'char'? –

回答

1

字符只能容纳一个字符。有2个替代在此情况下,

1)变型从炭为字符串类型的,以便它可以容纳多个字符,如幽默等

2)流派类型变化到char []

+0

使它成为一个数组?那么我会将每个单独的字母存储在新的数组索引中吗? – cupojava

+0

对,如果char []类型保存值[H,u,m,o,r]。你可以在索引的帮助下获得角色值。流派[0]会以'H'返回给你,流派[1]会以'u'返回给你。 –

0

是的,Scanner类(用于读取)提供了函数nextLine(),它返回String。这可能是你正在寻找的东西。当然,在这种情况下,文件“books.dat”的组织方式应使每个标题位于不同的行中。

其实我更喜欢DataInputStream所DataOutputStream类,有writeUTF()的readUTF()用于读取/写入字符串。

DataInputStream reader = new DataInputStream(new FileInputStrean(fileName)); 

然后

int a = reader.readInt(); 
String genre = reader.readUTF();