User and Programmer Interface:
Use Scanner class to take keyboard information.
Examples:
import java.util.Scanner;
public class UserInterface
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter two numbers");
int num1 = sc.nextInt(); //public int nextInt()
int num2 = sc.nextInt(); //Scans the next token of the input as an int.
System.out.println('\n'+"You entered "+num1+ " and "+num2+"."+'\n');
System.out.println(num1 + " + " +num2 + " = " +(num1+num2));
}
}
import java.util.Scanner;
public class UserInterface
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter your first name");
String name = sc.next();
System.out.println('\n'+"Your name is "+name+".");
}
}
import java.util.Scanner;
public class UserInterface
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the unit price:");
double price = sc.nextDouble();
System.out.println('\n'+"The unit price is "+price+".");
}
}
import java.util.Scanner;
public class UserInterface
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
String name = sc.nextLine();
System.out.println('\n'+"Your name is "+name+".");
}
}
Using Dialog Boxes for Input and Output
import javax.swing.JOptionPane;
public class UserInterface
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog("Enter price:");
double price = Double.parseDouble(input);
JOptionPane.showMessageDialog(null, "Price: " + price);
System.exit(0);
}
}
import javax.swing.JOptionPane;
public class UserInterface
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog("Enter the first integer:");
int num1 = Integer.parseInt(input);
String input1 = JOptionPane.showInputDialog("Enter the second integer:");
int num2 = Integer.parseInt(input1);
JOptionPane.showMessageDialog(null, num1 + " + " + num2 + " = " + (num1+num2));
System.exit(0);
}
}
import javax.swing.JOptionPane;
public class UserInterface
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog("Enter your name:");
JOptionPane.showMessageDialog(null, "Nice to meet you, " + input);
System.exit(0);
}
}
