Object-Oriented Programming with Java, part I + II

cc

This material is licensed under the Creative Commons BY-NC-SA license, which means that you can use it and distribute it freely so long as you do not erase the names of the original authors. If you make changes in the material and want to distribute this altered version of the material, you have to license it with a similar free license. The use of the material for commercial use is prohibited without a separate agreement.

Authors: Arto Hellas, Matti Luukkainen
Translators to English: Emilia Hjelm, Alex H. Virtanen, Matti Luukkainen, Virpi Sumu, Birunthan Mohanathas, Etiënne Goossens
Extra material added by: Etiënne Goossens, Maurice Snoeren, Johan Talboom
Adapted for Informatica by: Ruud Hermans

The course is maintained by Technische Informatica Breda


Reading User Input

So far our programs have been rather one-sided. Next we will learn how to read input from the user. We will use a special Scanner tool to read the user input.

Let us add the Scanner to our existing main program body. Do not worry if the main program body seems obscure as we will continue to write our code in the part marked // program code.

import java.util.Scanner;

public class ProgramBody {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        // program code
    }
}

Reading a string

System.out.print("What is your name? ");
String name = reader.nextLine(); // Reads a line of input from the user and assigns it
                                 //     to the variable called name

System.out.println("Hi, " + name);
What is your name? ~~John~~
Hi, John

The program above combined along with the main program body is shown below. The name of the program is Greeting, which means that it must be located in a file named Greeting.java.

import java.util.Scanner;

public class Greeting {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        System.out.print("Who is greeted: ");
        String name = reader.nextLine(); // Reads a line of input from the user and assigns it
                                         //     to the variable called name

        System.out.print("Hi " + name);
    }
}

When the program above is executed, you can type the input. The output tab in IntelliJ (at the bottom) looks as follows when the program has finished (the user inputs the name “John”).

Who is greeted: ~~John~~
Hi John
Process finished with exit code 0

Reading integers

Our Scanner tool is not good for reading integers, so we will use another special tool to read an integer. The command Integer.parseInt converts the string given to it into an integer. The command’s parameter is given between brackets and it returns an integer that can be assigned to an integer variable.

Basically, we are joining two commands together. First we read the input as a string from the user and immediately give it to the command Integer.parseInt.

System.out.print("Type an integer: ");
int number = Integer.parseInt(reader.nextLine());

System.out.println("You typed " + number);

Next we will ask the user to give us his name and age. The program body is included this time.

import java.util.Scanner;

public class NameAndAgeGreeting {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        System.out.print("Your name: ");
        String name = reader.nextLine();   // Reads a line from the users keyboard

        System.out.print("How old are you: ");
        int age = Integer.parseInt(reader.nextLine()); // Reads a string variable from the keyboard and transfers it to an integer

        System.out.println("Your name is: " + name + ", and you are " + age + " years old, nice to meet you!");
    }
}

Summary

The program body for interaction with the user is as follows:

import java.util.Scanner;
public class ProgramName {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        // code here
    }
}

Reading a string:

String text = reader.nextLine();

Reading an integer:

int number = Integer.parseInt(reader.nextLine());

Exercise user-input-1 : Adder

Create a program that asks the user for two integers and then prints their sum.

Type a number: ~~6~~
Type another number: ~~2~~

Sum of the numbers: 8

In this example the user input is marked in red color. From now on the red color will indicate user input in examples.

Exercise user-input-2 : Divider

Create a program that asks the user for two integers and prints their quotient. Make sure that 3 / 2 = 1.5. If the decimal part is missing, take another look at variables Floating point numbers (decimal numbers) to find the solution.

Type a number: ~~3~~
Type another number: ~~2~~

Division: 3 / 2 = 1.5

Exercise user-input-3 : Calculating the circumference

circumference

The circumference of a circle is calculated using the formula . Create a program that asks the user for the radius and then calculates the circumference using the given radius. Java already contains the value of pi in the Math.PI variable, which you can use in your calculation.

Type the radius: ~~20~~

Circumference of the circle: 125.66370614359172

Exercise user-input-4 : Bigger number

Create a program that asks the user for two integers and then prints the larger of the two.

Tip: When you write Math. (that is, Math followed by a dot) in IntelliJ, it shows you a bunch of available mathematical calculations. For example, Math.cos(10) calculates the cosine of the number 10. Try to find a suitable tool in Math to complete this exercise! If you cannot find anything suitable or do not know how to complete the exercise, skip the exercise for now. We will return to the matter later on.

Type a number: ~~20~~
Type another number: ~~14~~

The bigger number of the two numbers given was: 20

Exercise user-input-5 : Sum of the ages

Create a program that asks for the names and ages of two users. After that the program prints the sum of their ages.

Type your name: ~~Matti~~
Type your age: ~~14~~

Type your name: ~~Arto~~
Type your age: ~~12~~

Matti and Arto are 26 years old in total.

Exercise user-input-6 : NHL Statistics, part 1

A ready-made component NHLStatistics is included along with the exercise files for this excercise. It can be used to fetch and see NHL players’ score data, including their number of played games, goals, assists, points, and penalty amount.

The main program imports (i.e. enables the use of) the component by adding the following line to the beginning of the file: import nhlstats.NHLStatistics;. The next example prints the top 10 players based on points:

import java.util.Scanner;
import nhlstats.NHLStatistics;

public class Main {
   public static void main(String[] args) throws Exception {
       Scanner reader = new Scanner(System.in);

       System.out.println("Top ten by points");
       NHLStatistics.sortByPoints();
       NHLStatistics.top(10);
   }
}

It will print (this was the situation on the 9th of January 2012):

Top ten by points
Henrik Sedin           VAN        43 11 + 38= 49  36
Phil Kessel            TOR        41 24 + 24= 48  10
Claude Giroux          PHI        36 18 + 30= 48  16
Joffrey Lupul          TOR        41 19 + 28= 47  36
Daniel Sedin           VAN        42 18 + 29= 47  32
Steven Stamkos         TBL        40 28 + 17= 45  34
Marian Hossa           CHI        41 17 + 27= 44  14
Evgeni Malkin          PIT        33 16 + 28= 44  30
Jordan Eberle          EDM        41 17 + 26= 43   6
Jason Pominville       BUF        41 14 + 29= 43   8

The name, abbreviation of the club, matches played, goals, assists, points and penalties of players are printed.

The first command NHLStatistics.sortByPoints() sorts the list of NHL players by the points they have gathered. The second command NHLStatistics.top(10); prints the ten first players from the list. Any integer can be given as a parameter.

Similarly the players can be printed ordered by the goals or assists they have made, or by penalty minutes they have been given. First, we call the command to sort the players:

NHLStatistics.sortByPoints();     // orders the players by points
NHLStatistics.sortByGoals();      // orders the players by goals
NHLStatistics.sortByAssists();    // orders the players by assists
NHLStatistics.sortByPenalties();  // orders the players by penalty minutes

After that the players are printed with the command top using the number of players to be printed as its parameter.

It is also possible to use the component to request the statistics of a certain player:

NHLStatistics.searchByPlayer("Jaromir Jagr");  // prints stats of Jaromir Jagr
NHLStatistics.searchByPlayer("Koivu");         // prints stats of Mikko Koivu and Saku Koivu
NHLStatistics.searchByPlayer("Teemu");         // prints stats of all players named Teemu

The component can also print the statistics of all players in a club:

NHLStatistics.teamStatistics("NYR");  // Statistics of New York Rangers

The order of the printed club statistics can be changed using a sortBy...() first.

The name of the club must be given using the official three letter abbreviation. You can check the abbreviations here. The statistics component prints a list of the available abbreviations if you request the statistics of an invalid club.

Create a program that does the following tasks into the main program body. The tasks must be done in exactly the same order as listed below. Do the tasks in the program body one after another without deleting tasks you have already done.

Note: When you first run the program, the execution might take a while because the information is downloaded from the web. Execution should be quick after the first run.

The program must do the following:

  • Print the top ten players based on goals
  • Print the top 25 players based on penalty amounts
  • Print the statistics for Sidney Crosby
  • Print the statistics for Philadelphia Flyers (abbreviation: PHI). Note in which order the players are printed in and why that might be!
  • Print the players in Anaheim Ducks (abbreviation: ANA) ordered by points

After you have successfully submitted the exercise, you can play with the code as you wish!