0

I was wondering how to go about reading a file, and scanning each line, but separating the contents of each line into a Char variable and into a Double variable.

Example:

Let's say we write a code that opens up text file "Sample.txt". To read the first line you would use the following code:

 while(fin.hasNext())
         {

            try{

                inType2 = fin.next().charAt(0);

                inAmount2 = fin.nextDouble();
           }

This code basically says that if there is a next line, it will put the next char into inType2 and the next Double into inAmount2.

What if my txt file is written as follows:

D    100.00
E    54.54
T    90.99

How would I go about reading each line, putting "D" into the Char variable, and the corresponding Double or "100.00", in this example, into its Double variable.

I feel like the code I wrote reads the following txt files:

D
100.00
E
54.54
T
90.99

If you could please provide me with an efficient way to read lines from a file, and separate according to variable type, I'd greatly appreciate it. The Sample.txt will always have the char first, and the double second.

-Manny

Manny
  • 71
  • 1
  • 1
  • 11
  • Read a line into a `String` and then split on whitespace. – Tim Biegeleisen Oct 14 '15 at 01:27
  • how about making the txt file as a csv, read till the next \n and then split the string by comma and parse the data into the respective types – KennethLJJ Oct 14 '15 at 01:27
  • Have a look at http://stackoverflow.com/questions/33104575/input-mismatch-error/33104835#33104835. After split as per the post, instead on converting to int array, parse elements as per your use case. – Ravindra babu Oct 14 '15 at 01:28
  • I'm sorry guys, I'm trying to avoid all these methods. I don't want the whitespaces to dictate where to split the lines, matter of fact, I don't want to split the lines. I want the code to read the first Char in the line, then continue within the same line until it hits a Double. Then they get put into their respective variables. I really hope I'm making sense. Appreciate your help!! – Manny Oct 14 '15 at 01:42

2 Answers2

1

Use BufferedReader to read line, and then split on whitespace.

while((line=br.readLine())!=null){
    String[] arry = line.split("\\s+");
    inType2 = arry[0];
    inAmount2 = arry[1];
}
Kerwin
  • 1,212
  • 1
  • 7
  • 14
0

You can delimit by whitespace and

    Scanner scanner = new Scanner(new File("."));
    while (scanner.hasNext()) {

        //If both on different lines
        c = scanner.next().charAt(0);
        d = scanner.nextDouble();

        //if both on same line
        String s = scanner.next();
        String[] splits = s.split("\\s+");
        if (splits.length == 2) {
            c = splits[0].charAt(0);
            d = Double.parseDouble(splits[1]);
        }
    }
    scanner.close();
Saravana
  • 12,647
  • 2
  • 39
  • 57