java - 访问子级的数据并在父级测试类中使用它。

标签 java constructor dialog boolean joptionpane

我正在尝试使用小说代码的值,它是 Book 的子元素,而 book 也有另一个子非小说元素。以下是我到目前为止所得到的。我需要在 bookTest 文件中使用 children 的一些东西。

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;
}

 }

图书测试。 我在这里遇到问题,循环没有迭代,我认为问题已经结束,但不知道如何修复。

 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.

关于java - 访问子级的数据并在父级测试类中使用它。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36262104/

相关文章:

java - 我如何删除java中的数组条目(请简单一点?)

java - 如何在 ZK 中添加用于重定向的 Java 方法计时器

c# - C# 中的链式构造函数 - 使用中间逻辑

javascript - 为什么 SQL 语句将 "missing"列的值更新为 NULL?

java - 从项目 B 的 servlet 调用项目 A 的 bean

java - 我的类是 "Command"和 "Dispatcher"模式的示例吗?

c++ - 定义一个全局变量并在那里自己初始化它可以吗?

c++ - 如何显示可以设置注册表项权限的对话框

android - 我怎样才能把日期和时间选择器放在android的对话框中

java - 在 listView 中 onClick 之后创建一个对话框