CSCI 201 Introduction to Algorithm Design
home | homework index | labs index 
FALL 2006  

Control Statements

[an error occurred while processing this directive]
This lab objective is to practice using control statements in Java. You will work with two different kinds of control statements: if-else statements, and while loops. You will also  use some basic input methods of the Scanner class and some formatting techniques of the printf method.

Scanner Class

Scanner is a class that is built-in to Java (starting with Java version 1.5). It is located in the java.util package. Scanner has several methods. Some methods for inputting primitive values are:

To input Strings you can use:

To check if there are still more tokens left you can use:

The following code segment demonstrates all the above methods.

Scanner input = new Scanner(System.in);
int i;
double x;
String word;
String line;
String theRest = "no input";
System.out.print("Enter int, double, word, line: ");
i = input.nextInt();
x = input.nextDouble();
word = input.next(); // returns a String up to next whitespace
line = input.nextLine(); // returns the rest of line , excluding any line separator at the end
System.out.printf("Integer: %d\nDouble: %f\nWord: %s\n Line: %s\n", i, x, word, line);
if (input.hasNext()){
    theRest =  input.nextLine();
}
System.out.printf("Also entered: %s", theRest);

If end-of-file is the next input value after the line, output will be:

Enter int, double, word, line: 4 5.7 Textbook for CSCI201
Integer: 4
Double: 5.700000
Word:
Line: Textbook for CSCI201
end-of-file
Also entered: no input

String API

Complete String API available at http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html. Some methods are:

For example, to make variable alpha equal to the fifth character from String word, you need to write:
  char alpha = word.charAt(4);
Note: Remember that characters are numbered starting at 0, so the fifth character really is at position 4.

 

Checkpoint

Answer the questions below. You have to answer all questions correctly to see the rest of the lab.

One of the new classes in J2SE 5.0 that can be used for formatted input such as reading and parsing primitive type and strings is:
java.io.Scanner
java.util.Scanner
java.io.InputReader
java.util.FormattedReader

The ___________ method of the class Scanner can be used to check whether or not more input data is available?
hasNext( )
hasNextLine( )
nextLine( )
next( )