Download presentation
Presentation is loading. Please wait.
Published bySheryl Miles Modified over 8 years ago
1
Console Input and Output JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. TM
2
4-2 Libraries l Java programs are usually not written from scratch. l There are hundreds of library classes for all occasions. l Library classes are organized into packages. For example: java.util — miscellaneous utility classes java.awt — windowing and graphics toolkit javax.swing — newer GUI package Swing
3
4-3 import l Full library class names include the package name. For example: java.awt.Color javax.swing.JButton import statements at the top of your program let you refer to library classes by their short names: import javax.swing. JButton ;... JButton go = new JButton ("Click here"); Fully-qualified name
4
4-4 import (cont’d) You can import names for all the classes in a package by using a wildcard. * : import java.awt.* ; import java.awt.event.* ; import javax.swing.* ; java.lang is imported automatically into all classes; defines System, Math, Object, String, and other commonly used classes. Imports all classes from awt, awt.event, and swing packages
5
4-5 Console Output l The standard output stream for Java is called System.out. We will use System.out along with the print and println methods to write output to the screen. println adds a newline on the end of what you print, print does not. l Note that you do not need to import any library since Java.lang defines System and is automatically imported into all classes.
6
4-6 Console Output (cont’d) Examples of writing to the screen: system.out.print(“Enter the sides of a triangle”);//prints a string literal system.out.println(“Done ”+ count + ” words.”);//would look like: //Done: 23 words //then go to newline
7
4-7 Console Input In order to prompt the user for input we are going to use the Scanner class. In order to use the Scanner class you must include the statement import java.util.Scanner; at the top of your program.
8
4-8 Console Input (cont’d) To open the standard input stream for reading keyboard input use Scanner console = new Scanner(System.in); l You must include a statement like the one above before you can begin getting information from the keyboard. l Note that console is the name that you give the input stream (you can give it any name).
9
4-9 Console Input (cont’d) Examples for reading data from the keyboard : int n = console.nextInt(); // reads an integer double x = console.nextDouble(); // reads a double String word = console.next(); // reads a contiguous string of // non-whitespace characters String line = console.nextLine(); // reads an entire line including whitespace
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.