我试图使用小说代码的价值,这是Book的孩子,而book也有另一个孩子Non-fiction。以下是我到目前为止的内容。我需要在bookTest文件中使用来自子级的东西。

public class Fiction extends Book
{
private String fictionCode;
private boolean signedByAuthor;

public boolean isSignedByAuthor()
{
    return signedByAuthor;
}

public void setSignedByAuthor(boolean signedByAuthor)
{
     if (signedByAuthor == true)
    {
         this.signedByAuthor = signedByAuthor;
    }
     else
     {
         return;
         }
}

public Fiction()
{
    super();
    setFictionCode("");
}

 public Fiction(String title, String author, String isbn, Publisher publisher,  double price, String fictionCode,  int quantity,Date datePublished)
{
super(title, author,isbn, publisher, price, quantity,datePublished);
setFictionCode(fictionCode);
}

 public void setFictionCode(String fc)

 {
    fictionCode = fc;
 }

 public String getFictionCode()

 {
    return fictionCode;
 }


 public double calculateCharge()
 {
     double charge = this.getPrice();
     if (signedByAuthor == true)
     {
         charge = this.getPrice()+ 20 ;
     }
     else
     {
         return charge;
     }

    return charge;

 }


 public String toString()

{
return(super.toString() + " Fiction Code " + fictionCode);
}


public String printInvoice()
{
    return null;
}

 }


BookTest。
我在这里有一个问题,循环没有遍历,我认为问题在这里,但idk如何解决。

 Fiction f = (Fiction) book;

 if(f.isSignedByAuthor())


BookTest Java

 import java.io.*;
 import java.io.FileNotFoundException;
 import java.io.FileWriter;
 import java.io.IOException;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Formatter;
  import java.util.Scanner;

import javax.swing.JOptionPane;

public class BookTest
{

private static final Fiction Book = null;


public static void main (String[] args)
{

ArrayList <Book>list = createInstances();

writeFile(list);
}


public  static ArrayList<Book> createInstances()
{
ArrayList<Book> bookArray = new ArrayList<Book>();
String inputArray[] = new String [10];
int i = 0;
Scanner input;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

// Read the text file and stores into inputArray where each line is stored as String.
try
{
    input = new Scanner( new File("book.txt"));
    input.useDelimiter("\n");
    while (input.hasNext()){
        inputArray[i]=input.next();
        i++;
    }

    // dataArray defines the two dimensional array that store all the values in the line.
    String dataArray [] [] = new String [10] [11];

    for (int k =0; k<inputArray.length; k++)
    {
        String getLine = inputArray[k];
        String[] eachLine =getLine.split(" ");
        int length = eachLine.length;


    for ( int j=0; j<length;j++)
          {
             dataArray [k][j]= eachLine[j];
         }
    }

    for (int l = 0; l < 10; l++)

        {
            if (dataArray[l][0].equals("Fiction"))


            {
                Publisher p = new Publisher(dataArray[l][3], dataArray[l][4]);

                String[] dateSplit = (dataArray[l][10]).split("/"); // splits the date (eg. 01/1/2015 to array containg 01, 1, 2015
                Date date = new Date(Integer.parseInt(dateSplit[0]), Integer.parseInt(dateSplit[1]),Integer.parseInt(dateSplit[2]));

                bookArray.add(new Fiction(dataArray[l][1], dataArray[l][2], dataArray[l][5],
                p, Double.parseDouble(dataArray[l][6]), dataArray[l][7], l, date));
            }

            else
            {  NonFiction.CategoryCode categoryCode = NonFiction.CategoryCode.valueOf(dataArray[l][7]);
                Publisher p = new Publisher(dataArray[l][3], dataArray[l][4]);
                String[] dateSplit = (dataArray[l][9]).split("/");
                Date date = new Date(Integer.parseInt(dateSplit[0]), Integer.parseInt(dateSplit[1]),Integer.parseInt(dateSplit[2]));
                bookArray.add(new NonFiction(dataArray[l][1], dataArray[l][2],dataArray[l][5],
                p, Double.parseDouble(dataArray[l][6]), categoryCode, l,date));
            }
        }

}

catch (FileNotFoundException e)
{

    e.printStackTrace();
}
return bookArray;
}


public static void writeFile(ArrayList<Book> arrayOfBook)
{
Formatter output ;

try
{
     output = new Formatter("updatebooks.txt");

        for ( Book t : arrayOfBook)
        {
        output.format("%s %s %s %s %s %s %s %s %s %s \n \n","Title:", t.getTitle(),"        Author:", t.getAuthor(),"       ISBN:", t.getIsbn(),"       Publisher:",t.getPublisher(),"      Price:",t.getPrice());
        }
        output.close();
        } catch (IOException e)
        {
            e.printStackTrace();
        }



 int count = 0;
 String message = "";
for (Book book : arrayOfBook )
{
    if( Book instanceof Fiction)
    {
    Fiction f = (Fiction) book;

    if(f.isSignedByAuthor())
     {
         count++;
     }
    message += String.format("%s %s \n","p ", f.isSignedByAuthor());
   }

 }

JOptionPane.showMessageDialog(null, "Total Signed Fiction : " + count);;
System.out.println(count);


}
}

最佳答案

请同样做

for..loop之外的某个地方,

       int count = 0;

     ....


    String message = "";
    for (Book book : arrayOfBook )
    {
        if( book  instanceof Fiction){
         Fiction f = (Fiction) book;
          if(f.isSignedByAuthor()){
                 count++;
          }
         message += String.format("%s %s \n","p ", f.isSignedByAuthor());
        }
  } // end of for loop
    JOptionPane.showMessageDialog(null, "Total Signed Fiction : " + count);


如果book引用变量引用Fiction对象,则book instanceof Fiction返回true,在这种情况下,只需要向下转换,以使ClassCastException正确覆盖。

如果您的数组同时包含对象Non-fictionFiction的类型,则此instanceof检查将有助于更好地控制ClassCastException

10-06 14:00