Yatish Bathla Yatish Bathla - 1 month ago 9
Java Question

How to parse int or double values from text file in java application

i want to copy specific value from text file to Arraylist in Java Application. This is my text file( which is stored in my desktop as test.text)

String name = carrot;
double unit_price = 200;
int unit = 10;


This value i want to store in Arraylist, which is present in my main application as follow:

package com.main;
import com.collection.Ingridient;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class FileReaderApp {


public static void main(String[] args) throws FileNotFoundException, IOException {
Ingridient i_one = new Ingridient();
ArrayList<Ingridient> db = new ArrayList<Ingridient>();
FileReader fin = new FileReader("/home/yati/Desktop/test");
Scanner src = new Scanner(fin);
// Read the ingridient from text file.
while (src.hasNext()) {
if (src.hasNext()) {
i_one.setName(src.next());
System.out.println("Name: " +src.next());
} else
if(src.hasNextDouble()) {
i_one.setUnit_price(src.nextDouble());
System.out.println("Unit Price: " +src.nextDouble());
}
else if (src.hasNextInt()) {
i_one.setUnit(src.nextInt());
System.out.println("Unit: " +src.nextInt());
} else {
System.out.println("File format error.");
return;
}
db.add(i_one);
}
fin.close();

}

}


Her, Ingridient class has following code:

package com.collection;
public class Ingridient {
String name;
Double unit_price;
int unit;

public Ingridient() {
name = null;
unit_price = null;
unit = 0;
}

public void setName(String name) {
this.name = name;
}

public void setUnit_price(Double unit_price) {
this.unit_price = unit_price;
}

public void setUnit(int unit) {
this.unit = unit;
}

}


My problem is that my application can store only name in Ingridient object and it cannot store any value in unit and unit_price. Obtained output is:
enter image description here
I know i am mistaking somewhere but i cannot solve this issue. Any Suggestion?

Answer

This should do it:

public static void main(String[] args) throws IOException {
    String content = "String name = carrot;\ndouble unit_price = 200;\nint unit = 10;";
    try (Scanner sc = new Scanner(content)) {
        sc.useDelimiter("(;*\n*.+ .+ = )|;");
        List<Incredient> incredients = new ArrayList<>();
        while (true) {
            Incrediend incredient = new Incredient();
            if (sc.hasNext()) {
                String name = sc.next();
                incredient.setName(name);
                System.out.println("Name: " + name);
            } else {
                break;
            }
            if (sc.hasNextDouble()) {
                double unitPrice = sc.nextDouble();
                incredient.setUnit_price(unitPrice);
                System.out.println("Unit Price: " + unitPrice);
            } else {
                break;
            }
            if (sc.hasNextInt()) {
                int unit = sc.nextInt();
                incredient.setUnit(unit);
                System.out.println("Unit: " + unit);
            } else {
                break;
            }
            incredients.add(incredient);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

This works because of the delimiter I've used (;*\n*.+ .+ = )|;. This pice of regex just removes all the parts of the text file that you're not interested in saving.

There are a couple of problems with your approach, for example this:

i_one.setName(src.next());
System.out.println("Name: " +src.next());

Here, you're reading 2 tokens from the scanner because there are 2 calls to next(), if you want to use the same token for multiple things you should create a new variable to store it in (ex: String name = sc.next()).

The default delimiter that the Scanner is using is a single space and because of that, in your code, hasNextDouble() and hasNextInt() will never be true, all the numbers in the text file end with ;.

I'm not sure what you're trying to do here, it is kind of unusual to parse java code from a text file. If you can change the format of the text file, you should chose one that is easier to parse (CSV for example).

Comments