If you look at the API for Scanner, you will see a constructor that accepts a St
ID: 3709106 • Letter: I
Question
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:
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:
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:
the program should produce the following output:
Explanation / Answer
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LineSCanner {
public static void lineScanner(String fileName) throws FileNotFoundException{
File newFile = new File(fileName);
Scanner fileScanner = new Scanner(newFile);
int lineCount =1;
while(fileScanner.hasNext()){
String line = fileScanner.nextLine();
Scanner scanLine = new Scanner(line);
int count =0;
while(scanLine.hasNext()){
scanLine.nextInt();
count++;
}
System.out.println("There are " + count + " numbers in " + lineCount);
count =0;
lineCount++;
}
}
public static void main(String args[]) {
try {
lineScanner("numbers.text");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output
There are 3 numbers in 1
There are 5 numbers in 2
There are 0 numbers in 3
There are 10 numbers in 4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.