我已经被这个代码困住了一段时间

时间:2021-03-07 04:25:28

标签: java class text-files

我的第一个代码源自应该打印的内容。我创建了一个构造函数,并使用了 setter 和 getter 来实现它。然后用一个 toString() 方法结束它。

图书类:

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.lang.*;
public class Book {
   
   // Initiate variables
   // Note: I used the DecimalFormat so every price is always going to have 2 decimal spaces
   private static DecimalFormat df2 = new DecimalFormat("#.##");
   private String ISBN;
   private String author;
   private String title;
   private int edition;
   private String pubCode;
   private int quantity;
   private double price;
   
   //constructor
   public Book(String isbn, String auth, String ti, int ed, String pc, int qty, double pr)
   {
      ISBN = isbn;
      author = auth;
      title = ti;
      edition = ed;
      pubCode = pc;
      quantity = qty;
      price = pr;
   }
   
   //getters
   public String getTitle(){return title;}
   public String getAuthor(){return author;}
   public double getPrice(){return price;}
   public int getEdition(){return edition;}
   public String getISBN(){return ISBN;}
   public String getpubCode(){return pubCode;}
   public int getQuantity(){return quantity;}
   
   //setters
   public void changePrice(double newPrice){price = newPrice;}
   public boolean changeQuantity(int changeAmt){
   changeAmt = quantity + changeAmt;
   if (changeAmt < 0) {
   return false;
   } 
   else {
   return true;
   }
   }

   //This prints out all of the information once the object 'Book' is used
   public String toString() 
   {
      String subAuthor = "";
      String subTitle = "";
      subAuthor = author.substring(0,16);
      subTitle = title.substring(0,32);
      return "ISBN: " +ISBN + "\nAuthor: " + subAuthor + "\nTitle: " + subTitle + "\nEdition: " + edition + "\nPublisher Code: " + pubCode + "\nQuantity: " + quantity + "\nPrice: $ " +df2.format(price) + "\n\n";
   }
}

然后我创建了一个名为 Inventory 的类来管理 Book 类的实例。但是,我仍然不确定我的大部分代码是否正确,因为我编译它没有任何错误。我的意思是构造函数本身、addBook 方法和 changeQuantity 方法。

构造函数接受一个参数,即书籍数组的大小。它应该创建指定大小的空数组,并将 nextEntry 字段初始化为 0。

addBook 用于将 Book 对象添加到由 nextEntry 字段指定的位置的 books 数组,nextEntry 字段增加 1,该方法应返回 true 作为成功的指示。如果数组已满,则没有空间添加新书,因此该方法返回 false 作为失败的指示。

changeQuantity 方法应该通过添加changeAmt(可能是正数或负数)来更新指定书籍的数量,除非更改会导致最终数量为负数。如果成功,该方法将返回 true,如果更改将导致负数量,则返回 false。

同样让我感到困惑的是,我需要通过遍历清单以找到匹配的 ISBN 字符串来识别正确的 Book 对象。我假设我需要使用 .equals() 方法,但我一直在尝试查看是否可以先打印所有内容,所以我还没有对其进行编码。

然后我使用printInventory 方法。这个方法应该打印整个库存,在每本书上使用 toString() 方法。

库存类:

import java.math.RoundingMode;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import java.util.Arrays;
public class Inventory {

   private Book[] books;
   private int nextEntry;
   int questionAmt;
   
   public Inventory(int size){
      size = 7; 
      books = new Book[size];
      nextEntry = 0; 
   }
   
   public boolean addBook(Book theBook) {
   if (nextEntry > 27)
   { return false;}
   else{
   nextEntry++;
   books[nextEntry] = theBook;
   return true;
   }
  }
   
   public boolean changeQuantity(String isbn, int changeAmt) {
      if (changeAmt < 0) {
         return false;
      } 
      else {
         return true;
      }
      }
   public void printInventory()
   {
   for  (int i=0; i<books.length; i++) {
   System.out.println(books[i].toString()); 
   
   return;
   }
   }

然后我添加了文本文件,称为库存。这是代码中应该显示的内容,我应该能够在控制台内编辑它的数量。我还添加了 28,因为它需要 28 本书。

库存.txt:

28
013478796X_Tony Gaddis_Starting Out with Java: From Control Structures through Data Structures_4_PE_10_121.75
0321409493_John Lewis_Java Software Solutions: Foundations of Program Design_5_AW_12_94.05
0023606924_Richard Johnsonbaugh_Algorithms_1_PH_1_109.00
0134743350_Harvey Dietel_Java: How to Program, Early Objects_12_PE_12_134.84
0131474340_Ralph Morelli_Java, Java, Java, Object-Oriented Problem Solving_3_PH_4_95.25
0596100469_Alex Martelli_Python in a Nutshell_2_OR_6_39.99
0134802217_Tony Gaddis_Starting Out with Java: From Control Structures through Objects_7_PE_8_118.67
1403946876_Sally Fincher_Studying Programming_1_PM_3_26.59
0596510047_Andy Oram_Beautiful Code: Leading Programmers Explain How They Think_1_OR_5_44.99
0143037889_Ray Kurzweil_The Singularity is Near: When Humans Transcend Biology_1_PG_20_17.70
0135205972_John Lewis_Java Foundations: Introduction to Program Design and Data Structures_5_PE_5_129.99
0131872893_Wanda Dann_Learning to Program with Alice_1_PH_12_47.50
159413962X_Dave Eggers_The Circle_1_AW_4_3.99
1887902996_John Zelle_Python Programming: An Introduction to Computer Science_1_FB_2_26.40
0133356728_Rafael Gonzales_Digital Image Processing_4_PE_3_248.17
1592400876_Lynne Truss_Eats, Shoots & Leaves_1_PG_5_17.70
0072823798_William Collins_Data Structures and the Java Collections Framework_2_MH_6_105.57
0072866098_Allen Tucker_Programming Languages: Principles and Paradigms_2_MH_1_127.50
0534950973_Michael Sipser_Introduction to the Theory of Computation_2_CT_3_98.90
0131496710_Francis Hill_Computer Graphics Using OpenGL 3rd Edition_3_PH_4_112.00
0321173486_Dave Shreiner_OpenGL Programming Guide_5_AW_1_24.00
0072865512_Steven Schach_Object Oriented and Classical Software Engineering_6_MH_9_123.44
0321228383_Michael Kifer_Database Systems: An Application-Oriented Approach_2_AW_3_112.86
1416587787_Cliff Stoll_The Cuckoo's Egg_1_PG_3_13.32
1400032717_Mark Haddon_The Curious Incident of the Dog in the Night-Time_1_VI_10_13.95
006025492X_Maurice Sendak_Where the Wild Things Are_1_HC_6_17.95
0694003611_Margaret Brown_Goodnight Moon_1_HC_138_8.99
069401298X_Arnold Lobel_Frog and Toad Together_1_HC_27_11.55

最后但并非最不重要的是,我制作了一个 InventoryTester 文件来读取文本文件并使用两个类的代码打印它。

库存测试器:

import javax.swing.JOptionPane;
import javax.swing.UIManager;
import java.awt.Font;
import java.util.Scanner;
import java.io.*;
public class InventoryTester {
   public static void main(String[] args) throws IOException {
      Scanner inFile= new Scanner(new File("inventory.txt"));
      Book books;
      String inLine= inFile.nextLine();
      int size= Integer.parseInt(inLine);
      Inventory myInventory= new Inventory(size);
      
      while (inFile.hasNext()) {
      inLine= inFile.nextLine();
      String ISBN = inFile.next();       
      String author = inFile.next(); 
      String title = inFile.next();
      int edition = inFile.nextInt();
      String pubCode = inFile.next();
      int quantity = inFile.nextInt();
      double price = inFile.nextDouble();
      myInventory.addBook(new Book(ISBN, author, title, edition, pubCode, quantity, price));
      String[] tokens  = inLine.split("_");
      myInventory.printInventory(); 
      }
      
      inFile.close();
      }
      }

我对这段代码的问题是我不断收到不匹配异常。

编辑:我完全忘记添加错误。对不起!

Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at InventoryTester.main(InventoryTester.java:22)
 

我试图让 Java 理解有字符串、整数和双精度数。它应该与我需要更改的数量一起打印,但我似乎看不到我是否有正确的代码来使这个错误以我的方式工作。

如果您能帮我解决这个错误,并且如果您能告诉我 Inventory 类是否正确完成,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

我假设你想在测试文件中做的是读取每一行,用 _ 分割它,然后通过构造函数将它分配给每个值。 但代码似乎没有这样做。

inLine= inFile.nextLine();

这会将整行读入 inLine。然后您在执行 infile.next 之后将读取下一行而不是同一行。 nextline 方法将指针移动到下一行
此外,您在末尾拆分该行,但未使用它,因此让我们读取一行,拆分它,然后逐个使用每个字符串。

这应该更适合您的用例:

while (inFile.hasNext()) {
inLine= inFile.nextLine();
String[] tokens  = inLine.split("_");
String ISBN = tokens[0];       
String author = tokens[1]; 
String title = tokens[2];
int edition = Integer.parseInt(tokens[3]);
String pubCode = tokens[4];
int quantity = Integer.parseInt(tokens[5]);
double price = Double.parseDouble(tokens[6]);
myInventory.addBook(new Book(ISBN, author, title, edition, pubCode, quantity, price));
      
myInventory.printInventory(); 
}