Writing programs with defined variables is essential to demonstrate and test small and simple programs. However, in most cases, we need to perform operations based on the user's input. Therefore, we need to understand how to interact with the computer user through a program. In this section, we will discuss three popular ways to interact with the computer user: Command line arguments (args), where the terminal/command line is used; Scanner, a mechanism that scans a prompt from the computer user; and through JOptionPane, a dialog that permits the user to interact with the computer user through a Graphical User Interface (GUI).
Java programs can run directly from the command line or the terminal, depending on the computer user's operating system.
The part responsible for *holding* the arguments passed through the command-line is an array called args (we will discuss this in Chapter 4) String [] args. The variable `args` will contain 0 or more Strings based on the number of arguments that are passed through the command line/terminal. There are several ways you can access information from the arguments.
args.length: will provide the total number of arguments passed
args[0]: will provide the first argument passed
args[1]: will provide the second argument passed and so on.
Example: A basic program that processes two arguments from the command line and prints them
Suppose that we have a program called ArgsProcessor01.java and it looks like this:
1. public class ArgsProcessor01{
2. public static void main(String [] args){
3. System.out.println(args[0]);
4. System.out.println(args[1]);
5. }
6. }
when the program is called from the command line, it looks like this:
java ArgsProcessor01 hello world
hello
world
where:
java is the command to run the program
ArgsProcessor01 is the name of the program we want to execute
hello is the first argument for the program ArgsProcessor01
world is the second argument for the program ArgsProcessor01
once we run the program, Line 3 and Line 4 will execute, and it will print the args[0], which corresponds to "hello", and args[1], which corresponds to "world". Therefore, the program will print hello and world.
The String [] args explicitly mentions Strings. In our previous example, the hello and the world arguments both were Strings. But, how can we process values that are not Strings? For example, integers or real numbers?
For that, we need to use "helpers" called wrappers. There is one wrapper for each primitive data type. Table 4 provides some examples of these.
Example: transforming Strings into numbers using wrappers
Suppose that we have a program called ArgsProcessor02.java and it looks like this:
1. public class ArgsProcessor02{
2. public static void main(String [] args){
3. int x = Integer.parseInt(args[0]);
4. int y = Integer.parseInt(args[1]);
5. int z = x + y;
6. System.out.println("The sum of "+x+" + "+y+" is "+z);
7. }
8. }
This basic program processes two arguments from the command line, transforms them into integers using the Integer wrapper and then uses concatenation to construct an informative output.
when the program is called from the command line, it looks like this:
java ArgsProcessor02 5 2
The sum of 5 + 2 is 7
One of the most popular and useful Objects that a computer programmer will use is called Scanner. The Scanner is used to scan or inspect an input from the computer user token by token. The Scanner has several purposes other than simply scanning the user's input; it can also be used to scan a String or to read a file.
To use Scanner you must incorporate the following three steps into your code:
Import the Scanner library
Create a Scanner object -- a scanning handler
Use Methods to Scan User's Input
Import the Scanner Library
To use the Scanner object, it is important to request assistance from the Java Library that contains the Scanner by typing the following line at the very top of the program
import java.util.Scanner;
The import line is important to consider as the very first line of code in a program. If you don't include this line, Java will not recognize the functionality of Scanner and Errors will be thrown.
Create a Scanner object
Anytime that a Scanner is required, an object of type Scanner must be created. In Java, the notion of "creating a new object" means that the program will store a mechanism in memory to use functionalities and other characteristics in the program. The way is done this is by using the keyword new after the = sign, as follows:
Scanner input = new Scanner(System.in);
where:
Scanner is the object being created.
input is the variable name assigned to this object.
The = is an assignation operator
new is the keyword used to create a new *instance* of the object Scanner
System.in is the mechanism that will permit to interact with the computer user. The Scanner will use the "input from the system (i.e., System.in).
This is the general format in which we will be creating objects in Java.
Use Methods to Scan User's Input
Scanner counts with several methods used to extract data from the computer user. A complete list of the methods can be found at [Java API](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html). Some of the methods are shown in Table 5.
In contrast to interacting with the computer user through args, Scanner has the ability to open a dialog with the computer user and provide the opportunity to input an answer based on the question the program requests.
Example
Let us translate the example ArgsProcessor01; instead of providing arguments, have the program request two strings to the computer user. The program shall be called ScannerExample01.java.
1. import java.util.Scanner;
2. public class ScannerExample01{
3. public static void main(String [] args){
4. Scanner input = new Scanner(System.in);
5. System.out.print("Enter the first word");
6. String first = input.nextLine();
7. System.out.print("Enter the second word");
8. String second = input.nextLine();
9. System.out.println(first);
10. System.out.println(second);
11. }
12. }
By compiling and running this program, the program looks like this:
>javac ScannerExample01.java
>java ScannerExample01
Enter the first word: [hello]
Enter the second word: [world]
hello
world
Java counts with several Graphical User Interfaces (GUI) libraries. These libraries provide "more user-friendly" applications. One of these libraries is the JOptionPane. To use this library is important to import the library javax as follows:
import javax.swing.JOptionPane;
Similar to what we did with Scanner.
ACM CCECC
[Scope, Comments, and Programming Style]
SDF-18. Apply consistent documentation and program style standards.
[Keyboard Input and Dialog Boxes]
HCI-04. Write a simple application that uses a modern graphical user interface.
AP CS A
[Scope, Comments, and Programming Style]
MOD-2.C Describe the functionality and use of program code through comments.
MOD-2.C.1 Comments are ignored by the compiler and are not executed when the program is run.
MOD-2.C.2 Three types of comments in Java include /* */, which generates a block of comments, //, which generates a comment on one line, and /** */, which are Javadoc comments and are used to create API documentation.
CS1
[Scope, Comments, and Programming Style]
130.421.c.2.d Write programs with proper programming style to enhance the readability and functionality of the code by using meaningful descriptive identifiers, internal comments, white space, spacing, indentation, and a standardized program style;
130.421.c.6.s Demonstrate an understanding of the concept of scope;
[Keyboard Input and Dialog Boxes]
130.421.c.2.b Create interactive console display interfaces, with appropriate user prompts, to acquire data from a user;
Design, write, test, and debug a program that effectively uses the different structured data types provided in the language like strings, arrays/lists, dictionaries, sets
Trace the flow of control during the execution of a program (both correct and incorrect).
Use appropriate terminology to identity elements of a program (e.g., identifier, operator, operand)