Presentation is loading. Please wait.

Presentation is loading. Please wait.

User Input You’ve seen this: A Scanner object:

Similar presentations


Presentation on theme: "User Input You’ve seen this: A Scanner object:"— Presentation transcript:

1

2 User Input You’ve seen this: 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;

3 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 An Input Stream 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++

4 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!

5 Example: Enter an int, a float, a double and a string.
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

6 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();

7 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?)

8 int[][] matrix = new int[][]; File fl = new File(filename); if (fl
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<numarr.length;i++){ matrix[row][i] = Integer.parseInt(numarr[i]); row++; fn.close(); What does this do?

9 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

10 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

11 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);

12 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<numarr.length;i++){ matrix[row][i] = Integer.parseInt(numarr[i]); } row++; fn.close(); catch (FileNotFoundException e) { System.out.println("File not found: " + e.getMessage()); catch (IOException e) { System.out.println(e.getMessage()); System.exit(0); return matrix; You can catch more than one exception:

13 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.

14 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.

15 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());

16 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?

17 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 %4.3f prints a double with 3 values after the decimal but the whole string occupying 4 places. It never truncates 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.

18 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

19 Formatting Strings: %s prints the string (the whole string)
%15s prints out a string with the specified number of characters, 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 :

20 Formatting, Special Characters:
Special characters in formatting are preceded with a \ \t prints a tab \n adds a new line \\ inserts a backslash \’ inserts a single quote \” inserts a double quote E.g., String[] s = {"cat","dog","echidna","wombat","whale","bunny"}; for (int i = 0; i < s.length; i++) { System.out.format("%s\t",s[i]); if ((i+1)%2 == 0) { System.out.format("\n"); } Prints: cat dog echidna wombat whale bunny:

21 Try: Write a method that prints out a 3x4 Matrix of integers (random numbers)
Random r = new Random(); int arr[][] = new int[3][4]; for (int i = 0; i < arr.length*arr[0].length; i++) { arr[Math.floorDiv(i,4)][i%4] = r.nextInt(10); } for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.format("%2d\t",arr[i][j]); System.out.format("\n");


Download ppt "User Input You’ve seen this: A Scanner object:"

Similar presentations


Ads by Google