Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 User Input Create a Scanner object: Scanner inx = new Scanner(System.in); System.out.println("Type a number"); int x = inx.nextInt(); System.out.println("The.

Similar presentations


Presentation on theme: "1 User Input Create a Scanner object: Scanner inx = new Scanner(System.in); System.out.println("Type a number"); int x = inx.nextInt(); System.out.println("The."— Presentation transcript:

1 1 User Input Create a Scanner object: Scanner inx = new Scanner(System.in); System.out.println("Type a number"); int x = inx.nextInt(); System.out.println("The num you typed is " + x); Requires an import statement: You can just click and eclipse will add this for you: import java.util.Scanner;

2 Scanner class The Scanner class is a class in java.util that allows us to read values of various types We can read input from either the keyboard (as we saw) or from a file (to be seen) When reading from the keyboard, we need the parameter to be System.in We’ve been using System.out- writes to the console. System.in reads from the console (little window below the programming window in Eclipse) Like standard input (stdin) in c++

3 What the Scanner reads: The Scanner looks for tokens in the input. A token is a series of characters that ends with whitespace. a blank, a tab, a carriage return, or the end of the file. Methods for reading tokens:.nextInt().nextDouble().nextFloat().next() // next String.nextLine() And then there’s.close() MORE TO COME!

4 Example: Scanner in = new Scanner(System.in); System.out.println("Enter an int, a float, a double and a string."); System.out.println("Separate each with a blank or return."); int x1 = in.nextInt(); float f1 = in.nextFloat(); double d1 = in.nextDouble(); String s1 = in.nextLine(); System.out.println("Now enter another value."); String s2 = in.next(); System.out.println("Here is what you entered: "); System.out.println(x1 + " " + f1 + " " + d1 + " " + s1 + " and " + s2); in.close(); Enter an int, a float, a double and a string. Separate each with a blank or return hi there how are you Now enter another value. no Here is what you entered: hi there how are you and no

5 Processing Files File class contains a reference to an actual file location on your machine Special classes can read/write data to the file Scanner can actually read a file just like console input But we have to make a File object from the file class first: File myFile = new File(“myFile.txt”); //myFile.txt is the name of the file on your computer. Scanner in = new Scanner(myFile); if myFile.exists() //.exists is a method that checks to see if the myFile object was successfully created. (Why wouldn’t it have been?) What must it return? You can now use in to read from myFile.txt just like you read from the keyboard: int x1 = in.nextInt(); float f1 = in.nextFloat(); double d1 = in.nextDouble(); String s1 = in.nextLine(); String s2 = in.next();

6 Scanning in a file: Now we may want to use a few other scanner class methods:.hasNext() // returns true if there is more data to be read.hasNextInt() //returns true if the next value is an int.hasNextFloat() // returns true if the next value is a float.hasNextDouble() // returns true if the next value is a double We’ll likely use the.hasNext method (how?)

7 int[][] matrix = new int[][]; File fl = new File(filename); if (fl.exists()) { System.out.println("The file exists!"); } Scanner fn = new Scanner(fl); int row = 0; while (fn.hasNext()) { String line = fn.nextLine(); System.out.println(line); String[] numarr = line.split("\t"); for (int i = 0; i

8 Exceptions What could go wrong when we are trying to write data to a file? out of disk space don't have permission to write disk disconnected during our write file "locked" by a different program (maybe another program is writing to it when you want to…) etc

9 Exceptions We want to check for some exceptions, especially if we know it’s something that occurs regularly. Certain methods in java create exceptions for us They “throw an exception” File IO (the Scanner class) definitely creates exceptions for us. Some of the file IO exceptions are: IOException EOFException FileNotFoundException

10 Try…Catch We use Try…Catch to catch exceptions that are thrown. So if a method might “throw an exception” if something goes wrong, we can try it. If we don’t succeed and an exception is thrown, we “catch it. E.g.,: File fl = new File(filename); try { Scanner fn = new Scanner(fl); int row = 0; while (fn.hasNext()) { String line = fn.nextLine(); arr[row] = line; row++; } fn.close(); } catch (FileNotFoundException e) { System.out.println(“e.getMessage()"); System.exit(0); }

11 You can catch more than one exception: private int[][] makeMatrix(String filename) { int[][] matrix = new int[13][13]; File fl = new File(filename); try { Scanner fn = new Scanner(fl); int row = 0; while (fn.hasNext()) { String line = fn.nextLine(); System.out.println(line); String[] numarr = line.split("\t"); for (int i = 0; i

12 In general: There’s Exception – the catch-all exception that’s thrown. To find out what the problem was, use the Exception object’s getMessage method. E.g., try { int x = 10; int y = 0; int z = x/y; System.out.println(z); } catch (Exception err) { System.out.println(err.getMessage()); } Google other Exception errors if you want to use them.

13 Writing to a file: System.out.println is actually a special instance of PrintStream File myOutputFile = new File(“myOutputFile.txt”); PrintStream output = new PrintStream(myOutputFile); PrintStream “throws an error” so we will want to try it and, if unsuccessful, catch the error.

14 For example: public void makefile() { File f1 = new File("testout.txt"); try { PrintStream outfile = new PrintStream(f1); for (double[] x: newmatrix) { for (double y: x) { outfile.print(y + " "); } outfile.println(); } outfile.close(); } catch(IOException io) { System.out.println(io.getMessage()); }

15 How about formatting? In the previous example we were printing out doubles generated randomly. We get: This is ugly, and we often don’t care about the th place. Can we format?

16 Formatting: Instead of using print, use format, e.g, System.out.format(“”); Outfile.format(); And then we format, e.g.,: Double pi = ; System.out.format(“%3.2f”, pi); Prints: 3.14 %f prints a double or float out to 6 places %.3f prints a double or float with 3 values after the decimal (but as many numbers as needed) %4.3f prints a double with 3 values after the decimal but the whole string occupying 4 places. It doesn’t truncate the number before the decimal. However, if the number is smaller than the first number (e.g., %10.3), it will make the whole number 10 characters long, including the decimal, then add spaces to the left.

17 More formatting: Integer formatting: %d prints an integer with as many digits as needed %4d prints an integer with as many digits as needed, but always at least 4, with spaces to the left %04d prints an integer with as many digits as needed, but always at least 4, with zeros to the left Examples: System.out.format(“%d, %4d, %04d”, 34291, 34, 34); Prints: 34291, 34, 0034

18 Formatting Strings: %s prints the string (the whole string) %15s prints out a string with the specified number, right justified. %-15s prints out the string with the specified number, left-justified E.g., System.out.format("%s: %15s: %-15s:", "echidna", "wombat", "puffin"); Prints: echidna: wombat: puffin :


Download ppt "1 User Input Create a Scanner object: Scanner inx = new Scanner(System.in); System.out.println("Type a number"); int x = inx.nextInt(); System.out.println("The."

Similar presentations


Ads by Google