News Ticker

Menu

Scanner Practice in Java

Rationale

Reading data from stored files is an essential skill. Reading from arbitrary sources such as the user, a string, or a network location usually follows a similar pattern to reading from files. Completing this lab will illustrate how Java's Scanner class provides a uniform mechanism to read from a variety of sources. To complete the lab, one must understand several key elements surrounding Scanner input:

  • How to notify the compiler that a Scanner will be used in your code by using an import statement
  • How to create a Scanner which reads from a String and from a File existing on disk
  • Which methods Scanner provides to read tokens from the input stream. For example, find out which method reads a single word as a string and which method reads a number as an integer.
  • Which methods Scanner provides to check if a particular type of token appears next in the input stream, for example if the next token is a real number.
  • How to determine if there is any input left in the input stream.
Processing data also requires mastery of basic programming concepts such as iteration, conditional execution, and function declaration which will be reinforced here. Finally, this lab illustrates how one central function can facilitate a variety of tasks by writing short functions that pass the central function appropriate arguments.

Class Setup: ScannerPractice

Create a class called ScannerPractice in a file called ScannerPractice.java which you will need to create. This class will contain several methods which will be tested. You may want to copy the skeleton of the class (found below) into your file to get started but know that you'll need to add method bodies to get the skeleton to compile. You may add a main() method and use it for testing your own functions and additionally any other helper functions you might find useful. Just make sure that all the required methods are present.

The ScannerPractice class at a minimum must have the following class structure.

// Contains some simple parsing functions for reading from Scanners,
// Strings, and Files
public class ScannerPractice{

  // Accept a Scanner argument and read space-separated words from
  // it. If a word is a valid real number such as 0.1 or -3.14159 or
  // 87 then add the number onto a running total.  When there is no
  // more input available in the scanner, return the total.
  public static double sumReals(Scanner input);

  // Perform the same computation as sumReals(Scanner) except parse
  // the given string for real numbers.  You will need to create a new
  // Scanner which reads from parameter String.  It may be useful to
  // use employ sumReals(Scanner) in this function.
  public static double sumReals(String parseString);

  // Perform the same computation as sumReals(Scanner) except read
  // from the file named by the parameter filename.  The actual file
  // with the text should already be stored on disk. Some sample files
  // are stored in wordsNnumbers1.txt and wordsNnumbers2.txt.  This
  // function may throw an exception if the named file does not
  // exist. It may be useful to use the function sumReals(Scanner).
  public static double sumRealsInFile(String filename) throws Exception;

}

Problem1: sumReals(Scanner)Tested

public static double sumReals(Scanner input)

This method takes an already open Scanner and proceeds to read input words from it. If any input word happens to represent a valid real number, it is added to a running total. When no input remains in the Scanner, this running total is returned. If no words are valid real numbers then 0.0 should be returned. Some example uses in DrJava's interactive loop are shown below.

Welcome to DrJava.  
> import java.util.Scanner;

// All numbers
> String allNums = "1.23 4.56 7.89";
> Scanner in = new Scanner(allNums);
> double total = ScannerPractice.sumReals(in);
> total
13.68
 
// All words
> String allWords = "none of these are numbers";
> in = new Scanner(allWords);
> ScannerPractice.sumReals(in)
0.0

// Mixed words and real numbers
> String mixed = "number 1.0    two  12.3   stuffed turkey -0.99   five";
> in = new Scanner(mixed);
> ScannerPractice.sumReals(in)
12.31

Constraint

Do not use regular expressions to solve this problem. They are not needed and will only over-complicate a good solution. Instead, focus on the built-in ability of Scanner to recognize different kinds of input and distinguish when a number can be read next or if the next token is an arbitrary string.

Problem 2: sumReals(String) (TESTED)

public static double sumReals(String parseString)


Rather than take an already opened Scanner this method takes a String to parse. It should create a Scanner object that reads from the parameter String and then perform the same computation as sumReals(Scanner).



Note that this illustrates that Java methods may have the same name so long as they have different argument types or different numbers of arguments.



Some sample uses



> ScannerPractice.sumReals("here are some numbers... psyche!")
0.0
> ScannerPractice.sumReals("43110")
43110.0
> ScannerPractice.sumReals("4.3 110.5  0.12  3.14")
118.06
> ScannerPractice.sumReals("one 1.0 two 2.0 thre-and-a-half 3.5 and so on...  ")
6.5

Problem 3: sumRealsInFile(String filename) (TESTED)

public static double sumRealsInFile(String filename) throws Exception

This function opens a pre-existing file on disk, reads it word by word and sums any valid real numbers that appear in it. Some example files are present with the code distribution called wordsNnumbers1.txt and wordsNnumbers2.txt. Examples of summing reals in these files are as follows.

> ScannerPractice.sumRealsInFile("wordsNnumbers1.txt")
15.912099999999999
> ScannerPractice.sumRealsInFile("wordsNnumbers2.txt")
-12.3

Hint: The best solutions to this problem are 1-2 lines long and make use of another function you wrote.

Notice that the type signature for the method includes throws Exception. In Java, some operations can go wrong which triggers an exception. Methods that can cause certain kinds of exceptions must "admit" this fact by declaring that they can throw some kind of exception. In this case, creating a Scanner that reads from a file may encounter difficulties. For instance, if the requested file is not present, then an exception will be raised. For now, we will simply state an arbitrary Exception may be thrown but in the near future we will write more refined java which declares the specific kinds of exceptions that can be thrown, in this case a FileNotFoundException.

Note - only "checked" exceptions must have these throws annotations added; RuntimeException and Error types and their descendents are unchecked, and all others are checked. Most exceptions you experience will be either a RuntimeException (unchecked) or an IOException (checked), as we see here.

Testing Locally Using JUnit

Review Lab 01 for details of how to run tests locally as graders will use test cases as a way to determine the correctness of your code. As an example, code passing all tests will compile and produce test output which looks like this.

> javac -cp junit-cs211.jar:. *.java
> java -cp junit-cs211.jar:. Lab03Tests
JUnit version 4.12
..................
Time: 0.263

OK (18 tests)

Note: The test cases for Lab 3 create some test input files which follow the name pattern sumReals_File_0.txt. These are only used during testing and may be safely deleted if desired. They are regenerated each time the tests are run.

Order your solution now only for $5


Share This:

Hassnain

I'm Hassnain. A full time Java Developer. I enjoy to make modern projects. I love to create JavaFX, Java Swing GUI and write about Java Programming, OOP. Now I'm working with CS2IT. You can buy our projects from here.

No Comment to " Scanner Practice in Java "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM