CMUQ 15-121 Loops, Strings, I/O, and Random
- 1. Java API
- 2. Incrementors/Decrementors
- 3. Loops
- 4. Strings
- 5. Using the Scanner for I/O
- 6. Generating Random Numbers
1. Java API
One very nice thing about Java is that is comes with a large, robust library of code that you can make use of when building your programs. This library (called the Java API) is meticulously documented at https://docs.oracle.com/javase/8/docs/api/. At that link you can find the details of every class available in the API, and usually some examples of how to use them.
The Java API will become your very close friend during this class, and you will become very familiar with it.
2. Incrementors/Decrementors
2.1. The Basics
In Python, when you want to increment or decrement an integer, you usually do something like…
// Increment i by 1 i += 1 // Decrement i by 1 i -= 1
You can do the same thing in Java, but by convention we tend to do it a different way by using incrementors and decrementors:
public class IncrementorDemo { public static void main(String[] args) { int i = 10; // Two different ways to increment i by one i++; ++i; // Two different ways to decrement i by one i--; --i; } }
2.2. Pre vs. Post
If i++
(post incrementing) and ++i
(pre incrementing) both increment i
by 1, then what’s the difference between them? When used on their own, there is no difference. The difference occurs when they are used as part of a larger expression. Consider the following code:
public class PrePostDemo { public static void main(String[] args) { int a = 10; int b = 10; int c = 7 + a++; int d = 7 + ++b; System.out.println("a is "+a); System.out.println("b is "+b); System.out.println("c is "+c); System.out.println("d is "+d); } }
Consider line 7 of the code. What value is used for a
in that expression? 10 (the value before incrementing) or 11 (the value after incrementing)? The answer depends on whether the ++
occurs before or after the variable. If it occurs after the variable (like line 7), then a
is incremented after the operation occurs. If it occurs before the variable (like line 8), then a
is incremented before the operation occurs. It is important to note that in both cases the variables are still incremented.
The output from the above program is:
a is 11 b is 11 c is 17 d is 18
Make sure you study it an understand why. This is likely to come up on quizzes and exams…
2.3. Quick Exercise
See if you can figure out what the following program will print. After you have worked it through on paper, run the code in Eclipse and see if you are correct.
public class IncrementorExercise { public static void main(String[] args) { int e = 5; System.out.println(5 + e++ + ++e - e++ + --e - e-- ); System.out.println(e); } }
3. Loops
There are three basic types of loops in Java: While loops, for loops, and do-while loops.
3.1. While Loops
While loops in Java are almost identical to those in Python. The loop has conditional that is checked before every run of the loop.
Consider the following example:
public class WhileLoopDemo { public static void main(String[] args) { // Print out all the numbers from [0,10) int i = 0; while(i < 10) { System.out.println(i); i++; } } }
3.2. For Loops
A basic for loop in Java is very different from one in Python. It contains an initializer, termination condition, and incrementor.
Consider the following example:
public class ForLoopExample { public static void main(String[] args) { // Print out all the numbers from [0,10) /* * The loop below can be thought of as follows: * 1. Before the loop runs, a new integer i is created and set to 0. * 2. The code inside the loop (in this case the print statement) runs once. * 3. The conditional check (i < 10) runs. If the conditional returns false * (meaning that i >= 10), then the loop stops. Otherwise it continues. * 4. The incrementor (i++) runs and changes the value of i. * 5. Go back to step 2. */ for(int i=0; i < 10; i++) { System.out.println(i); } } }
3.3. Do-While Loops
The last type of loop is a do-while loop. It is very similar to a standard while loop, except that the conditional is checked after each run of the loop instead of before. This means that the loop contents always run at least once, even if the loop conditional fails on the initial try.
Consider the following example:
public class DoWhileLoopDemo { public static void main(String[] args) { /* * Even though the conditional is false from the beginning, the loop * always runs the first time because the conditional is checked after * each loop iteration. */ int a = 5; do { System.out.print("From the do-while: "); System.out.println(a); a--; } while (a > 10); // Similar code from a normal while loop doesn't run at all int b = 5; while(b > 10) { System.out.print("From the while: "); System.out.println(b); b--; } } }
4. Strings
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
Strings are not a primitive type in Java, but they are used so often that we tend to think of them that way.
- String variables store references (the address), not the actual characters of the string.
- Strings are immutable (can’t be changed).
- Useful operations:
Method Description charAt
Get a single character from a string compareTo
Compare two strings contains
See if a string contains another equals
Check equivalence
Don't use == for stringslength
Length of a string substring
Copy part of a string into a new string trim
Remove characters at the beginning and end of a string
5. Using the Scanner for I/O
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
The Scanner is a class that allows for easy input from a user. There are a few important rules when using a scanner:
- You must import
java.util.Scanner
- You must declare a Scanner variable (which will reference the Scanner), create a Scanner object (use
new
), and bind it to standard input (System.in
) - When you print a prompt for the user, you should use
print
instead ofprintln
. (Can you figure out why?) - Here are some useful methods of the Scanner:
Method Description next()
Read a String
Note that this reads characters until a space, so it can't read multi-word strings properly.nextInt()
Read an Integer nextDouble()
Read a Double nextLine()
Read an entire line as a String
This is the one you should use the most.
Here is a sample program making use of the Scanner class. Try running it with various inputs and see if you can make it crash. It isn’t very reliable, is it? We’ll work on this later.
import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) { Scanner userInput = new Scanner(System.in); // Input a String System.out.print("Please enter a string: "); String inputStr = userInput.next(); // Input an Integer System.out.print("Please enter an integer: "); int inputInt = userInput.nextInt(); // Input a Double System.out.print("Please enter a double: "); double inputDouble = userInput.nextDouble(); // Close the scanner when I'm done. userInput.close(); System.out.println("Thanks for saying:"); System.out.println(inputStr); System.out.println(inputInt); System.out.println(inputDouble); } }
6. Generating Random Numbers
https://docs.oracle.com/javase/8/docs/api/java/util/Random.html
It is frequently very useful to be able to generate random values. This can help you with testing (you can generate random values to test your functions with) or even use them to introduce some variety into a simple game. Java provides random number generation as part of its standard library.
Take some time now to follow the link above to the API for Random
. Take a look at the methods it includes that start with next
. This gives you an idea of the types of random data that can easily be produced.
Consider the following sample code for an example of how to use Random
:
import java.util.Random; public class RandomDemo { public static void main(String[] args) { Random rand = new Random(); System.out.println("Here are 10 random integers:"); for(int i=0; i < 10; i++) { int temp = rand.nextInt(); System.out.println(temp); } System.out.println("Here are 10 random integers from the range [0,5)"); for(int i=0; i < 10; i++) { int temp = rand.nextInt(5); System.out.println(temp); } double randomDouble = rand.nextDouble(); System.out.print("Here is a random double: "); System.out.println(randomDouble); } }
It is important to note that while Random
can produce seemingly random values, they are actually pseudo-random, meaning that they are mathematically derived from an initial state. For most things you want randomness for, this is just fine. If you are doing security, this isn’t fine and you’ll need to find a better source of randomness. (This probably isn’t something you need to worry about in this class, but it is interesting to note.)