【发布时间】:2019-04-03 15:27:50
【问题描述】:
这是我的家庭作业... “你是一家五金店的老板,需要保留一份清单,可以告诉你你有哪些不同的工具,你手头有多少工具,以及每个工具的成本。编写一个创建随机访问的程序文件“hardware.dat”。您的程序应该允许您输入每个工具的数据并将数据写入它创建的文件。使用以下信息开始您的文件:...“然后它给出了信息列表.
这些是我的作业。(下面的课程)第二个(硬件课程)我对此没有任何问题,但我只是想确保它是正确的。 但是我在第一个链接中遇到了 RandomAccessFile 的问题。我不知道我是否做得对。每当我将鼠标悬停在“import java.io.RandomAccessFile;”上时,它一直说“RandomAccessFile 已在此编译中定义”这意味着什么?? (如果没有包含代码,我无法粘贴链接) 我做错了什么?
RandomAccessFile 类:
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Scanner;
public class RandomAccessFile {
public static void main(String[] args)
{
RandomAccessFile file;
Scanner sc = new Scanner(System.in);
int toolId;
String toolName;
int quantity;
double cost;
System.out.println("Please Input Tool ID: ");
toolId = sc.nextInt();
System.out.println("Please Input Tool Name: ");
sc.nextLine();
toolName = sc.nextLine();
System.out.println("Please Input the Quantity: ");
quantity = sc.nextInt();
System.out.println("Please Input the Price: ");
cost = sc.nextDouble();
try
{
file = new RandomAccessFile(new File("hardware.dat"), "rw");
long FileSize = file.length();
file.seek(FileSize);
file.writeInt(toolId);
file.writeUTF(toolName);
for(int i = 0; i < 24- toolName.length(); i++)
{
file.writeByte(24);
}
file.writeInt(quantity);
file.writeDouble(cost);
System.out.println("Item added to inventory");
file.close();
}
catch (FileNotFoundException e)
{
System.err.println("File not found. Check Project Folder and if you have read and write permissions to it");
}
catch (IOException e)
{
e.getStackTrace();
}
}
}
硬件类:
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.FileNotFoundException;
public class Hardware
{
private static final int RECORD = 24;
public static void main(String[] args)
{
RandomAccessFile file;
int toolId = 0;
String toolName = null;
int quantity = 0;
double cost = 0.00;
try
{
file = new RandomAccessFile(new File("hardware.dat"), "rw");
long FileSize = file.length();
file.seek(0);
long NUMRecords = FileSize / RECORD;
for (int j = 0; j < NUMRecords; j++)
{
toolId = file.readInt();
toolName = file.readUTF();
for (int i = 0; i < 24- toolName.length(); i++)
{
file.readByte();
}
quantity = file.readInt();
cost = file.readDouble();
System.out.println("Tool ID: " + toolId + " Tool Name: " + toolName + " Quantity: " + quantity + " Cost: $" + cost);
}
file.close();
}
catch (FileNotFoundException e)
{
System.err.println("File not found. Check Project Folder and if you have read and write permissions to it");
}
catch (IOException e)
{
e.getStackTrace();
}
}
}
【问题讨论】:
标签: java randomaccessfile