java—从子级访问数据并在父测试类中使用

c90pui9n  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(280)

我试图利用小说的价值代码,这是书的孩子和书也有另一个孩子非小说。下面是我到目前为止所做的。我需要使用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;
}

 }

书本测试。我有一个问题在这里,循环不是通过迭代,我认为问题在这里,但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);

}
}
szqfcxe2

szqfcxe21#

请你也这样做,
在外面的某个地方,

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-fiction 以及 Fiction 那么这个呢 instanceof 检查有助于更好地控制 ClassCastException .

相关问题