使用Java编辑文本中的记录



我目前遇到一个问题,当我运行代码并且没有使用用户输入的ID更新文本文件时,它会给我一个错误。

有关于如何修复的想法吗?

我知道我的代码没有main,因为将构造函数调用到另一个包含main的java文件中。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class Update {
public static Scanner x;
public void update() {
Scanner input = new Scanner(System.in);
String filepath = "Item.txt";
System.out.println("Enter the ID of the item");
int editTerm = input.nextInt();
int newID = editTerm;
System.out.println("Enter the description of the Item");
String newDescription = input.nextLine();
System.out.println("Enter the current price of the item");
double newunitPrice = input.nextFloat();
System.out.println("Enter the current amount of stock");
int newqtyinStock = input.nextInt();
double newtotalPrice = newunitPrice * newqtyinStock;

editRecord(filepath,editTerm,newID,newDescription,newunitPrice,newqtyinStock,newtotalPrice);
System.out.println(newID + "," + newDescription + "," + newunitPrice + "," + newqtyinStock + "," + newtotalPrice + " has been updated on the system");

}

public static void editRecord(String filepath, int editTerm, int newID, String newDescription, double newunitPrice, int newqtyinStock, double newtotalPrice)
{   
String tempFile = "temp.txt";
File oldFile = new File(filepath);
File newFile = new File(tempFile);
int ID = 0; String Description = ""; double unitPrice = 0.0; int qtyinStock = 0; double totalPrice = 0.0;
try
{
FileWriter fw = new FileWriter(tempFile, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filepath));
x.useDelimiter("[,n]");

while(x.hasNext())
{
ID = x.nextInt();
Description = x.next();
unitPrice = x.nextFloat();
qtyinStock = x.nextInt();
totalPrice = x.nextFloat();

if(ID == editTerm)
{
pw.println(newID + "," + newDescription + "," + newunitPrice + "," + newqtyinStock + "," + newtotalPrice);
}
else
{
pw.println(ID + "," + Description + "," + unitPrice + "," + qtyinStock + "," + totalPrice);
}

}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File (filepath);
newFile.renameTo(dump);
}
catch (Exception e)
{
System.out.println("Error");
}
}

}

在while循环中更改为:

while(x.hasNext())
{
ID = x.nextInt();
Description = x.next();
unitPrice = x.nextDouble();
qtyinStock = x.nextInt();
x.next()
totalPrice = unitPrice  * qtyinStock;

if(ID == editTerm)
{
pw.println(newID + "," + newDescription + "," + newunitPrice + "," + 
newqtyinStock + "," + newtotalPrice);
}
else
{
pw.println(ID + "," + Description + "," + unitPrice + "," + 
qtyinStock + "," + totalPrice);
}

}

最新更新