CS-151 Labs > Lab 1. The First Cup of Java


Warmup

In cs151 directory, create a new folder for your project called lab1.

Create new Java project in Eclipse by selecting File > New > Java Project. Give it the project name lab1. Uncheck the Use default location box. Use the browse button to select the lab1 folder you created at the start.

Add file readme.txt to the project. In this file document your warmup experiences: add the name of your lab partner, answer the questions from this section of the lab, and give your feedback on what was challenging. Later on you will add the notes about your lab1 programs, and the Honor pledge.

Add new class to lab1/src folder. Use warmup1 as the package name. Use Numbers as the name of the class and check the button for including a public static void main stub. Click the Finish button at the bottom and you are ready to start coding.

A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts. For example you might want to create your own class called File. However there already exists class named File in java.io package. If you add your File class to mypackage package, then you will be able to use both classes in the same program, referring to one as java.io.File and to the other as mypackage.File.

You should now have a new file Numbers.java with the auto-generated main:

package warmup1;

public class Numbers {
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }
}

We will learn how to use class Scanner defined in java.util package. Import Scanner by adding this line above the public class Numbers line:

import java.util.Scanner;

Inside main, add the code:

String numbers = "86 75 309";
Scanner scanner = new Scanner(numbers);

while (scanner.hasNextInt()) {
    int num = scanner.nextInt();
    System.out.println(num);
}
scanner.close();

With your partner, predict what will happen when you run this code. Run the code. Did it match what you expected? Document your experiences in readme.txt.

Scanning words

Create a new class named Words. Copy the code from Numbers.java into Words.java. Change the code so that rather than scanning for numbers, the scanner returns words. To do this, change String numbers = "..." to String words = "Java is very wordy!"; and replace hasNextInt() and nextInt() with hasNext() and next(), respectively.

Compile and run your code.

Before moving on, click on one of those links in the paragraph above. That will take you to the documentation for those methods. Look at what other methods the Scanner class has. What other types can the Scanner read?

Scanning files

Next, change your code to not read from a fixed string, but from a file. You’ll want to replace the Scanner variable declaration with something like this:

// We need to declare scanner outside the try/catch block so that it is in scope
// when we use it in our loop.
Scanner scanner = null;
try {
    scanner = new Scanner(new File("input.txt")); 
} catch (FileNotFoundException e) {
    System.out.println("Problem opening file: " + e.getMessage());
    System.exit(1);
}

Leave the rest of the while loop the same. This will read words from a file called input.txt.

At this point, Eclipse is probably complaining about your code. It doesn’t know what File or FileNotFoundException are. Add these import lines next to your other import line.

import java.io.File;
import java.io.FileNotFoundException;

Hopefully, Eclipse is happy now so let’s create our input file. Right-click on project name and select New > File. Name the file input.txt. Enter a few lines of text. Enter whatever you want here.

Save all your work and then compile and run Words.

Notice that the Scanner puts every word on a line of its own. That’s not great. Change the System.out.println() to use System.out.print() instead. What do you think will happen? Try it out.

Okay, that’s not great either. Try printing out a space after each word. You can do it via something like this.

String word = scanner.next();
System.out.print(word + " ");

Save and run.

That’s better, but we still lost all of the line breaks!

We can solve this by using two scanners. Rather than using scanner.hasNext() and scanner.next(), we can use scanner.hasNextLine() and scanner.nextLine().

Each call to scanner.nextLine() will return a string containing a line of the file.

Inside your while loop, create a new scanner that will scan the line. Your code might look something like this.

while (lineScanner.hasNextLine()) {
    String line = lineScanner.nextLine();
    Scanner wordScanner = new Scanner(line);
    // code which prints the words on this line
    wordScanner.close();
}
lineScanner.close();

Notice that we have given the scanners more distinctive names.

Print out each word in each line using System.out.print() with appropriate spaces between words. At the end of each line, print a new line via

System.out.println();

Finish documenting your warmup experiences in readme.txt. This is required to get the participation points for the warmup, which is not graded on correctness. Now you are ready for Lab 1.