-1

I have an input text file in the following format:

11111, "Top Secret Twenty One - Janet Evanovich", 8.99
22222, "W Is For Wasted - Sue Grafton", 9.95
33333, "Gray Mountain - John Grisham", 14.95
44444, "Revival - Stephen King", 12.95

How can I read in "1111" "Top Secret Twenty One - Janet Evanovich" and "8.99" as separate variables without the quotes and commas?

I'm basically trying to search the file for the bookID (aka "11111").

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • 1
    Have you tried something? Can you provide code? It is probably achievable by reading each line with `readline` and the searching for the appropriate result with `substring` and `indexOf` – Sir Celsius Sep 01 '14 at 19:11
  • Code shows what - Looked up `Reader.readLine`? `String.indexOf`? Using a loop? Running into a compiler error or a run-time exception? Unless this is a school assignment I would 1) not use Java (as there are better tools for the task) and/or; 2) use a CSV library. – user2864740 Sep 01 '14 at 19:11
  • Try reading http://stackoverflow.com/questions/101100/csv-api-for-java – ericbn Sep 01 '14 at 19:15

1 Answers1

0

This is the way I learned it in class:

import java.util.*; // for the scanner
import java.io.*; // for the object

File f = new File("<filename>");
Scanner input = new Scanner(f);

input.useDelimiter(",|\"|\n"); // delimiters are commas, quotes, and newlines

input.nextInt(); //reads 1111 as an integer
input.next(); // reads the empty space (needed because " " wasn't declared as a delimiter)
input.next(); // reads in Top Secret Twenty One - Janet Evanovich as a String.
input.next(): // reads in the empty space
input.nextDouble(); // reads in 8.99 as a double

To change the default delimiters of Java (spaces, tabs, newlines), I used the following:

Scannervariable.useDelimiter(",|\"|\n");

This command uses commas, quotes, and newlines as delimiters, ignoring them and moving onto the next token. The | means "or." You can use the following Scanner methods depending on what you are trying to read in:

next(), nextInt(), nextDouble(), or nextLine()

You can look up the exact function of each method online.

Amy
  • 301
  • 2
  • 9