整个代码部分未激活.相信这可能与类型转换有关



我正在编写一些代码,这些代码应该打印出符合标准的书籍列表。但问题是,在书本上,代码已经到了检查和打印匹配项的循环开始的地步。然后跳过整个循环。我测试了这个循环,看看它是否在运行,但似乎不是。

public static void main(String[] args) throws FileNotFoundException {
    int count;
    count = 0;
    Book bookList [] = new Book[100];
    File file = new File("books.txt");                                  //assigns file
    Scanner textScan = new Scanner(file);                               //opens scanner to file
    do{
        String newType = textScan.nextLine();
        if(newType.equals("TradeBook")){
            bookList[count] =
                    new Tradebook(textScan.next(), textScan.next(),
                            textScan.nextInt(), textScan.nextDouble(), textScan.next());
        }
        else if(newType.equals("TextBook")){
            bookList[count] =
                    new Textbook(textScan.next(), textScan.next(),
                            textScan.nextInt(), textScan.nextDouble(), textScan.next());
        }
        count++;
    }while(textScan.hasNextLine());
    textScan.close();
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter your Major: ");
    String major = scan.next();
    String courseList [] = new String[10];
    count = 0;
    int sentinal = 0;
    do{
    System.out.println("Enter a course name: (xxx to quit): ");
    String temp = scan.next();
    if(temp.equals("xxx")||temp.equals("XXX")){
        sentinal = 1;
    }
    else{
    courseList[count] = temp;
    count++;
    }
    }while (sentinal != 1);
    scan.close();
    double retailSum = 0;
    double bookPrice = 0;
    System.out.println("List of textbooks: ");
    NumberFormat fmt = NumberFormat.getCurrencyInstance();  //POST: converts numbers into currency form
    for(int n = 0; n<11; n++){
        for (int x=0;x<11;x++){
            if (bookList[x] instanceof Textbook){
                String newCourse = ((Textbook) bookList[x]).getCourse();
                String courseName = courseList[n];
                if(newCourse.equals(courseName)){
                    bookPrice = ((Textbook) bookList[x]).retailPrice();
                    System.out.printf("%-10s bbbsd  %-10s  %-10s  %-10s n",
                            ((Textbook) bookList[x]).getCourse(),((Textbook) bookList[x]).getTitle(),
                            ((Textbook) bookList[x]).getAuthor(),fmt.format(bookPrice));
                    retailSum = retailSum + bookPrice;
                }
            }
        }
    }
    System.out.printf("Sum of retail book Prices: %-40sn", fmt.format(retailSum));

这是我得到的输出

教材清单:零售书籍价格之和:0.00美元

如果您的books.txt文件与代码预期的一样,那么您的代码就会工作:

books.txt

TextBook
Title1 Author1 1 1 Course1
TradeBook
Title2 Author2 2 2 Course2
TextBook
Title3 Author3 3 3 Course3

我用上面的books.txt文件运行了你的程序,它的行为与我预期的完全一样。

最新更新