Download Reading from files

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Announcements & Review
Last time:
static methods vs
Lab 6 Due Thursday
object methods
arrays of objects
more flight
Today:
reservations
review static vs object
methods
Reading from files
Lecture 19: Reading Input from Files
Class, Variables,
Methods
• Class - a model for an object instance
– one class, lots of objects
• Class variable declarations
– <private/public> <static> type variableName;
• private - only accessible through method calls, e.g., get and set
methods
• public - accessible directly, e.g., objectName.varName
• static - one per class
• non-static - one per object
• Class method declarations
– <private/public> <static> <return type> methodName;
•
•
•
•
private - only accessible within the class
public - accessible from clients
static - invoke on the class
non-static - invoke on an object of the class
Lecture 19: Reading Input from Files
Java Examples in BlueJ
• Adding static methods for input
• Putting static methods together with
arrays
Lecture 19: Reading Input from Files
So far, user input from the
console
stdin.next();
// a string
stdin.nextLine();
// a line of text
stdin.nextInt();
// an integer, etc.
stdin.hasNextInt(); // First make sure there is one
...
Scanner stdin = new Scanner (System.in);
System.out.println(“Input an integer:”)
while (!stdin.hasNextInt()) {
System.out.println(“Input an integer:”)
stdin.nextLine(); // consumes bad input
}
int i = stdin.nextInt();
Lecture 19: Reading Input from Files
Lots of Input? and/or
Persistant Input
Store and read input from a file
Lecture 19: Reading Input from Files
File Input Syntax
Scanner stdin = new Scanner(System.in);
System.out.println("Input a file name: ");
String fileName = stdin.next();
Scanner groceryFile = new Scanner(new File(fileName));
while (!groceryFile.hasNextInt()) {
System.out.println("File did not start with an integer.");
groceryFile.nextLine();
// consumes bad input
}
int totalEntries = groceryFile.nextInt();
Read the file by making it into Scanner object,
and then treat it like stdin, where
stdin = new Scanner (System.in)
Lecture 19: Reading Input from Files
Java Examples in BlueJ
• Reading from a file
• Array of objects initialized from a
file
Lecture 19: Reading Input from Files
More Questions?
Lecture 19: Reading Input from Files
Related documents