Penn CIT 591 - Simple Text (7 pages)

Previewing pages 1, 2 of 7 page document View the full content.
View Full Document

Simple Text



Previewing pages 1, 2 of actual document.

View the full content.
View Full Document
View Full Document

Simple Text

134 views


Pages:
7
School:
University of Pennsylvania
Course:
Cit 591 - Programming Languages & Techniques I
Programming Languages & Techniques I Documents
Unformatted text preview:

Simple Text I O Jan 14 2019 java util Scanner Java finally has a fairly simple way to read input First you must create a Scanner object To read from the keyboard System in do Scanner scanner new Scanner System in To read from a file do File myFile new File myFileName txt Scanner scanner new Scanner myFile You have to be prepared to handle a FileNotFound exception You can even read from a String Scanner scanner new Scanner myString This can be handy for parsing a string Using the Scanner First you should make sure there is something to scan scanner hasNext boolean You wouldn t use this when reading from the keyboard You can read a line at a time Or you can read one token at a time A token is any sequence of nonwhitespace characters scanner next String You must be prepared to deal with exceptions scanner nextLine String Eclipse will tell you what you need to do These return Strings which you can convert to numbers or other types if you like There are also methods to check for and return primitives directly Scanning for primitives You can read in and convert text And test if you have to primitives something to read boolean b sc nextBoolean byte by sc nextByte short sh sc nextShort int i sc nextInt long l sc nextLong float f sc nextFloat double d sc nextDouble hasNextBoolean hasNextByte hasNextShort hasNextInt hasNextLong hasNextFloat hasNextDouble Formatted output Java 5 has a printf method similar to that of C Each format code is width code Some format codes are s for strings d for integers f for floating point numbers Example double pi Math PI System out printf 8s 8s 6d 6d 8f 8 2f n abc def 123 456 pi pi System out printf 8s 8s 6d 6d abcdef ghijkl 12345 6789 Output abc def abcdef ghijkl 123 456 12345 6789 3 141593 3 14 But wait there s more We have just scratched the surface of the Scanner and Formatter classes See the Java API for more details The End


View Full Document

Access the best Study Guides, Lecture Notes and Practice Exams

Loading Unlocking...
Login

Join to view Simple Text 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 Simple Text 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?