简体   繁体   中英

Reading from a txt file in Java

I'm taking a C course right now, but I also want to practice my work in Java as well. I'm having trouble reading from a file in Java (I want to get different types (double, int, etc..) from a file and store it in some variables. I know in C, the code would be like this:

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;
}

But what about in Java? I have done this so far but it doesn't work. I did get an output but the format wasn't what I wanted.

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);
    }
}

}

EDIT: Sorry guys, I forgot to include the txt file contents. I want my output just to be like this.

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

My output (In Java, and I'm just going to include some of them since they are quite long):

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();
}

change this to

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

And change

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

this to

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

If all you care about is printing the data, you might as well read everything as a string and simplify the code to:

while (scan.hasNextLine()) {
    String name, quantity, item_name, price;

    if(scan.hasNext()) {
        name = scan.next();
    }
    else ...

    if(scan.hasNext()) {
        quantity = scan.nextInt();
    } 
    else ...

    if(scan.hasNext()) {
        item_name = scan.next();
    }
    else ...

    if(scan.hasNext()) {
        price = scan.nextDouble();
    }
    else ...

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

The tab character, '\\t', makes the output look a little better. Where the else's are, you can set default values in case nothing is found.

If you actually care if something is an int or a double, you can just use the parse methods, ie

int int_quantity = Integer.parseInt( quantity );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM