Courses‎ > ‎AP Computer Science‎ > ‎

Konstantinovich

Email: 
    konstans@stuy.edu

Office Hours:
    Periods 6,7,8  in room 301
    Note: 6th is my lunch and I tend to be out getting food the 1st 10 minutes of the period


2018-11-13 WordSearch final update.

posted Nov 13, 2018, 6:09 AM by Konstantinovich Samuel   [ updated Nov 15, 2018, 11:36 AM ]

Quiz This Thurs/Fri  on random, random seed, arrayList, arrays.

Do Now:
1. PAIR UP (triples ok if the row is oddly filled)
2. Discuss with your neighbors and then BOTH of you: WRITE an outline of this program on paper.
3. Write your name and your partner's name on each copy.

Note: each numerical value is nextInt()%100

$java Rerandom
This is your seed: 33211
-94 86 -97 -96 48 99 -6 56 25 -97
$java Rerandom
This is your seed: 23479
-6 66 27 -39 51 -80 27 95 -19 55
$java Rerandom
This is your seed: 82264
57 -53 -64 -75 10 88 69 0 -16 -56 
$java Rerandom 33211
This is your seed: 33211
-94 86 -97 -96 48 99 -6 56 25 -97
$java Rerandom 82264
This is your seed: 82264
57 -53 -64 -75 10 88 69 0 -16 -56






Final revision, to your WordSearch Repo.
This is due Monday 11/19/2018 8am.
This is ample time to complete the assignment. HOWEVER other small assignments may also be given before then.
You will get 2 lab days this week.  (and maybe a partial day)


Overview of new main behavior:

java WordSearch [rows cols filename [randomSeed [answers]]]  
//square brackets mean optional


Edit: removed "java WordSearch" and redefined valid.
This means that each of these will produce a puzzle or key:
java WordSearch rows cols filename
java WordSearch rows cols filename randomSeed  
java WordSearch rows cols filename randomSeed answers  

0. You must handle all exceptions.

1. You must print directions to the user that explain how to use the program when:
  • 0, 1, or 2 command line arguments are specified (this is not enough to run the program)
  • the file is not found
  • any numerical arguments are improperly formatted or out of range*
*Valid ranges:
seed is from 0 to 10000 inclusive
row/col must be > 0


Printing the directions is the end of the program, it should not do anything else!

2. rows and cols are the dimensions of the puzzle, filename is the name of the plain text file that contains words.
   If they are the only parameters passed, you should choose a random seed from 0 to 10000 inclusive.
   The puzzle is constructed with words from the textfile specified, and after thee words are added, you fill the 
   remaining spaces with random letters.
   The puzzle is then printed (including the seed).

3. When you give 3 arguments, you may optionally also give randomSeed to choose which seed your program uses. 
   The purpose of this is to force the same puzzle to occur again, so you can reprint the puzzle and/or the answers later.
   The puzzle is then printed (including the seed).

4. When you give 4 arguments, you may optionally give a parameter to display answers. 
The answer is just the puzzle but without the random letters filled in! 
You trigger answer mode by passing the value "key" into the answers parameter. 
Omitting the answers parameter, or passing any other values will just display the normal puzzle, and not show the answer.
   The puzzle answer is then printed (including the seed).


Sample output of word search
java WordSearch 4 4 words.txt  
OR
java WordSearch 4 4 words.txt 103
|X Y F B|
|I A I F|
|D E S A|
|M E H R|
Words: FAD, FISH, MEH (seed: 103)

Sample output of a solution: (solutions use spaces instead of underscores because it looks better)
java WordSearch 4 4 words.txt 103 key
|    F  |
|  A I  |
|D   S  |
|M E H  |
Words: FAD, FISH, MEH (seed: 103)


java WordSearch 20 30
 names.txt 1248
//would print the 20x30 puzzle seeded by 1248
java WordSearch 20 30 names.txt  1248 fish
//would print the 20x30 puzzle seeded by 1248
java WordSearch 20 30 names.txt  1248 key 
//would print the 20x30 answer key for the puzzle seeded by 1248    (all 3 of these will match)

java WordSearch 10 20 fish.txt 8230 oops
java WordSearch 10 20 fish.txt 8230     
//would print the 10x20  puzzle seeded by 8230  (both of these will match, neither are answer keys)


All of the following would print the directions (for various reasons)
java WordSearch 20 30
usage: java WordSearch [rows cols filename [randomSeed [answers]]]

java WordSearch 20 30 names.txt 51248
usage: java WordSearch [rows cols filename [randomSeed [answers]]]

java WordSearch 20 -30 names.txt 5248
usage: java WordSearch [rows cols filename [randomSeed [answers]]]

java WordSearch FISH 30 names.txt 5148
usage: java WordSearch [rows cols filename [randomSeed [answers]]]


Changing the seed, dimensions of the puzzle, or quantity of words, even by a single number/word, will cause a completely different puzzle to occur. 



Write your main in your WordSearch. I will test your program with the 3 correct ways of using it above AS WELL AS various invalid ways.
java WordSearch r c mydatafile.txt 
java WordSearch r c mydatafile.txt s
java WordSearch r c mydatafile.txt s key

Then use your main to construct the object and output the appropriate puzzle!


Things to note:
- I am not checking your WordSearch methods! I don't care what you called them.
- I am checking the main of your WordSearch by changing the command line arguments!


import java.util.*;
public class Rerandom{
    public static void main(String[]args){
        //change this to any seed you want.
        int seed = (int)(Math.random()*100000);


	//Manually assign a seed if you wish
        //seed = 17127;
        //or use the args
        if(args.length > 0){
          seed = Integer.parseInt(args[0]);
        }


        System.out.println("This is your seed: "+seed);
	Random randgen = new Random(seed);
        
        //Use the random to generate 10 numbers
for(int i=0;i<10;i++){ System.out.print(randgen.nextInt()%100+" "); } System.out.println(); } }

2018-11-09 Random

posted Nov 9, 2018, 6:23 AM by Konstantinovich Samuel   [ updated Nov 13, 2018, 6:27 PM ]


Now let us look at Random:

import java.util.Random;
public class DemoRandom{
  public static void main(String[]args){

    //here no seed is provided, so it uses the clock as a seed
    //this can be used to produce a random seed for a different Random object!
    Random rng = new Random();
    for(int i =  0; i < 5; i++ ){
      System.out.println(rng.nextInt() % 1000);
    }
    System.out.println();

    //specified seed can be used to reproduce sequences
    rng = new Random(100);//seed of 100 is stored.
    for(int i =  0; i < 5; i++ ){
      System.out.println(rng.nextInt() % 1000);
    }
  }
}




WordSearch updates

1. Make a plain text file "words.txt" and fill it with whatever words you like. 
   -Put in words with different lengths to help you test
Your text file should be formatted like this:
ham
beef
sushi
turkey
venison
meatloaf




Update to your WordSearch with new instance variables + Methods
(Due Wednesday, DO NOT wait until Tuesday)


import java.util.*; //random, scanner, arraylist
import java.io.*; //file, filenotfoundexception
public class WordSearch{
    private char[][]data;

    //the random seed used to produce this WordSearch
    private int seed;

    //a random Object to unify your random calls
    private Random randgen;

    //all words from a text file get added to wordsToAdd, indicating that they have not yet been added
    private ArrayList<String>wordsToAdd;
    
    //all words that were successfully added get moved into wordsAdded.
    private ArrayList<String>wordsAdded;

}


Update your wordSearch with the methods discussed in class:

Two Constructors:
    Both will read in the word text file, then run addAllWords(). Do not fill in random letters after.

public WordSearch( int rows, int cols, String fileName) 
    Choose a randSeed using the clock random

public WordSearch( int rows, int cols, String fileName, int randSeed)
    Use the random seed specified.


Three Methods

1. public String toString()

toString should print in the following format: 
  • Use '|' as left/right boundaries of the grid. 
  • One long line of comma separated words after the string "Words: "
  • When you got all other things working, add the seed 

|_ _ F _|
|_ A I _|
|D _ S _|
|M E H _|
Words: FAD, FISH, MEH (seed: 103)

When printing the final puzzle, you will add random letters to fill in the _'s

AddWord (Edit: corrected the order of parameters, since it is private, the wrong order will not affect your code)
2. private boolean addWord( String word, int r, int c, int rowIncrement, int colIncrement)


  

   /**Attempts to add a given word to the specified position of the WordGrid.
     *The word is added in the direction rowIncrement,colIncrement 
     *Words 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.
     *@param rowIncrement is -1,0, or 1 and represents the displacement of each letter in the row direction
     *@param colIncrement is -1,0, or 1 and represents the displacement of each letter in the col direction
     *@return true when: the word is added successfully.
* false when: the word doesn't fit, OR rowchange and colchange are both 0,
*        OR there are overlapping letters that do not match */ private boolean addWord(String word,int row, int col, int rowIncrement, int colIncrement){ }

    /*[rowIncrement,colIncrement] examples:
     *[-1,1] would add up and the right because (row -1 each time, col + 1 each time)
     *[ 1,0] would add downwards because (row+1), with no col change
     *[ 0,-1] would add towards the left because (col - 1), with no row change
*/


3. private void addAllWords() 
EDIT: There is no returned value! This is not useful since it will add 0 or more words no matter what.
Attempt to add all of the words from the wordsToAdd list using the following algorithm:
  1. Choose a random word, and a random direction (rowIncrement/colIncrement)
  2. Try to add that word to different starting positions* until: 
    • you successfully add the word
    • you run out of positional tries 
  3. Repeat this process until you added all of the words, or you tried to add unsuccessfully too many times in a row. 
  4. OPTIONAL    Optimize your addAllWords such that: 
    • You do not try to add words to positions that would not fit the word on the board. **
    • Use the rowIncrement/colIncrement to decide what the range of valid row/col should be.

    *Each try in step 2 only changes the position of the start, not the direction or word
    **A five letter word that is meant to be added across to the right should not START in the last 4 columns of the board    

Make sure your toString verifies your words are adding properly. Feel free to print the object inside of its own methods as a debug!




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){
    }

2018-11-07

posted Nov 7, 2018, 6:07 AM by Konstantinovich Samuel   [ updated Nov 7, 2018, 8:01 AM ]

Goal: Quiz2, Wordsearch getting started.


HW:
Here is a base set of methods to get you started! Complete them!

Make a git repo:
MKS21X-WordSearch


public class WordSearch{
    private char[][]data;

    /**Initialize the grid to the size specified 
     *and fill all of the positions with '_'
     *@param row is the starting height of the WordSearch
     *@param col is the starting width of the WordSearch
     */
    public WordSearch(int rows,int cols){
    }

    /**Set all values in the WordSearch to underscores'_'*/
    private void clear(){
    }

    /**Each row is a new line, there is a space between each letter
     *@return a String with each character separated by spaces, and rows
     *separated by newlines.
     */
    public String toString(){
    }


    /**Attempts to add a given word to the specified position of the WordGrid.
     *The word is added from left to 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 
     * and the board is NOT modified.
     */
    public boolean addWordHorizontal(String word,int row, int col){
    }

   /**Attempts to add a given word to the specified position of the WordGrid.
     *The word is added from top to bottom, 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.
     *and the board is NOT modified.
     */
    public boolean addWordVertical(String word,int row, int col){
    }
}

using javadoc produces documentation like this:
  • Constructor Detail

    • WordSearch

      public WordSearch​(int rows,
                        int cols)
      Initialize the grid to the size specified and fill all of the positions with '_'
      Parameters:
      row - is the starting height of the WordSearch
      col - is the starting width of the WordSearch
  • Method Detail

    • toString

      public java.lang.String toString()
      Each row is a new line, letters are separated by a space
      Overrides:
      toString in class java.lang.Object
      Returns:
      a String with each character separated by spaces, and rows separated by newlines.


2018-11-05

posted Nov 4, 2018, 6:50 PM by Konstantinovich Samuel   [ updated Nov 7, 2018, 5:57 AM ]

LAB07 results at bottom of post.


Goal: Word search design! 

Puzzles like this are common:

U A I F L Q B I D R T V D S S 
D R H N N N K W R N E A P H F 
U J Y M B O A X U S L O G J N 
N U X D L Z E P C A P X V V I 
B O D S J O T X S C L I X R D 
C A C L Y Y S I O T A N U E B 
K H X N M P P R E S L U E T C 
E K O I K I N T F S T T B S S 
S G D C V C D I U B X Z H B I 
H O N F O Z Y P F K S W J O W 
Z E O W V L E A R H R E R L R 
Q W X A T R A O Z M S J E U N 
Z C N Y M V N T O Z U I F L L 
N T W A Y A S Q E L I D F Q X 
X H N T K S O H J W O P J Z X
	 
FIND THE FOLLOWING WORDS:
FISH        LOBSTER    PIZZA       CHOCOLATE
STEAK       SALAD      POPCORN     THOR
LOKI        ZOD        SUPERMAN



You are writing a word search generator. 

The class should be able to:
1. generate an N by M puzzle 
    (A puzzle includes a list of words, and a grid of letters with those words hidden.)
2. add a bunch of words randomly
3. show the puzzle , or the solution. (have a puzzle have a unique ID so you can recall it later)
4. Use a plain text file as a list of words to add to the puzzle. 
           This means we can swap the theme of the puzzle with different files.
5. Be able to reproduce the same puzzle/solution at a later date. This is a VERY useful feature.


IN CLASS:
 Brainstorm with your neighbors on the following points:
 - How to design a data structure to hold the puzzle, words, solution, etc.
 - How the overall program would place the words and how you could view a solution.
 - How would the user interact with the words search program?
     e.g.     java WordSearch ???? ??? ???
 - What tools in java do you need but not have yet?

2018-11-02

posted Nov 2, 2018, 6:12 AM by Konstantinovich Samuel   [ updated Nov 5, 2018, 6:38 PM ]

Today: Lab Day

Quiz Wed.
Theory + Coding.
Including up to ArrayLists.

Lab Due Monday:
Ordered Super Array

HW Due Wed: (I don't want to make 2things due the same day, so I will give extra time for this:

There are 6 methods, but they have a lot of overlap.
Repo: MKS21X-2darraymethods


Part 1-2
I will not try to go out of bounds explicitly by my making the index too large or too small. 
Part 3:
I will test that non-rectangular arrays (ragged arrays) work properly.

public class ArrayMethods{

   /*
   *PART 1
   */
   public static int rowSum(int[][] ary, int x){}
    //returns the sum of the elements in Row x of ary
    //When x is past the last row count it as a zero. (NO indexOutOfBounds should ever occur)

   public static int columnSum(int[][] ary, int x){}
    //returns the sum of the elements in Column x of ary (careful with rows of different lengths!).
    //When a row is not long enough to reach the column count it as a zero. (NO indexOutOfBounds should ever occur)
    
   /*
   *PART 2 - use prior methods where appropriate
   */
   public static int[] allRowSums(int[][] ary){}
    //returns an array of the row sums for each row of ary. 
    //Index i of the return array contains the sum of elements in row i.

    public static int[] allColSums(int[][] ary){}
    //Returns an array with the column sum of each column of ary.
    //When a row is not long enough to reach the column count it as a zero. (NO indexOutOfBounds should ever occur)
    //Index i of the return array contains the sum of elements in column i, ignoring any rows that are too short.
    //The length of the returned array should be the length of the LONGEST array in ary.

  
   /*
   *PART 3 - use prior methods where appropriate
   */
   public static boolean isRowMagic(int[][] ary){}
     //checks if the array is row-magic (this means that every row has the same row sum).

   public static boolean isColumnMagic(int[][] ary){}
    //checks if the array is column-magic (this means that every column has the same column sum).

}


2018-11-01 Extending the ArrayList

posted Nov 1, 2018, 6:03 AM by Konstantinovich Samuel   [ updated Nov 2, 2018, 7:58 AM ]

Goal : Generics + Extend the Array List


Generics:

Using the format
public class ClassName<VARIABLE_TYPE>{

}

Restriction: It must be an OBJECT type, no primitives!
You may now use that VARIABLE_TYPE as a type throughout your code.


public class ThingThatHolds<T>{
public T value;
}



WITHOUT METHODS (for demo only)

public
class Holder<T>{ public T value; public static void main(String[]args){ Holder<String> name = new Holder<String>(); name.value = "Whoa!"; Holder<Integer> data = new Holder<Integer>(); data.value = 5; System.out.println(name.value+" "+data.value); } }


WITH METHODS:

public class Holder<T>{ private T value;

 public Holder(){ //NOTICE NO <> here!!! }
 public Holder(T start){ //NOTICE NO <> here!!! value = start; } public T getValue(){ return value; } public void setValue(T newVal){ value = newVal; } public static void main(String[]args){ Holder<String> name = new Holder<String>(); name.setValue("Whoa!"); Holder<Integer> data = new Holder<Integer>(); data.setValue(5); System.out.println(name.getValue()+" "+data.getValue()); } }





Consider the Class Hierarchy Below

ArrayList (built in class - your super array)
\
NoNullArrayList (not built in)
\
             OrderedArrayList (not built in)

Lab (Due Monday) Implement the NoNullArrayList and OrderedArrayList.
COMPLETE NoNullArrayList before moving on to OrderedArrayList

Github repo: MKS21X-OrderedArrayList

Note: 
-There are many methods in the arraylist that can break the NoNullArrayList and OrderedArrayList.
-If you do not use addAll, or the constructor(Collection<>) then you should be fine. 
-DO NOT use any built in sort methods!


NoNullArrayList<T> extends ArrayList<T>
    is an ArrayList of T that cannot take a null as a value.

    Override set and both add methods -> throw an IllegalArgumentException when null is added,
                                 otherwise call the old add method.


    Only have 2 constructors: default + startingCapacity.
    

OrderedArrayList<T extends Comparable<T>> extends NoNullArrayList<T>
    This is a NoNullArrayList that maintains all elements in a sorted order upon insertion.

    Override both add methods -> find the correct index where the new element should be added, 
                                 then add() the new element into that position
                                 (hint: 1.compareTo 2.helper method)

    Override set(index,value) -> remove() the element at index, then add() the new value.

    Only have 2 constructors: default + startingCapacity.



There are three main tricky parts to this assignment:
1) finding the correct index to add to in OrderedArrayList is the obvious one.
2) using the super methods at the correct time (e.g. in ordered array list, once you know where to put it, use the super.add method)
3) How to make it compile properly... because we want our list to accept a generic type.

2018-10-31 HW

posted Oct 30, 2018, 9:24 PM by Konstantinovich Samuel

Happy Halloween!

More coding bat problems have been added to the 

Work in class + finish at home.

2018-10-30

posted Oct 30, 2018, 6:26 AM by Konstantinovich Samuel   [ updated Oct 30, 2018, 8:32 AM ]


ArrayList:
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

AP Subset:
https://www2.cs.duke.edu/csed/ap/subset/doc/ap/java/util/ArrayList.html


import java.util.ArrayList; import java.util.List; public class ArrayListDemo{ public static void main(String[]args){ List<String> names; //can store any kind of list, but you only //know about ArrayList for now. names = new ArrayList<String>(); names.add("Bart"); names.add(0,"Homer"); names.add("Polyphemus"); names.add("Lisa"); names.add("Charybdis"); names.remove(1); names.remove(2); System.out.println(names); for(int i = 0; i < names.size();i++){ //you cannot use var[i] notation! names.set(i,names.get(i)+"!"); } ArrayList<Integer>nums = new ArrayList<Integer>(); nums.add(new Integer(4));//old way, not used nums.add(3);//automatically convert into an Integer from int nums.add(2);//this is called autoboxing nums.add(Integer.valueOf(1));//proper way System.out.println(nums); nums.remove(1); System.out.println(nums+" after remove(1)"); nums.remove(new Integer(1));//should use valueOf(1) System.out.println(nums+" after remove(new Integer(1))"); } }

Classwork/Homework:
https://codingbat.com/home/konstans@stuy.edu/apcs1

Complete the new section with arrayLists

Quiz Next Wed.

PClassic Competition Sign Up:
http://bert.stuy.edu/pbrooks/pclassic/pclassic-fall-2018.html


Remember you can use this to visualize your code... but they dont usually work with ArrayLists.
https://cscircles.cemc.uwaterloo.ca/java_visualize/


2018-10-29

posted Oct 29, 2018, 6:23 AM by Konstantinovich Samuel   [ updated Oct 30, 2018, 5:53 AM ]

Goal: Working with Exceptions 

Do now: On Paper
1. Rewrite this class by adding
IllegalArgumentException whenever a negative age is set.
2. Compare with your neighbors, identify where/how redundant code may be eliminated (if any)


class
Person{ int age; public Person(int age){ this.age = age; } public void setAge(int age){ this.age = age; } }

SOLUTION:

class Person{
int age;
Person(int age){
setAge(age);
}

public void setAge(int age){
if (age<0){
throw new IllegalArgumentException("invalid age: "+age);
}
this.age = age;
}
}





DEMO EXCEPTIONS:


class Person{ int age; public Person(int age){ setAge(age); } public void setAge(int age){ if ( age < 0){ throw new IllegalArgumentException("Age cannot be "+age); } this.age = age; } public static void main(String[]args){

    try
{ Person a = new Person(-9); int[]b = new int[1]; b[1]=3; System.out.println("A Everything is gonna be alright!"); }catch(IllegalArgumentException err){ err.printStackTrace(); System.out.println("B Handle argument"); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("C Handle array"); } System.out.println("D Did not crash!"); } }


HOMEWORK - complete your super array

Add one more constructor to your super array if you don't have it:
    public SuperArray(int initialCapacity) -> Throws:  IllegalArgumentException - if the specified initial capacity is negative


ArrayList:
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

AP Subset:
https://www2.cs.duke.edu/csed/ap/subset/doc/ap/java/util/ArrayList.html


Consider the Class Hierarchy Below

ArrayList (built in class - your super array)
\
NoNullArrayList (not built in)
\
             OrderedArrayList (not built in)

1-10 of 39