Courses‎ > ‎AP Computer Science‎ > ‎Konstantinovich‎ > ‎

2018-11-08 Files/Args/Random

posted Nov 8, 2018, 6:21 AM by Konstantinovich Samuel   [ updated Nov 8, 2018, 10:56 AM ]
Goal: Terminal arguments, Files

Useful minor new things:


For easy printing of arrays

import java.util.Arrays;
public class Demo0{
  public static void main(String[]args){   
    int[]nums = {1,2,3};
    System.out.println(Arrays.toString(nums));
  }
}




For converting Strings to primitives:
The wrapper classes have a parse command that converts from string to that wrapper class.

Integer:
    static int parseInt(String s) - Parses the string argument as a signed decimal integer.


Integer.parseInt("20") returns 20
Integer.parseInt("+20") returns 20
Integer.parseInt("-20") returns -20


public class Demo1{
  public static void main(String[]args){   
    String s = "123";
    int x = Integer.parseInt(s);
    System.out.println(x+1);//you can't add unless it is an int
  }
}



Terminal commands often have arguments!

Arguments are stored in the args variable of the main.


Here is how we access them:
import java.util.Arrays;
public class Demo1{
  public static void main(String[]args){
    //args has your terminal options
    System.out.println(Arrays.toString(args));
  }
}


Now call your program on the terminal:

java Demo1 fish 123 abba good day

This is like saying: 
    args = {"fish", "123", "abba", "good", "day"};


This can be used to pass values into the program:

public class Demo2{
  public static void main(String[]args){

    int defaultSize = 10;    
    //Only when it exists, get a value from the arguments
    if(args.length > 0){
        defaultSize = Integer.parseInt(args[0]);
    }
    
    //DO STUFF WITH defaultSize

  }  
}




We NEED to know about something new before we touch files:

Checked Exceptions  (you haven't seen these yet)

          Object
                \
            Throwable (Can be used with the throw command)   / \ Error Exception (checked)
 (unchecked) \         RuntimeException (unchecked)


Runtime Exceptions are things like indexOutOfBoundsException, or OutOfMemoryError. They can crash your program and dump the stack trace to the terminal.

FileIO exceptions like FileNotFoundException are not meant to happen at runtime, so they are REQUIRED to be caught or declared as thrown(re-throw the exception). This is by design as they are intended to be handled by the programmer.


Checked Exceptions : are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either:
(a) handle the exception
OR
(b) it must specify the exception using throws keyword.

If you do NOT do either (a) or (b)you will get a compile time error see this:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception EXCEPTION_NAME_HERE; must be caught or declared to be thrown

We will focus on (a) first, then talk about (b) after.

These exceptions are important enough for the compiler to make sure you handle them or explicitly not handle them.




Now let us look at files: (and see how to 1) handle, and 2) declare as thrown )


1) Handling requires a try/catch

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Demo2b{
  public static void main(String[]args){
    String fileName = "file.txt";
    try{
      File f = new File(fileName);//can combine
      Scanner in = new Scanner(f);//into one line
      
        //NOW read the file here...
      
    }catch(FileNotFoundException e){
      System.out.println("File not found: " + fileName);
      //e.printStackTrace();
      System.exit(1);
    }
  }
}


2) We declare using throws if we want to handle it later. Since the file constructor didn't have to deal with the problem, there must be a way to "handle the problem later" and that is by using the keyword throws

When a method "throws ExceptionName" that tells java that you want to handle the exception in a different method.
In this example foo doesn't want to handle the problem, so we push off the responsibility to the method that called foo; in this case that is the main.

Consider this diagram: (Where the downward arrows indicate which methods call which other methods)



import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Demo2c{

    public static void foo(String fileName) throws FileNotFoundException{
      File f = new File(fileName);//can combine
      Scanner in = new Scanner(f);//into one line
      
        //NOW read the file here...
    }
    public static void main(String[]args){
        String fileName = "file.txt";
        try{
                       foo(fileName);
     
        }catch(FileNotFoundException e){
          System.out.println("File not found: " + fileName);
          System.exit(1);
        }

  }
}




//WE DO NOT DO THIS EVEN THOUGH IT WILL COMPILE
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Demo2a {

    //Effectively this would NOT handle the exception
    //This would pass it to the JVM which shows the stack trace
    public static void main(String[]args)throws FileNotFoundException{
        String fileName = "file.txt";
        File f = new File(fileName);//can combine
        Scanner in = new Scanner(f);//into one line
    }
}






Reading the file line by line:

while(in.hasNext()){
        String line = in.nextLine();
        //do something with line
        System.out.println(line);
}

Reading the file word by word:

while(in.hasNext()){
        String word = in.next();
        //do something with word
        System.out.println(word);
}

The java Scanner is super useful! It is an easy way to parse through files.



Homework:  

Do not worry about the constructor for you wordSearch yet. 
Focus on the various add methods, test them, verify them.

Think about:
-How are Horizontal/Vertical/Diagonal the same/different?
-How can you combine these methods into a much more flexible method?

Write the addWordDiagonal method.

   /**Attempts to add a given word to the specified position of the WordGrid.
     *The word is added from top left to bottom right, must fit on the WordGrid,
     *and must have a corresponding letter to match any letters that it overlaps.
     *
     *@param word is any text to be added to the word grid.
     *@param row is the vertical locaiton of where you want the word to start.
     *@param col is the horizontal location of where you want the word to start.
     *@return true when the word is added successfully. When the word doesn't fit,
     *or there are overlapping letters that do not match, then false is returned.
     */
    public boolean addWordDiagonal(String word,int row, int col){
    }

Comments