Question

I have a file with following text:

  • Alan Alda 100 2
  • Coco Channel 103 2
  • Eric Edwards 105 0 ...

I should use only one method for read the first file and write this information to the second and count the number of lines which means borrowers and total books borrowed which is the last number in the line. OK So in my output are 3 empty lines for this text but count and total is good processed on following lines.I had no idea how to add last number only by give a variable to each String.

    input = new Scanner(inFile);
    output = new PrintWriter(outFile);
     ... 
    public void processFiles()
    { 
     while(input.hasNextLine())
     { 
          count++;
          String firstName = input.next();
          String lastName = input.next();
          String libraryNumber = input.next();
          total += input.nextInt(); 
          output.println(input.nextLine());//empty strings
       }
       output.println("number of borrowers"+count); //3
       output.println("number of books borrowed"+total); //2+2+0
       }
Was it helpful?

Solution

String firstName = input.next();
String lastName = input.next();
String libraryNumber = input.next();
total += input.nextInt(); 
output.println(input.nextLine());//empty strings

You read the first name, "Alan", The second name "Alda", The library number "100", and the next int, which is 2. Then, you read right up until the next carriage return.. which is the very next character. Because \n is stripped from the String that is found, you're going to be getting an empty line. If I were you, I would read the whole line in, parse the String itself and write it out.

Example

String line = input.nextLine();

String[] values = line.split(" ");

String firstName = values[0];
String secondName = values[1];
String libraryNumber = values[2];
total += Integer.parseInt(values[3]);

output.println(line);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top