|
Reading Input
There are many ways that a program can get input from the outside world. Input can read from a user via the keyboard and the mouse. A Java program can also open a file on a disk drive and read the contents of the file, and also pull in information from over the network, such as by retrieving a web page from a web server. Here we will only look at reading input from the user, either from the console or via a dialog box.
Click here for discussion about reading input via the console or dialog boxes in jGRASP.
One of the two options mentioned in the discussion, above, is to get input from the user via a dialog box. The code below retrieves a number from the user and then doubles it. The input is read via JOptionPane's showInputDialog method. This method always returns the user's input as a String. If a different type is required then the String must be converted to that type. In this case we want the value to be an int so that we can performed some arithmetic on the value (i.e., multiply it by two), so we have to convert the input via a call to Integer.parseInt (or, if we wanted to convert to a double then Double.parseDouble could be used):
import javax.swing.*;
public class ReadingNumbers1
{
public static void main(String [] args)
{
String s = JOptionPane.showInputDialog("Enter a number: ");
int num = Integer.parseInt(s);
int twice = num * 2;
JOptionPane.showMessageDialog(null,
"Twice " + num + " is " + twice);
}
}
Click here for a discussion of this program.
Here is another program that also reads a number from the user and doubles that value, but it gets the number from the user from the console using the Scanner object:
import java.util.*;
public class ReadingNumbers2
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
int twice = num * 2;
System.out.println("Twice " + num + " is " + twice);
}
}
Here is a discussion of the above program (this discussion also includes a demonstration of the jGRASP debugger).
Another source of input for a Java program is a random number generator. Random number generators are used frequently in computer programs for simulations and games. There are a couple of different ways of generating a random number. Here we will use the random method found in Java's Math class. Click here for an introduction to using Math.random. The following program is a third version of the "get a number and double it" program. This version reads a number from the random number generator and doubles it:
public class ReadingNumbers3
{
public static void main(String [] args)
{
int num = (int)(Math.random() * 1000 + 1);
int twice = num * 2;
System.out.println("Twice " + num + " is " + twice);
}
}
|