120 likes | 230 Views
Input/Output in Java. Output. To output to the command line, we use either System.out.print () or System.out.println() or System.out.printf() Examples using println: System.out.println(“One”); System.out.println(“Two”); System.out.println(“Buckle My Shoe”); or
E N D
Output • To output to the command line, we use either System.out.print () or System.out.println() or System.out.printf() Examples using println: System.out.println(“One”); System.out.println(“Two”); System.out.println(“Buckle My Shoe”); or System.out.println(“One\nTwo\nBuckle My Shoe”);
Output Continued • Examples using print & println System.out.print(“One “); System.out.print(“Two “); System.out.print(“Buckle my shoe”); System.out.println();
Output Continued • Examples using + (the concatenate operator) int x = 10, y = 20; System.out.println (“x =“ + x + “\ny=“ + y + “\nx + y = “ + (x + y)); What would be output if the parenthesis around x + y were left off?
Using printf • System.out.printf() is a method that receives multiple arguments. • The first argument is a string that tells how to print the arguments that follow. • Example: %s means print the argument as a string System.out.printf(“%s\n%s\n%s\n”, “One”, “Two”, “Buckle my shoe”);
printf continued int number1, number2, sum; number1=10; number1=30; sum = number1 + number2; System.out.printf(“The sum of %d + %d = %d”, number1, number2, sum);
Command line Input • The Scanner class is used for input from the command line. • The Scanner class is in the package java.util so any program using the Scanner class must first include an import statement that is used to help the compiler locate the class. • All import statements appear first in a java program before the class definition or any other statement (other than comments).
import java.util.Scanner; public class AddTwoNumbers { public static void main(String[] str) { int x, y; //create a Scanner object to get input //System.in refers to standard input object Scanner input = new Scanner(System.in); //Prompt for and read the first integer //using the Scanner object’s nextInt method. //The program waits for the user to type in //an integer and press the ENTER key System.out.println(“Enter the first integer:”); x = input.nextInt();
System.out.println (“Enter the next integer:”); y = input.nextInt(); sum = x + y; System.out.println (“Sum is %d\n”, sum); } //end of main } //end of class AddTwoNumbers
Displaying output using JOptionPane • JOptionPane is a class in the package javax.swing that allows output to be displayed in a dialog box. Example: JOptionPane.showMessageDialog(null, “Welcome\nto\nJava”); produces:
String name = JOptionPane.showInputDialog( “What is your name?”); String message = “Welcome, to Java Programming! “ + name; JOptionPane.showMessageDialog(null, message);