Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

If you look at the API for Scanner, you will see a constructor that accepts a String as it's argument. The semantics of this constructor

If you look at the API for Scanner, you will see a constructor that accepts a String as it's argument. The semantics of this constructor is that the passed string is treated like an input source upon which you can then call the various Scanner methods: next, nextInt, etc. Thus, for example, if one had the file:

1 2 3 4 5 6 7 

one could read in a line at a time, and then using each line as an input source, you could then process the integers on each line.

The basic code structure of this technique is:

 Scanner fileScanner = new Scanner(new File(filename); while (fileScanner.hasNextLine() { // while there are lines left to read String line = fileScanner.nextLine(); // read next line of file Scanner lineScanner = new Scanner(line); // set up a Scanner to read the 'contents of the line'  // use lineScanner just like any other Scanner object // i.e., you can call all the hasNext and next methods  } 

This technique can be useful when one want to limit their processing of data to that on a single line of a file. Using next or nextInt doesn't work because those methods treat newlines like blanks (i.e., all whitespace is treated in the same fashion), so one doesn't know when the end of the line has been reached. While there are several ways of handling this, the above-described techique of reading in a line at a time using nextLine and then creating a new Scanner object from the resulting string returned is a fairly straightforward way of accomplishing this.

Write an application class, named LineScanner, that opens the file numbers.text and prints out the number of integers on each line of the file. Again, to accomplish this, read each line into a String using nextLine and then create a second Scanner object using that string as the contructor's argument.

The name of your class should be LineScanner.

For example, if the file numbers.text contains:

1 2 3 5 10 15 20 25 10 9 8 7 6 5 4 3 2 1 

the program should produce the following output:

 There are 3 numbers on line 1 There are 5 numbers on line 2 There are 0 numbers on line 3 There are 10 numbers on line 4

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Oracle Solaris 11.2 System Administration (oracle Press)

Authors: Harry Foxwell

1st Edition

007184421X, 9780071844215

More Books

Students also viewed these Databases questions

Question

What is A free product or gift?

Answered: 1 week ago