简体   繁体   中英

Scanner - managing input from text file

I'm working with java Scanner trying to extract product information from a text file called Inventory.txt.

This file contains data on products in this format:

“Danelectro|Bass|D56BASS-AQUA|336177|395.00Orange|Amplifier|BT1000-H|319578|899.00Planet Waves|Superpicks|1ORD2-5|301075|4.50Korg|X50 Music Synthesizer|X50|241473|735.00Alpine|Alto Sax|AAS143|198490|795.00”

I am trying to parse the strings and add them into an arraylist such that each element in the arraylist would look something like this:

"Danelectro|Bass|D56BASS-AQUA|336177|395.00"
"Orange|Amplifier|BT1000-H|319578|899.00"    
"KorPlanet Waves|Superpicks|1ORD2-5|301075|4.50"
"g|X50 Music Synthesizer|X50|241473|735.00"
"Alpine|Alto Sax|AAS143|198490|555.00”

Following is my code:

public class ItemDao {        
    public ItemDao() {
        scanFile();
    }

    public void scanFile() {
        Scanner scanner; 
        ArrayList <String> content = new ArrayList <String>();
        try {
            Pattern p1 = Pattern.compile("\\.[0-9]{2}$");
            scanner = new Scanner(new File("Inventory.txt"));

            while (scanner.hasNext(p1)) {
                content.add(scanner.next(p1));
            }

            for (String item : content) {
                System.out.println("Items:" + item);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

When I tested this code I found that the arraylist is empty. Any help would be much appreciated.

java -jar A00123456Lab5.jar

Create an ItemDAO class in a dao package This class will contain an static inner class which implements Comparator (DAO = Data Access Object)

You can define a Scanner on a String, and a delimiter. Since the | is used in regex as OR combinator, you have to mask it with (double)-backslash:

sc = new java.util.Scanner ("Danelectro|Bass|D56BASS-AQUA|336177|395.00");
sc.useDelimiter ("\\|");

String name = sc.next ();
// name: java.lang.String = Danelectro
String typ = sc.next ();
// typ: java.lang.String = Bass
String model = sc.next
// model: java.lang.String = D56BASS-AQUA
int id = sc.nextInt ();
// id: Int = 336177
val d = sc.nextDouble ();
// d: Double = 395.0

I see you're using a pattern, those can come in handy--but I'd just take each line and substring it.

while(scanner.hasNextLine()){
    String temp = scanner.nextLine();
    while(temp.indexOf("|") != -1){
        content.add(temp.substring(temp.indexOf("|"));
        temp.substring(temp.indexOf("|")+1);
    }    
}

Just a thought--might be easier to debug with this way.

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