gpt4 book ai didi

java - 无法打印 bin 文件中的数据

转载 作者:太空宇宙 更新时间:2023-11-04 11:35:37 25 4
gpt4 key购买 nike

我尝试编写这段代码,它基本上可以工作。但是,当我希望程序打印已输入的数字(在最后部分)时,程序不想这样做。我做错了什么?我该如何解决它?

public static void main(String[] args)
{
FileOutputStream outChannel = null;
DataOutputStream numberChannel = null;
Scanner kb = new Scanner(System.in);
int sum = 0;
int count = 0;
int highest = 0;
int number = 0;
String name = "";
try
{
System.out.println("Enter the name of the binary file: ");
name = kb.nextLine();
outChannel = new FileOutputStream(name);
numberChannel = new DataOutputStream(outChannel);
System.out.println("Enter negative value to stop.");
System.out.println("Enter scores: ");
while(true)
{
number = kb.nextInt();
if(number <0)
break;
numberChannel.writeInt(number);
sum+=number;
count++;
if(number>= highest)
highest = number;

}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
catch(IOException e)
{
System.out.println("Cannot write file");
}
finally
{
Scanner fileReader = new Scanner(name);
while(fileReader.hasNextInt())
{
System.out.println(number);
}

fileReader.close();

System.out.println("Average: " + ((double)sum/(double)count));
System.out.println("Highest: " +highest);
try
{
if (numberChannel!= null)
numberChannel.close();
}
catch(IOException e)
{

}
}
}

感谢所有帮助!

最佳答案

根据我给出的评论,使用 PrintWriter 写入文件,如下所示:

PrintWriter writer = new PrintWriter(new File(name));
writer.println(number);

并使用扫描仪从文件中读取数据,如下所示:

Scanner fileReader = new Scanner(new File(name));
while (fileReader.hasNextLine()) {
String nu = fileReader.nextLine();
System.out.println(nu);
}

您的代码的编辑版本:

public static void main(String[] args) throws IOException {
FileOutputStream outChannel = null;
DataOutputStream numberChannel = null;
Scanner kb = new Scanner(System.in);
int sum = 0;
int count = 0;
int highest = 0;
int number = 0;
String name = "";
try {
System.out.println("Enter the name of the binary file: ");
name = kb.nextLine();
PrintWriter writer = new PrintWriter(new File(name));
System.out.println("Enter negative value to stop.");
System.out.println("Enter scores: ");
while (true) {
number = kb.nextInt();
if (number < 0) {
break;
}
writer.println(number);
sum += number;
count++;
if (number >= highest) {
highest = number;
}

}
writer.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} finally {
Scanner fileReader = new Scanner(new File(name));
while (fileReader.hasNextLine()) {
String nu = fileReader.nextLine();
System.out.println(nu);
}

fileReader.close();

System.out.println("Average: " + ((double) sum / (double) count));
System.out.println("Highest: " + highest);
try {
if (numberChannel != null) {
numberChannel.close();
}
} catch (IOException e) {

}
}
}

关于java - 无法打印 bin 文件中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43328189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com