DOC PREVIEW
USF CS 110 - Java Input and Output

This preview shows page 1 out of 2 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 2 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 2 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

CS 110: Introduction to Computer Science Spring 2008 Java I/O Input: The Scanner class The scanner class is used to read in data from the end-user, providing functionality similar to Python’s input() and raw_input() methods. Example: import java.util.*; class ScannerDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string:"); String s = scanner.next(); System.out.println(s); } } The specification for Scanner class can be found within the Java 1.5 API: http://java.sun.com/j2se/1.5.0/docs/api/index.html Scanner has nextX methods for each type: Java Python s =scanner.next() s = raw_input() i=scanner.nextInt() i = input() f=scanner.nextFloat() f = input() Consider the line: Scanner scanner = new Scanner(System.in); The parameter is a file. System.in is a system defined ‘file’ mapped to the keyboard. If you want to read from a file, you can just do something like the following: Scanner sc = new Scanner(new File("myNumbers")); The 'hasNext()' method can be used to see if at end of file: while (sc.hasNext()) { s = sc.next() }CS 110: Introduction to Computer Science Spring 2008 We’ll look at file I/O in more detail later. Output: System.out.println In Java, everything is object-oriented. So you can’t just call a 'print' function as in Python. Even printing requires an class, in this case a Java library class named System: Java Python System.out.print("hello world") print ("hello world") In Class Assignment: For your Person class, write a method named ‘readData’ that allows the user to enter the data (name, age) for a person. To test your method add code like the following to your main: Person ralph= new Person(); ralph.readData(); System.out.println(ralph.name);


View Full Document

USF CS 110 - Java Input and Output

Download Java Input and Output
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Java Input and Output and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Java Input and Output 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?