简体   繁体   中英

Can someone help me to figure out how to read my file from ":" (not included) til the end of the line?

My exercise ask to open the file sales.dat, and read only the number part of every line. All of this using the Scanner class

i've tried with while loops, for loops and every other possible solution on my book but none works

public static void main(String[] args) {
        String nomeFile = "sales.dat";
        Scanner inputStream = null;
        System.out.println("Il file "+ nomeFile + "\ncontiene le righe seguenti:\n");

        try {
            inputStream = new Scanner(new File(nomeFile));
            inputStream.useDelimiter(":");
            while(inputStream.hasNext()) {
                String riga = inputStream.nextLine();
                System.out.println(riga);
            }
        } catch (FileNotFoundException e) {
            System.out.println("Errore nell'apertura del file " + nomeFile);
            System.exit(0);
        }

        inputStream.close();
    }
}

Expected: if line is San Francisco: 198870.32 it must read and print only 198870.32

Actual: San Francisco: 198870.32
        Chicago: no report received
        New York: 298734.12

Remove the line

inputStream.useDelimiter(":");

You may now read the whole line and then use split() .

String riga = inputStream.nextLine(); //San Francisco: 198870.32
System.out.println(riga.split(":")[1].trim());

this should give you 198870.32 .

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