Chapter 5
Using Library Classes
Good news! You don’t have to write everything yourself. Often, you use code contained in classes written by someone else (such as the System class mentioned earlier). Specifically, the Java Class Library is a set of classes that perform important functions, such as capturing user input (the Scanner class) and generating random numbers (the Random class). To use these classes, you (typically) first import the class (thereby gaining access to the code), then create objects and use their methods (i.e., code that gives the class/objects functionality).
We’ll explore objects in much more depth later, but for now think of it this way-- a class is like a set of plans for building an object-- like a bicycle, to use a "real world" example. You only need one set of plans to create many bicycles. In order to actually use a bicycle, however, the plans are not enough; you need to build an actual bicycle.
In code, this idea requires the use of the new keyword with the syntax ClassName variableName = new ClassName([optional parameters]);
For example, creating a Scanner object called myScanner looks like
Scanner myScanner = new Scanner(System.in);
We now have a functioning Scanner (a software scanner-- not a physical machine) to use in our code. System.in is called a parameter; parameters provide input to a method. In this case, it tells the Scanner that it should read from the computer keyboard (as opposed to a text file, for example, which could alternatively be a parameter). If we need another Scanner object, we can go ahead and create that, as well, from the same class. Note that an object is also called an instance of a class.
Full documentation for any Java class is readily available by internet search (I recommend searching “Oracle Java” followed by the class name, because Java is maintained by Oracle).
Scanner
The Scanner class allows you to accept input from the user of a program. Here is a four-step process for using a Scanner (numbered so you can see them in the example):
- Import the Scanner class
- Create a new Scanner object (call it whatever you want), using System.in as the parameter .
- Use the Scanner methods to read in input.
- nextLine()-- reads the remainder of the current line as a String and skips to the next line (use this to read Strings and after any use of nextInt(), nextDouble(), or next()
- nextInt()-- reads in the next integer
- nextDouble()-- reads in the next double
- next()-- reads in the next String
- Close the Scanner when finished
//1. Import the Scanner class
import java.util.Scanner;
public class ScannerDemo
{
public static void main (String [] args)
{
//2. Create a new Scanner object
Scanner sc = new Scanner(System.in);
//prompt user for a number
System.out.println("Enter a number");
//3. Scan in user entry
int a = sc.nextInt(); //use nextInt() for integers
//always use a blank nextLine() after nextInt() or nextDouble()
sc.nextLine();
System.out.println("Enter your name");
//use the same Scanner object to get more input
String name = sc.nextLine(); //use nextLine() for Strings
System.out.println(name + ", you entered " + a);
//4. Close the Scanner
sc.close();
}
}
Sample output
Enter a number
12
Enter your name
Charlie
Charlie, you entered 12
Note that there is no nextChar() method for Scanner. If you want to read in a single character, use nextLine() to read it as a String, instead. You’ll learn later how to change that to a char.
Scanner troubleshooting
There is a problem when using the nextInt(), nextDouble(), or next() method before using the nextLine() method. These methods retrieve the next integer, double, or String, respectively, but they do not advance to the next line. If you then attempt to use the nextLine() method, you will only capture the Enter key character from the current line To avoid that issue, add an extra nextLine()method call to retrieve the abandoned Enter key character after using these methods.
String
Note that although you’ve already been using strings in a manner similar to how you use primitive objects, a String is actually an instance of a class. Because this class is so commonly used, it is part of every project by default, so you do not need to import it (this is also why you don’t need to import System).
Since Strings are objects, we should have to write (assuming we want to create a String with the literal value "Charlie"):
String name = new String("Charlie");
However, since this is so commonly used, the shortcut
String name = "Charlie";
achieves the same thing (as if String were a primitive type-- but it’s not!).
String methods
Within the String class, there are several useful methods that can be applied.
Some of these methods involve the index of a character in the String. This means simply the location of each character in the String. Note that the first index is numbered 0, not 1, as shown below for the String literal “Hello.”
char |
H |
e |
l |
l |
o |
index |
0 |
1 |
2 |
3 |
4 |
Counting from 0 instead of 1 is referred to as zero-indexed. It is a common error to be "off by one" because of this, so be careful.
Here is a listing of some important String methods. A complete reference can be found here.
- toUpperCase() returns a version of the String in all uppercase
- toLowerCase() returns a version of the String in all lowercase
- length() returns the number of characters in a String (including spaces)
- charAt(int i) returns the character at index i.
- indexOf(char c) returns the first index where c is found (even if c occurs more than once in the String) or -1 if c is not found. To be clear, we do not mean the actual char ‘c’ here; c is a variable to hold any char.
- substring(int i) returns a part of the String starting at index i to the end.
- substring(int i, int j) returns a part of the String starting at index i and going up to (but not including) j.
Random
The Random class is used to generate random numbers. Just like Scanner, you import the Random class, then create a Random object. This object is not a random number-- it is a random number generator that can be used to generate as many random numbers as needed. The methods nextInt(int a) and nextDouble() are used to generate random numbers. Note that nextInt(int a) generates an integer (from 0 to a-1) and nextDouble() generates a double n, between 0 and 1 (including 0, but not 1)
By multiplying and/or adding to the random number generated, you can get outputs in different ranges, as shown in the example below.
import java.util.Random;
public class RandomDemo {
public static void main(String[] args) {
//create a random number generator
Random gen = new Random();
//print a random integer between 0 and 4
System.out.println(gen.nextInt(5));
//print a random double between 0 and 1
System.out.println(gen.nextDouble()); //note the empty () for nextDouble
//print a random double between 0 and 8
System.out.println(8*Math.random());
//print a random integer between 0 and 9
System.out.println(gen.nextInt(10));
//print a random integer between 1 and 10
System.out.println(gen.nextInt(10)+1);
//print a random integer between 100 and 110
//note there are 11 integers from 100 to 110
System.out.println(gen.nextInt(11)+100);
In general to get a random integer between a and b, use nextInt(b-a+1)+b
For example, nextInt(10) + 1 will yield an integer between 1 and 10 and
nextInt(6) + 20 will give an integer between 20 and 25 (20, 21, 22, 23, 24, and 25 is 6 numbers, not 5).
To get a random double in a range other than 0 to 1, multiply by the desired range size. For example, nextDouble()*15 will yield a decimal between 0 and 15 (actually, 14.9999...). Note how the *15 is outside of the parentheses. Unlike nextInt, nextDouble does not take any arguments.
Math
Like String, you do not need to import the Math class-- it is made available by default. All Math methods and data are static. We’ll learn later the full meaning of static, but for now it means that (unlike Scanner and Random) to use Math methods and data, you do not need to create a Math object. Rather, just call the methods on the Math class itself, as in Math.pow(), for example. Math.PI is the value of π (note that there are no parentheses after PI because it’s data in a variable, not a method). Math.random() does the same thing as nextDouble() in the Random class (i.e., generates a random double between 0 and 1, not icluding 1).
Some commonly used methods of the Math class (shown by example) are:
Math.pow(5,3) //raises 5 to the 3rd power = 125.
Math.random() //generates a random double n, 0 ≤ n < 1, such as 0.57483
Math.round(63.812) //rounds to the nearest integer, 64
Math.sqrt(10) //finds the square root of 10 ≈ 3.16
Math.PI //the value 3.1415926… note no () after PI
The methods above are the ones you should know for this course.
A complete list of methods and data is here.
As mentioned earlier Java does not have an operator for exponents (such as 5**3 in Python); you must use the pow() method in the Math class.
Also note that the round() method does not allow for rounding to a number of decimal places-- only to the nearest integer.