gpt4 book ai didi

java - 从Java中读取一个txt文件

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

我现在正在学习 C 类(class),但我也想用 Java 练习我的工作。我在 Java 中读取文件时遇到问题(我想从文件中获取不同类型(double、int 等)并将其存储在一些变量中。我知道在 C 中,代码将是这样的:

int main(void) {

FILE* fp;
char name[29];
int qty;
char item[20];
float price;

fp= fopen("input.txt","r");
if (fp == NULL) {
printf("Couldn't open the file.");
return;
}

while (fscanf(fp, "%s %d %s %.2f\n", name, &qty, item, &price) != NULL) {
// do something
}

return 0;
}

但是在 Java 中呢?到目前为止,我已经这样做了,但没有用。我确实得到了输出,但格式不是我想要的。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main_Class {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = null;
try {
scan = new Scanner(new File("input.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

while (scan.hasNextLine()) {
String name = "";
int quantity = 0;
String item_name = "";
double price = 0.0;

if(scan.hasNext()) {
name = scan.next();
}
if(scan.hasNextInt()) {
quantity = scan.nextInt();
}
if(scan.hasNext()) {
item_name = scan.next();
}
if(scan.hasNextDouble()) {
price = scan.nextDouble();
}
System.out.println(name + " " + quantity + " " + item_name + " " + price);
}
}

}

编辑:对不起大家,我忘了包含 txt 文件内容。我希望我的输出就像这样。

Smith 3 Sweater $22.50
Reich 3 Umbrella $12.50
Smith 1 Microwave $230.00
Lazlo 1 Mirror $60.00
Flintstone 5 Plate $10.00
Lazlo 1 Fridge $1200.00
Stevenson 2 Chair $350.00
Smith 10 Candle $3.50
Stevenson 1 Table $500.00
Flintstone 5 Bowl $7.00
Stevenson 2 Clock $30.00
Lazlo 3 Vase $40.00
Stevenson 1 Couch $800.00

我的输出(在 Java 中,我只包含其中的一些,因为它们很长):

Smith 3 Sweater 0.0
$22.50 0 Reich 3.0
Umbrella 0 $12.50 0.0
Smith 1 Microwave 0.0
$230.00 0 Lazlo 1.0
Mirror 0 $60.00 0.0
Flintstone 5 Plate 0.0
$10.00 0 Lazlo 1.0

最佳答案

if(scan.hasNextDouble())
{
price = scan.nextDouble();
}

将此更改为

 price = Double.parseDouble(scan.next().substring(1));

并改变

 System.out.println(name + " " + quantity + " " + item_name + " " +    price);

这个给

 System.out.println(name + " " + quantity + " " + item_name + " $" +    price);

关于java - 从Java中读取一个txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28486981/

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