使用插入算法将对象从一个数组复制到另一个数组的 "beginning"

Copy Object from one array to the "beginning" of another array using Insert Algorithm

我被分配了开发一个简单的 Java 程序的任务,该程序基于以下内容:

Write an algorithm to search for reserved book copies, from a list (array) of books using Linear Search, and then store them at the beginning of a newly created array, using an insert algorithm.

我已经编写了算法,但由于以下代码的最后一行有问题,我正在努力演示它:

package javaapplicationadt2;

public class Books
{

    public String ISBN;               // class properties
    public String title;
    public int copies;
    boolean reserved = true;

    public static void main(String[] args)
    {

        Books[] Book1 = new Books[1];
        Books[] Book2 = new Books[1];

        Book1[0].ISBN = "ISBN-00001";
        Book1[0].title = "Algorithms that torture minds";
        Book1[0].copies = 2;
        Book1[0].reserved = true;

        Book2[0].ISBN = "ISBN-00002";
        Book2[0].title = "Lecture Slides that defied practical Java Programming !";
        Book2[0].copies = 1;
        Book2[0].reserved = false;

        for (int i = 0; i < Book1.length; i++)
            if (Book1[i].reserved = true)
                for (int j = Book2.length - 1; j > 0; j++)
                    Book2[j] = Book2[j - 1];
     *Book2[0] = Book1[i].title;*   **(Incompatible types:
    Books cannot be converted to a String)**

    }
}

你的逻辑和代码约定有很多错误

Java 使用 CamelCase 作为编写方法、变量、classes、包和常量名称的惯例。 Class 名称应为名词,大小写混合,每个内部单词的首字母大写。接口名称也应该像 class 名称一样大写。看看Java Code conventions

Book[] bookArray = new Book[1];

回到你的代码。当你做

Book[] book1 = new Book[1]; //Create an Array of Books -> all elements are NULL
book1[0].ISBN = "ISBN-00001"; // book1[0] is NULL so a NullPointException will be throw

你必须初始化你的数组and/or分配一个对象给它

Book[] bookArray = new Book[1];
Book book = new Book();
Book[0] = book; //Now you have an Object Book at Book[0] and you can set the properties    
bookArray[0].ISBN = "ISBN-00001";

For和If...如果你不定义块,只会执行下一行。即

 if(true == bookArray[0].reserved)
     System.out.println("1");//This will be executed only if condition is true
     System.out.println("2"); //This will be executed no matter what

如果您只想在条件为真时执行代码,您必须:

if(true == bookArray[0].reserved){
     System.out.println("1");//This will be executed only if condition is true
     System.out.println("2"); //This will be executed only if condition is true
}