teaching machines

CS 148: Lab 3 – String and Math

September 21, 2017 by . Filed under cs1, cs148, fall 2017, labs.

Welcome to lab 3!

If you have checkpoints from the last lab to show your instructor or TA, do so immediately. No credit will be given if you have not already completed the work, nor will credit be given after the first 10 minutes of this lab.

Work with a partner that you have not worked with before.

Our goal today is acquaint ourselves with methods of the Math and String classes.

Checkpoint 1

Person A types. Make a lab03 package in your Eclipse project.

Complete three of the following problems:

Checkpoint 2

Person B types.

Write an anagram puzzler. Generate a random word via Random Word API, jumble the letters, prompt the jumbled form to the user, grab their unscrambled form from the keyboard, and print whether or not they descrambled it correctly.

Reading from the Web

To read data from the web in Java, use URLConnection:

URL url = new URL("insert your URL here");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();

You can then feed inputStream into a Scanner—instead of using System.in.

The code will potentially generate some exceptions. For the time being, don’t try to handle them. Just let them be thrown by adding a throws clause on the main method:

public static void main(String[] args) throws MalformedURLException, IOException {
  ...
}

Constraining Word Length

The Random Word API documentation describes how you can tailor the length of the randomly-generated word. Append to your URL this query: ?len=N, replacing N with your desired word length.

Scrambling

To scramble a collection of data, I recommend you use Collections.shuffle. But to use this, you must turn the String into something that Java considers a Collection. ArrayList is a good choice. So, I’d follow this pseudocode:

convert String to ArrayList
shuffle list
convert ArrayList to String