Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

JAVA Problem: Create the class ScannerPractice. It must contain the following implemented methods, though you can add more helper methods (make them public static ...

JAVA Problem:

Create the class ScannerPractice. It must contain the following implemented methods, though you can add more helper methods (make them public static ... and you can call them from our others).

sumReals(Scanner)

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.

sumReals(String)

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, as long as they have unique sequences of parameter types.

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 

Hint: It is tempting to copy and paste code for similar methods but clever programmers figure out how to use an already written method to solve a new problem by passing the old method appropriately constructed arguments. The best solutions to this problem are 1-2 lines long.

sumRealsInFile(String filename)

0 public static double sumRealsInFile(String filename) throws Exception

This method 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 sample1.txt and sample2.txt. Examples of summing reals in these files are as follows.

> ScannerPractice.sumRealsInFile("sample1.txt") 15.912099999999999 > ScannerPractice.sumRealsInFile("sample2.txt") -12.3 

Hint: The best solutions to this problem are 1-2 lines long and make use of another method 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 we can do better by listing 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.

------------

Create the class Date. It represents a day in the Gregorian calendar (in a pretty simplfied representation).

Instance Variables

Each object of this class will have its own copy of each instance variable. We sometimes call them "fields" (focusing on how they store a value) or "members" (focusing on how they are a definition inside a class, which is also true of methods).

public int year, month, day

Assume that year is positive; that month is a value from 1 to 12 inclusive; and that day is a valid day in the indicated month.

Methods

public Date(int year, int month, int day)

This constructor method assigns the given actual parameters to the corresponding instance variables.

public String toString()

Much like Python's __str__ method, this method returns a String representation of the object. For this class, we require strings that follow the obvious pattern in these examples:

"2018-02-28" "2000-02-29" "1949-10-01" 

------

Create the class Person. It must contain the following definitions, but you are welcome to add more if you'd like.

Instance Variables

Each object of this class will have its own copy of each instance variable. We sometimes call them "fields" (focusing on how they store a value) or "members" (focusing on how they are a definition inside a class, which is also true of methods).

Include these instance variable definitions:

public String name

public Date birthday

public boolean isHappy

Methods

public Person (String name, Date birthday, boolean isHappy) This constructor method must accept the three actual parameters and store them to the indicated instance variables.

public int age(Date today) Finds and returns what the person's age is today. Don't worry about validating dates, just compare this person's birthday to today and figure out how many full years they've completed, and return that integer.

public void seePuppy() This method makes the person happy.

public boolean canRentCar(Date today) Our fictitious car rental company, Budgamoprise, only rents cars to people who are 25 and older. This method indicates (returns) if a person is old enough to rent a car from Budgamoprise.

public String toString() Much like Python's __str__ method, this method returns a String representation of the object. For this class, we require strings that follow the obvious pattern in these examples:

"Person(Oscar the Grouch, 1969-11-10, false)" "Person(Groucho Marx, 1890-10-2, true)" 

Note there is a space after each comma, and no quotes in the generated string.

Tester:

import org.junit.*; import static org.junit.Assert.*; import org.junit.rules.*;

import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.*; import java.io.*;

public class Lab3Tests { /*Main method runs tests in this file*/ public static void main(String args[]) { org.junit.runner.JUnitCore.main("Lab3Tests"); }

// Black magic to enable access to name of running test via // name.getMethodName() @Rule public TestName name = new TestName();

// Test whether real numbers in space-separated strings can be read; // opens the scanner and passes it on to user function public static void testSumReals_Scanner(double expect, String parseString){ Scanner input = new Scanner(parseString); double actual = ScannerPractice.sumReals(input); double tolerance = 1e-3; String msg = String.format("Wrong sum String: %s Expect: %s Actual: %s ", parseString,expect,actual); assertEquals(msg,expect,actual,tolerance); } @Test(timeout=500) public void sumReals_Scanner_0() { testSumReals_Scanner(0.0,""); } @Test(timeout=500) public void sumReals_Scanner_1() { testSumReals_Scanner(-2.1," 0.5 1.2 -3.8"); } @Test(timeout=500) public void sumReals_Scanner_2() { testSumReals_Scanner(4.2," word 1.0 3.2 "); } @Test(timeout=500) public void sumReals_Scanner_3() { testSumReals_Scanner(5.45," 13 doh! 4 7.65 -22.34 barf stuff 3.14 nada"); } @Test(timeout=500) public void sumReals_Scanner_4() { testSumReals_Scanner(10.9,"line 9.9 don't\t\t1.0"); } @Test(timeout=500) public void sumReals_Scanner_5() { testSumReals_Scanner(201.2,"Punctuation like ! and && as well as 123 or 78.2 are words. "); }

// Test whether reading from string version is available public static void testSumReals_String(double expect, String parseString){ double actual = ScannerPractice.sumReals(parseString); double tolerance = 1e-3; String msg = String.format("Wrong sum String: %s Expect: %s Actual: %s ", parseString,expect,actual); assertEquals(msg,expect,actual,tolerance); } @Test(timeout=500) public void sumReals_String_0() { testSumReals_String(0.0,""); } @Test(timeout=500) public void sumReals_String_1() { testSumReals_String(-2.1," 0.5 1.2 -3.8"); } @Test(timeout=500) public void sumReals_String_2() { testSumReals_String(4.2," word 1.0 3.2 "); } @Test(timeout=500) public void sumReals_String_3() { testSumReals_String(5.45," 13 doh! 4 7.65 -22.34 barf stuff 3.14 nada"); } @Test(timeout=500) public void sumReals_String_4() { testSumReals_String(10.9,"line 9.9 don't\t\t1.0"); } @Test(timeout=500) public void sumReals_String_5() { testSumReals_String(201.2,"Punctuation like ! and && as well as 123 or 78.2 are words. "); }

// Write strings to file named after test then ask user code to read them in and some existing numbers public static void testSumReals_File(double expect, String parseString, String filename){ double actual = -1.0; try{ PrintWriter out = new PrintWriter(filename); out.print(parseString); out.close(); actual = ScannerPractice.sumRealsInFile(filename); } catch(Exception e){ fail(e.getMessage()); } String msg = String.format("Wrong sum File %s contents: %s Expect: %s Actual: %s ", filename,parseString,expect,actual); double tolerance = 1e-3; assertEquals(msg,expect,actual,tolerance); } @Test(timeout=500) public void sumReals_File_0() { testSumReals_File(0.0,"", name.getMethodName()+".txt"); } @Test(timeout=500) public void sumReals_File_1() { testSumReals_File(-2.1," 0.5 1.2 -3.8", name.getMethodName()+".txt"); } @Test(timeout=500) public void sumReals_File_2() { testSumReals_File(4.2," word 1.0 3.2 ", name.getMethodName()+".txt"); } @Test(timeout=500) public void sumReals_File_3() { testSumReals_File(5.45," 13 doh! 4 7.65 -22.34 barf stuff 3.14 nada", name.getMethodName()+".txt"); } @Test(timeout=500) public void sumReals_File_4() { testSumReals_File(10.9,"line 9.9 don't\t\t1.0", name.getMethodName()+".txt"); } @Test(timeout=500) public void sumReals_File_5() { testSumReals_File(201.2,"Punctuation like ! and && as well as 123 or 78.2 are words. ", name.getMethodName()+".txt"); } // Test cases devoted to Date objects. @Test(timeout=500) public void date_1(){ Date d = new Date(2018,1,22); assertEquals(2018,d.year ); assertEquals( 1,d.month); assertEquals( 22,d.day ); d.year=1999; d.month=12; d.day=31; assertEquals(1999,d.year ); assertEquals( 12,d.month); assertEquals( 31,d.day ); } @Test(timeout=500) public void date_2(){ Date d = new Date(1,2,3); assertEquals(1,d.year); assertEquals(2,d.month); assertEquals(3,d.day); }

@Test(timeout=500) public void date_3(){ assertEquals("1969-11-10",new Date(1969,11,10).toString());} @Test(timeout=500) public void date_4(){ assertEquals("2000-12-29",new Date(2000,12,29).toString());} @Test(timeout=500) public void date_5(){ assertEquals("1949-10-11",new Date(1949,10,11).toString());} // deal with leading zeroes. @Test(timeout=500) public void date_6(){ assertEquals("2018-02-28",new Date(2018,2,28).toString()); } @Test(timeout=500) public void date_7(){ assertEquals("2000-02-29",new Date(2000,2,29).toString()); } @Test(timeout=500) public void date_8(){ assertEquals("1949-10-01",new Date(1949,10,1).toString()); } // Test cases on Persons. @Test(timeout=500) public void person_1(){ Person p = new Person("Oscar the Grouch",new Date(1969,11,10),false); assertEquals("Oscar the Grouch",p.name); } @Test(timeout=500) public void person_2(){ Person p = new Person("Oscar the Grouch",new Date(1969,11,10),false); assertEquals(1969,p.birthday.year); assertEquals(11,p.birthday.month); assertEquals(10,p.birthday.day); } @Test(timeout=500) public void person_3(){ Person p = new Person("Oscar the Grouch",new Date(1969,11,10),false); assertFalse(p.isHappy); } @Test(timeout=500) public void person_4(){ Person p = new Person("Groucho Marx",new Date(1890,10,2),true); assertEquals("Groucho Marx",p.name); assertEquals(1890,p.birthday.year ); assertEquals( 10,p.birthday.month); assertEquals( 2,p.birthday.day ); assertTrue(p.isHappy); } @Test(timeout=500) public void person_5(){ Person p = new Person("Groucho Marx",new Date(1890,10,2),true); assertEquals(86,p.age(new Date(1977,8,19))); }

@Test(timeout=500) public void person_6(){ Person p = new Person("Juniper Juneson",new Date(1950,6,15),true); assertEquals(10,p.age(new Date(1960,12,31))); } @Test(timeout=500) public void person_7(){ Person p = new Person("Juniper Juneson",new Date(1950,6,15),true); assertEquals(19,p.age(new Date(1970,1,1))); } @Test(timeout=500) public void person_8(){ Person p = new Person("Juniper Juneson",new Date(1950,6,15),true); assertEquals(29,p.age(new Date(1980,5,20))); assertEquals(29,p.age(new Date(1980,6,13))); } @Test(timeout=500) public void person_9(){ Person p = new Person("Oscar the Grouch",new Date(1969,11,10),false); assertFalse(p.isHappy); p.seePuppy(); assertTrue(p.isHappy); } @Test(timeout=500) public void person_10(){ Person p = new Person("Groucho Marx",new Date(1890,10,2),true); assertTrue(p.isHappy); p.isHappy = false; assertFalse(p.isHappy); p.seePuppy(); p.seePuppy(); assertTrue(p.isHappy); } @Test(timeout=500) public void person_11(){ Person p = new Person("John Doe",new Date(2000,2,2),false); assertFalse(p.canRentCar(new Date(2000,1,1))); assertFalse(p.canRentCar(new Date(2020,1,1))); assertFalse(p.canRentCar(new Date(2025,2,1))); } @Test(timeout=500) public void person_12(){ Person p = new Person("John Doe",new Date(2000,2,2),false); assertTrue(p.canRentCar(new Date(2025,2,2))); assertTrue(p.canRentCar(new Date(2025,3,1))); assertTrue(p.canRentCar(new Date(2050,1,1))); } @Test(timeout=500) public void person_13(){ Person p = new Person("Oscar the Grouch",new Date(1969,11,10),false); assertEquals("Person(Oscar the Grouch, 1969-11-10, false)",p.toString()); } @Test(timeout=500) public void person_14(){ Person p = new Person("Groucho Marx",new Date(1890,10,2),true); assertEquals("Person(Groucho Marx, 1890-10-02, true)",p.toString()); }

}

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_2

Step: 3

blur-text-image_3

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

Hands-On Database

Authors: Steve Conger

2nd Edition

0133024415, 978-0133024418

More Books

Students also viewed these Databases questions