Except where otherwise noted, the contents of this document are Copyright 2012 Stuart Reges and Marty Stepp.
lab document created by Marty Stepp, Stuart Reges, Whitaker Brand and Hélène Martin
Goals for today:
Random
to generate random numbersboolean
typeScanner
and File
objects to read input data from filesScanner
breaks input into tokensRandom
methods
To use these methods, you need a variable of type Random
in
scope:
Random randy = new Random();
int aRandomNumber = randy.nextInt(10); // 0-9
Method name | Returns... |
---|---|
nextInt()
|
a random integer |
nextInt(max)
|
a random integer between 0 (inclusive) and max (exclusive) |
nextDouble()
|
a random real number between 0.0 and 1.0 |
nextBoolean()
|
a random boolean value: true
or false
|
Fill in the boxes to produce expressions that will generate random numbers in the provided ranges.
Assume that the following Random
variable has been declared:
Random rand = new Random();
Example: a random integer from 1 to 5 inclusive: |
rand.nextInt(5)
+
1
|
a random integer from 0 to 3 inclusive: |
rand.nextInt(4)
|
a random integer from 5 to 10 inclusive: |
rand.nextInt(6)
+
5
|
a random integer from -4 to 4 inclusive: |
rand.nextInt(9)
-
4
|
a random even integer from 16 to 28 inclusive: (Hint: To get only even numbers, scale up.) |
rand.nextInt(7)
*
2
+
16
|
Write a method named makeGuesses
that will output random
numbers between 1 and 50 inclusive until it outputs one of at least 48.
Output each guess and the total number of guesses made. Below is a sample
execution:
guess = 43 guess = 47 guess = 45 guess = 27 guess = 49 total guesses = 5
Try solving this problem in Practice-It! from the link above.
Write a method flip
that takes a Random
object as
a parameter and that prints information about a coin-flipping simulation.
Your method should use the Random
object to produce a sequence
of simulated coin flips, printing whether each flip comes up "heads" or
"tails". Each outcome should be equally likely. Your method should stop
flipping when you see three heads in a row.
Solve this problem in Practice-It by clicking on the check-mark above.
boolean
type
The boolean
type represents logical values of true
or false
. Combine boolean
expressions with logical operators &&
(and), ||
(or), and !
(not).
Example:
boolean test1 = 7 < 10; // true boolean test2 = (1 == 2); // false if ((test1 || test2) && 2 + 2 != 5) { System.out.print("hello"); // output: hello }
String
methods with boolean
resultsMethod name | Description |
---|---|
string.equals(string)
|
whether the two strings are identical |
string.equalsIgnoreCase(string)
|
whether the two strings are identical, ignoring capitalization |
string.startsWith(string)
|
whether this string begins with the characters of the given string |
string.endsWith(string)
|
whether this string ends with the characters of the given string |
string.contains(string)
|
whether the characters of the given string occur within this string |
String name = "Professor Smith"; if (name.startsWith("Prof")) { System.out.println("When are your office hours?"); }
Write the result of each expression as either true
or false
, given the following variables.
int x = 12; int y = 7; int z = 28; String s = "mid term";
x < 14 |
true |
|
!(x % 2 < 1) |
false |
|
x < y || x < z |
true |
|
z / x < x / y * x |
true |
|
s.length() == y |
false |
|
s.toUpperCase().equals("MID TERM") |
true |
|
!s.equals("mid term") || x * y != z |
true |
|
s.substring(z / x).length() > y |
false |
Scanner
usage
1 2 3 4 5 6 7 8 9 |
import java.io.*; // for File import java.util.*; // for Scanner public class FileScannerDemo { public static void main(String[] args) throws FileNotFoundException { File f = new File("test.txt"); Scanner input = new Scanner(f); } } |
File
class is in the java.io
packageScanner
object on that file's File
objectScanner
object on a File
needs to acknowledge the possibility of a FileNotFoundException
throws
clause is like a legal waiver: "I know bad things will happen if the file is missing but I accept that"
Which of the following choices is the correct syntax for declaring
a Scanner
to read the file example.txt
in the
current directory ?
Scanner
methodsMethod name | Description |
---|---|
next()
|
reads and returns the next token as a String
|
nextLine()
|
reads and returns as a String all the characters up to
the next new line (\n )
|
nextInt()
|
reads and returns the next token as an int , if
possible
|
nextDouble()
|
reads and returns the next token as double , if
possible
|
hasNext()
|
returns true if there is still a token in
the Scanner
|
hasNextLine()
|
returns true if there is still at least one line left
to be read in the Scanner
|
hasNextInt()
|
returns true if the next token can be read as
an int
|
hasNextDouble()
|
returns true if the next token can be read as
an double
|
How many tokens are in the
following String
?
3
welcome...to the matrix.
What are the tokens that the String
breaks up into?
How many tokens are in the
following String
?
9
in fourteen-hundred 92 columbus sailed the ocean blue :)
What are the tokens that the String
breaks up into?
Scanner
practice
The next couple problems are about a file called readme.txt
that has the following contents:
6.7 This file has several input LINES! 10 20
What would be the output from the following code, as it would appear on the console?
Scanner input = new Scanner(new File("readme.txt")); System.out.println(input.next()); // 6.7 System.out.println(input.next()); // This System.out.println(input.next()); // file
Scanner
practice
Input file: readme.txt
6.7 This file has several input LINES! 10 20
What would be the output for the following code? If there would be an error, write error .
Scanner input = new Scanner(new File("readme.txt")); System.out.println(input.nextDouble()); // 6.7 System.out.println(input.nextDouble()); // error
Scanner
practice
Input file: readme.txt
6.7 This file has several input LINES! 10 20
What would be the output for the following code? If there would be an error, write error .
Scanner input = new Scanner(new File("readme.txt"));
while (!input.hasNextInt()) {
input.next();
}
System.out.println(input.nextInt()); // 10
import
statements and a throws
clause to
the code.
import java.io.*; // for File import java.util.*; // for Scanner public class Words { public static void main(String[] args) throws FileNotFoundException { int wordCount = 0; Scanner input = new Scanner(new File("wordinput.txt")); // your code goes here ... while (input.hasNext()) { String word = input.next(); wordCount++; } System.out.println("Total words = " + wordCount); } }
runningSum
Write a static method called runningSum
that
accepts as a parameter a Scanner
holding a sequence of real
numbers and that outputs the running sum of the numbers followed by the
maximum running sum. For example if the Scanner
contains the
following data:
3.25 4.5 -8.25 7.25 3.5 4.25 -6.5 5.25
Your method should produce the following output:
running sum = 3.25 7.75 -0.5 6.75 10.25 14.5 8.0 13.25 max sum = 14.5
Click on the check-mark above to try out your solution in Practice-it!
frequentFlier
Write a method frequentFlier
that accepts a Scanner
for an input file of ticket type / mileage pairs and reports how many frequent-flier miles the person earned.
For example, given the input below, your method should return 15600 (2*5000 + 1500 + 100 + 2*2000).
firstclass 5000 coach 1500 coach 100 firstclass 2000 discount 300
flipLines
Write a method named flipLines
that accepts
a Scanner
for an input file and writes to the console the same
file's contents with each pair of lines reversed in order. For example, if
the file contains:
Twas brillig and the slithy toves did gyre and gimble in the wabe. All mimsey were the borogroves, and the mome raths outgrabe. The End
your method should produce the following output:
did gyre and gimble in the wabe. Twas brillig and the slithy toves and the mome raths outgrabe. All mimsey were the borogroves, The End
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Counts the total lines and words in the given input scanner. public static void countWords(Scanner input) { Scanner input = new Scanner(new File("example.txt")); int lineCount = 0; int wordCount = 0; while (input.nextLine()) { String line = input.line(); // read one line lineCount++; while (line.next()) { // count tokens in line String word = line.hasNext; wordCount++; } } } |
The above attempted solution to Practice-It problem
"countWords
" has 5 errors.
Open Practice-It from the link above, copy/paste this code into it, and fix
the errors. Complete the code so that it passes the test cases.
Scanner
for the
filenextLine
should be hasNextLine
line
should be nextLine
Scanner
to read the tokens of
each linehasNext
should be next()
println
statements to print
line/word stats
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Counts the total lines and words in the given input scanner. public static void countWords(Scanner input) { |
coinFlip
Write a method named coinFlip
that accepts
a Scanner
for an input file of coin flips that are heads (H)
or tails (T). Consider each line to be a separate set of coin flips and
output the number and percentage of heads in that line. If it is more than
50%, print "You win!". Consider the following file:
H T H H T T t t T h H h
For the input above, your method should produce the following output:
3 heads (60.0%) You win! 2 heads (33.3%) 1 heads (100.0%) You win!
printDuplicates
Write a method printDuplicates
that accepts a Scanner
for an input file.
Examine each line for consecutive occurrences of the same token on the same line and print each duplicated token along how many times it appears consecutively. For example the file:
hello how how are you you you you I I I am Jack's Jack's smirking smirking smirking smirking smirking revenge one fish two fish red fish blue fish bow wow wow yippee yippee yo yippee yippee yay yay yay
leads to the following console output:
how*2 you*4 I*3 Jack's*2 smirking*5 wow*2 yippee*2 yippee*2 yay*3
mostCommonNames
Write a method mostCommonNames
that accepts a Scanner
for an input file with names on each line separated by spaces. Some names appear multiple times in a row. For example:
Benson Eric Eric Marty Kim Kim Kim Jenny Nancy Nancy Nancy Paul Paul Stuart Stuart Stuart Ethan Alyssa Alyssa Helene Jessica Jessica Jessica Jessica Jared Alisa Yuki Catriona Cody Coral Trent Kevin Ben Stefanie Kenneth
For each line, print the most commonly occurring name. If there's a tie, use the first name that had that many occurrences.
Most common: Kim Most common: Jessica Most common: Jared
Also return the total number of unique names in the whole file (e.g. 23 for the above input).
stripHtmlTags
Write a method stripHtmlTags
that accepts a Scanner
for an input file containing an HTML web page, then reads that file and prints the file's text with all HTML tags removed. A tag is any text between the character < and >. For example, consider the following text:
<html> <head> <title>My web page</title> </head> </html>
If a file containing these lines were passed to your program, your program should output the following:
My web page
In this exercise we will practice the jGRASP debugger using the Case Study example from the end of Chapter 6. To download this example, follow these steps:
ZipLookup.java
and zipcode.txt
.
Right-click the file names and choose the option to save the link in whatever folder you have been using for lab work.
Make sure to save them in the same folder.
ZipLookup.java
in jGRASP.
You might try using your own ZIP code and a relatively small radius like 0.5 miles.
The program takes a while to run because it has to search a large data file.
continued on the next slide...
ZipLookup
program.
find
.
Then it shows all matches in the method named showMatches
.
We want to debug showMatches
.
continued on the next slide...
What zip code are you interested in? 20500 And what proximity (in miles)? 0.3 20500: Washington, DC zip codes within 0.3 miles: 20045 Washington, DC, 0.26 miles 20500 Washington, DC, 0.00 miles 20501 Washington, DC, 0.27 miles 20502 Washington, DC, 0.27 miles
while
loop in the showMatches
method executes.
Set a break point on the while
loop itself.
Then debug to find lat1
and long1
(latitude and longitude of the White House ZIP code).
lat1 |
38.894781 |
|
long1 |
-77.036122 |
continued on the next slide...
Clear your previous break point and set a new break point inside on the printf
inside the if
.
Then hit the resume button that looks like a play button and fill in the table below with the values for zip
, lat2
, and long2
.
zip |
lat2 |
long2 |
---|---|---|
20045 | 38.896599 | -77.0319 |
20500 | 38.894781 | -77.036122 |
20501 | 38.89872 | -77.036198 |
20502 | 38.89872 | -77.036198 |
Write a method named allDigitsOdd
that returns whether every
digit of a positive integer is odd. Your method should
return true
if the number consists entirely of odd digits
and false
if any of its digits are even. 0, 2, 4, 6, and 8
are even digits, and 1, 3, 5, 7, 9 are odd digits.
For example, allDigitsOdd(135319)
returns true
but allDigitsOdd(9145293)
returns false
.
Hint: You can pull apart a number into its digits using /
10
and % 10
.
Write a method sameDashes
that takes two strings as parameters
and that returns whether or not they have dashes in the same places
(returning true
if they do and returning false
otherwise). For example, below are four pairs of strings of equal length
that have the same pattern of dashes. Notice that the last pair has no
dashes at all.
string 1: "hi--there-you." "-15-389" "criminal-plan" "abc" string 2: "12--(134)-7539" "-xy-zzy" "(206)555-1384" "9.8"To be considered a match, the strings must have exactly the same number of dashes in exactly the same positions. The Strings might be of different length.
Solve this problem in Practice-It by clicking on the check-mark above.
If you finish all the exercises, try out our Practice-It web tool. It lets you solve Java problems from our Building Java Programs textbook.
You can view an exercise, type a solution, and submit it to see if you have solved it correctly.
Choose some problems from the book and try to solve them!