# Building Java Programs

## Lab: Scanner

Except where otherwise noted, the contents of this document are Copyright 2019 Stuart Reges and Marty Stepp.

# Lab goals

Goals for this problem set:

• use `Scanner` to create interactive programs that read user input
• practice using `if/else` statements for conditional execution

# User input and `Scanner`

Method name Description
`nextInt()` reads and returns the next token as an `int`, if possible
`nextDouble()` reads and returns the next token as `double`, if possible
`next()` reads and returns a single word as a `String`
`nextLine()` reads and returns an entire line as a `String`

Example:

```import java.util.*;   // so you can use Scanner
...
Scanner console = new Scanner(System.in);
System.out.print("How old are you? ");   // prompt
int age = console.nextInt();
System.out.println("You typed " + age);
```

Write a complete program `CollegeAdmit` with the behavior shown below. Use the `Scanner` to read user input for a student's grade point average and SAT exam score. A GPA below 1.8 will cause the student to be rejected; an SAT score below 900 will also cause a rejection. Otherwise the student is accepted.

```University admission program
What is your SAT score? 1280
You were accepted!
```

# Exercise : `Scanner` sum

Copy and paste the following code into your editor.

```public class SumNumbers {
public static void main(String[] args) {
int low = 1;
int high = 1000;
int sum = 0;
for (int i = low; i <= high; i++) {
sum += i;
}
System.out.println("sum = " + sum);
}
}
```

continued on next slide...

# Exercise : `Scanner` sum

Modify the code to use a `Scanner` to prompt the user for the values of `low` and `high`. Below is a sample execution in which the user asks for the same values as in the original program (1 through 1000):

```low? 1
high? 1000
sum = 500500
```

Below is an execution with different values for `low` and `high`:

```low? 300
high? 5297
sum = 13986903
```

You should exactly reproduce this format.

# Exercise : longestName

Write a method named `longestName` that reads names typed by the user and prints the longest name (the name that contains the most characters) in the format shown below. Your method should accept a console `Scanner` and an integer n as parameters and should then prompt for n names.

A sample execution of the call `longestName(console, 4)` might look like the following:

```name #1? roy
name #2? DANE
name #3? sTeFaNiE
name #4? Erik
Stefanie's name is longest
```