Earlier we talked about the output system. We've also covered variables and literals. But so far the programs we build stay the same. One direction, only printing output with nothing interactive.
One way to make your program more interactive is to use the input system.
How do you build an input system in Java, and what can you do with it? Let's go deeper.
A Quick Look at the Input System and Scanner
The input system is the command you use to tell the computer to take input from the user.
In general that input can be keyboard typing, a mouse click, a screen touch, and so on.
Even though there are many ways to take input, our focus this time is typing alone. So we'll read the user's typing on the terminal screen and put it into a variable.
In Java, the input system is served by an object named Scanner. The object is already available, and you can use it after importing a library first, either java.util.* or java.util.Scanner.
Library is a collection of code that's already written, so you don't have to write code from scratch for trivial things like this input system.
In its initialization, the Scanner object must have an input source as its argument. Since we take input from the terminal this time, the argument given is System.in.
For a clearer picture of Scanner, try typing and running this code:
import java.util.Scanner; // import Scanner
public class SistemOutput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // initialize the scanner object
System.out.print("Masukkan nama: ");
String nama = scanner.nextLine(); // read input from the keyboard
System.out.println("Halo " + nama); // output the input result
}
}
When the program runs, it stops at Masukkan nama:. That's because when you call scanner.nextLine() the program waits for input from the user.
Next, type a name, say "Inva", then press enter. The output "Halo Inva" comes out. In full it looks like this:
Masukkan nama: Inva
Halo Inva
That example uses the nextLine method. It takes input of the String type, in other words letters or a group of letters.
There's usually a misunderstanding between Scanner and scanner. They look alike at a glance, but the 2 keywords are very different. Scanner with a capital "S" is the object, while scanner with a lowercase "s" is the identifier we create to hold the Scanner object. You could say scanner is the variable holding Scanner.
Since
scannerin this example is an identifier, like identifiers in general you can rename it however you like. What matters is that when you call it, you use the same identifier.
The Methods in Scanner
Using a method on a Scanner object has to match the data type of the input, so many methods are available, among them:
nextLine: takesstringinputnextInt: takesintinput, or whole numbersnextFloat: takesfloatinput, or decimal numbers
There are other methods too, like nextBoolean, nextDouble, and nextLong. Their names make their purpose clear.
Using these methods is roughly the same as before. You create a Scanner object first, then call the method that fits. For example like this.
import java.util.Scanner;
public class SistemOutput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Masukkan nama : ");
String nama = scanner.nextLine();
System.out.print("Masukkan angka bulat : ");
int bulat = scanner.nextInt();
System.out.print("Masukkan angka pecahan: ");
float pecahan = scanner.nextFloat();
float hasil = bulat + pecahan;
System.out.println("Halo " + nama);
System.out.printf("Hasil dari %d + %.2f adalah %.2f", bulat, pecahan, hasil);
}
}
In that program the user is meant to enter 3 inputs. First a name with the string data type, then a whole number with the int data type, and last a decimal number with the float data type. Since all of them have different data types, the methods used have to match.
Next you add the whole number and the decimal number and put the result in a variable. That variable is of type float because pecahan is also of type float.
Last, we output the name with println, and the whole number, the decimal number, and the result with printf as you can see above. If you forgot what that printf does, look again here.
If we run it and enter data of matching types, the result comes out more or less like this.
Masukkan nama : Inva
Masukkan angka bulat : 23
Masukkan angka pecahan: 3.1415
Halo Inva
Hasil dari 23 + 3.14 adalah 26.14
You can see the result matches the logic we built earlier. But if we enter data of the wrong type, the program errors out on the spot. Feel free to try it.
Input Separator Characters in Java
Java doesn't actually read input from the button press; the character that button produces is what it really uses. Confused? Here's how it works..
When we use the nextLine method, the scanner object reads our whole input line until it finds the \n character, which we call an escaped character newline. To enter that \n character we use the enter key on the keyboard.
It's a different story with methods other than nextLine, such as nextInt and nextFloat. Those methods use not only the \n character as a marker but other whitespace characters too, like space.
For a clearer picture, let's go straight to code.
import java.util.Scanner;
public class SistemOutput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Masukkan 2 angka dipisah dengan spasi: ");
int angka1 = scanner.nextInt();
int angka2 = scanner.nextInt();
int hasil = angka1 + angka2;
System.out.printf("hasil dari %d + %d adalah %d", angka1, angka2, hasil);
}
}
In that code we mean to add 2 numbers that come from the user's input. This time we enter 2 numbers separated by a space character, say 23 7. The result looks like this.
Masukkan 2 angka dipisah dengan spasi: 23 7
hasil dari 23 + 7 adalah 30
You can see the result matches the input given, 30 as the sum of 23 and 7.
If you use the enter key instead, the result is the same, more or less like this:
Masukkan 2 angka dipisah dengan spasi: 23
7
hasil dari 23 + 7 adalah 30
Remember, this doesn't apply to input with nextLine. That's because nextLine only reads input once it finds the \n character, in other words when you press enter.
A Note: Watch Out for Scanner
As mentioned above, methods other than nextLine are processed as soon as they find a whitespace character. That turns out to cause a small problem in Java.
The problem shows up when we call nextLine after calling another method like nextInt or nextFloat. For example like this.
import java.util.Scanner;
public class SistemOutput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Masukkan angka : ");
int angka = scanner.nextInt();
System.out.print("Masukkan nama : ");
String nama = scanner.nextLine();
System.out.println("Isi variabel angka : " + angka);
System.out.println("Isi variabel nama : " + nama);
}
}
Now run that code and enter input as prompted.
When you do, the result comes out more or less like this.
Masukkan angka : 24
Masukkan nama : Isi variabel angka : 24
Isi variabel nama :
Well now, when you enter a number and press enter, the second input asking for a name never runs, and the output appears right away. Why is that?
That's because the nextInt method and its siblings don't consume the \n character, the newline. So when we press enter after entering a number, the \n character is still left behind.
Remember that nextLine reads a line until it finds the \n character. Since that character is still left over after the nextInt call, nextLine reads an empty line. That's also why the program never asks for the name.
To learn more about this, read this stackoverflow thread
So what's the fix?
The fix is easy: just ask for input again. So the earlier code becomes like this.
import java.util.Scanner;
public class SistemOutput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Masukkan angka : ");
int angka = scanner.nextInt();
System.out.print("Masukkan nama : ");
scanner.nextLine(); // add this line
String nama = scanner.nextLine();
System.out.println("Isi variabel angka : " + angka);
System.out.println("Isi variabel nama : " + nama);
}
}
If you run it, the output will match.
Masukkan angka : 24
Masukkan nama : Inva
Isi variabel angka : 24
Isi variabel nama : Inva
A bit of explanation: in that code we call the nextLine method 2 times. The first call reads and consumes the leftover \n character from the earlier nextInt. The second call takes the name input from the user.
So don't be surprised that the first nextLine call doesn't involve any variable assignment.
Next Up
Now that you know about the input system in Java, next time we'll go deeper into variables and their data types.
Happy coding