【发布时间】:2015-02-12 20:18:50
【问题描述】:
我现在正在学习 C 课程,但我也想在 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
【问题讨论】:
-
你得到了什么?你想要什么?
-
您想要的格式是什么?
-
$22.50 不是双倍,您必须将其解析为字符串并去掉符号。
-
对不起,我编辑了帖子。