2

I am hitting a wall in trying to read strings from command line with Scanner. My program should accept three book infos: book title and the number of pages. Those infos should be store in a file then read. The intention is to show only books with more that 100 pages.

After playing a while I manage to be get is works, but only if I enter the name of the book without spaces. If it type the book title with space I got error. I have been trying to fix the issue setting a delimiter, but not much luck with it.

'''

/*
 *
 * FILE: booklist.java
 * 
 *
*/

import java.io.*;
import java.util.*;

class Libri {
   //Variabili membro
   private String titolo;
   private int pagine;
    
   //Costruttore
   Libri (String a, int b) {
    this.titolo = a;
    this.pagine = b;
   }

   //Metodi
   public String toString() {
    return this.titolo + " " + this.pagine;
   }

   String getTitolo() {
    return this.titolo;
   }

   int getPagine() {
    return this.pagine;
   }

} // Fine classe libri


class SortByPagine implements Comparator<Libri> {
   public int compare(Libri a, Libri b) {
    return Integer.compare(a.getPagine(), b.getPagine());
   }
    
} // Fine classe SortByPagine

class booklist {
 public static void main(String args[]) {
   // Definizione variabili
    String titoloLibro = "";
    int numeroPagine = 0;
    boolean append = false;
    File fileX = new File("C:\\Users\\loremac13\\Documents\\Esercizi\\Lez14\\Testout.txt");

    try (FileReader fr = new FileReader(fileX); FileWriter fw = new FileWriter(fileX, append)) {
        // Definizione Scanner per lettura dati libri ed ArrayList
        Scanner scn = new Scanner(System.in);
        //scn.useDelimiter("\n");
        ArrayList<Libri> alB = new ArrayList<>();
        Libri catalogo;
    
        for (int a=0; a<3; a++) {
            // Richiesta dati ad utente
            System.out.println("PLEASE PROVIDE THE BOOK TITLE AND PRESS ENTER");            
            titoloLibro = scn.next();
            fw.write(titoloLibro + "\n");
            System.out.println(titoloLibro);
            System.out.println("PLEASE PROVIDE NUMBER OF PAGES AND PRESS ENTER");       
            numeroPagine =  scn.nextInt();
            fw.write(numeroPagine + "\n");                  
            System.out.println(numeroPagine);
            catalogo = new Libri(titoloLibro, numeroPagine);
            alB.add(catalogo);
        } // Fine ciclo for
        scn.close();
        fw.close();

    System.out.println("THE BOOK CATALOGUE CONTAINS:" + alB + " TOTAL NUMBER OF BOOKS:" + alB.size());

    Scanner src = new Scanner(fr);
            
    // Imposto demilitatore personalizzato -ACCAPO-
    src.useDelimiter("\n");
        
    // Creo ArrayList per contenere i libro con più di 100 pagine.
    ArrayList<Libri> alBFiltrato = new ArrayList<>();
            
    System.out.println("\n IL FILE CONTIENETE:");

    while (src.hasNextLine()) {
        String name = src.next();
        int number = src.nextInt();
        src.nextLine();
        System.out.println(name + " and " + number);
            if (number >= 100) {
                Libri catalogoFiltrato = new Libri(name, number);
                alBFiltrato.add(catalogoFiltrato);
            } // fine if numeroPagine           

    } // Fine While loop
    src.close();
    System.out.println("BOOKS WITH AT LEAST 100 PAGES:" + alBFiltrato + "TOTAL NUMBER OF BOOKS:" + alBFiltrato.size());
            
    // Ordino lo array list in base al numero di pagine.
    Collections.sort(alBFiltrato, new SortByPagine());
    System.out.println("BBOKS WITH AT LEST 1OO PAGES - SORTED BY PAGES:" + alBFiltrato);
                
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
} // Fine main
} // Fine classe booklist
'''
2
  • what line in your code gives error ? Commented Nov 24, 2020 at 17:51
  • I getting Exception in thread "main" java.util.inputMismatchException. I have changed the line titoloLibro = scn.next(); with titoloLibro = scn.nextLine(); this let me enter the book title with spaces, but then i got an issue in entering the pages of the book, and this is as far i could go. Commented Nov 24, 2020 at 18:10

1 Answer 1

1

If you need to read book's title that contains spaces then you may use method nextLine().

titoloLibro = scn.nextLine();

API docs: "Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line."

If you get "an issue in entering the pages of the book", then add one more call of nextLine() after you read pages. It must consume the end-of-line character remaining after reading the integer number of pages.

numeroPagine =  scn.nextInt();
scn.nextLine();
Sign up to request clarification or add additional context in comments.

2 Comments

It works!, I did add the scn.nextLine(); as you suggested aftert the numeroPagine = scn.nextInt(); and it works!!! How did you understand it?
I had a similar problem before. Methods such as nextInt() leave line separator, so you need to read it explicitly and throw away.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.