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

notes

2017-09-26

posted by Samuel Konstantinovich

Goal: References vs Primitives

Go Over Array Problems

A reference in java is similar to using the address in memory of the thing you are referring to. 


2017-09-25

posted Sep 25, 2017, 9:51 AM by Samuel Konstantinovich   [ updated Sep 25, 2017, 10:08 AM ]

Exam Friday. All of Java so far. Not including objects. (We start them soon)

-Go over all problems there was difficulty solving.

 public static void main (String[]args){
	char[] fakeString = {m,c,g,k,s};
	for (int i = 0; i < fakeString.length; i++){
		System.out.println(fakeString[i] +  );
	} 
	
	// Three different ways to initialize an int[][]. 
	//Applies to 2D arrays of another type too. 

	int[][] multiA = new int[3][4]; 
	// first number is the # of arrays in multiA
	// second number is the # of items of each array in multiA
	// for multiA, all arrays must be the same length. 


	// for multiB, the arrays within can have different lengths. 
	int[][] multiB = new int[3][];
	multiB[0] = new int[4]; // each row, 0,1 and 2
	mutliB[1] = new int[4]; // can be a different length 
	multiB[2] = new int[4];

	
	int[][] multiC = new int[][]{
		{0,0,0,0}, // can make these different lengths as well
		{0,0,0,0},
		{0,0,0,0},
		};
	// for multiC, arrays within can have different lengths. 
}


Lets try these 2 problems:

Write test cases. 
Compare with your neighbors.

1. Calculate and return how many zeros are in the parameter
(a rectangular 2D array of integers)

public static int countZeros2D(int[][] nums){

}

Hint for problem 2: 
First make a function to print a 1D array.
Then make a function to print a 2d array.
THEN you can attempt these problems.

2. Fill the given 2-dimensional array of integers with 1's.
Where the row number is the same as the column number:
   you must fill those with 3's instead.

public static void fill2D(int[][] vals){
  
}

3. Make a new 2d array the same dimensions as the given parameter.
Fill that array with with 1's, 
except where the row number is the same as the column number:
   you must fill those with 3's instead.

You may NOT modify vals.

public static int[][] fill2DCopy(int[][] vals){
  
}



2017-09-20 HW

posted Sep 20, 2017, 10:02 AM by Samuel Konstantinovich

I will not reinvent the wheel, here is the java documentation for arrays:

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Class Work with arrays / HW:

Arrays-1 (no loops, very silly warmup)
fix23 
start1 
biggerTwo

Arrays-2
centeredAverage 
sum13 
sum67
withoutTen 
zeroMax 
evenOdd 
fizzBuzz

2017-09-19 HW

posted Sep 19, 2017, 9:37 AM by Samuel Konstantinovich   [ updated Sep 19, 2017, 9:37 AM ]

Regarding Strings, you really need the following:
1 charAt(int)
2 length()
3 equals(String)
4 compareTo(String)
5 indexOf(String)
6 substring(int,int)
7 substring(int)
When you read the java documentation, pay attention to when they throw exceptions (runtime errors), and when they return special values. 


Here is the AP subset of Java you need to know:
Strings are here:


Goal: For Loops!

int x = 0; //initialize

while (x<10){     //check

//body

x++;       //increment

}


equivalent to this is:

for(int x = 0; x<10; x++){

//body

}


Basic syntax for a "for" loop:

for(variable; check; increment){

//body

}


However, when you declare a variable inside of a "for" loop, it will not be defined outside of the function.

 - If you define the variable, x, outside of the "for" loop, you will be able to use it both in the "for" loop and outside of it.


In a "while" loop, there is much flexibility inside of the body, where the parts such as the increment and body can be scrambled.

On the other hand, in "for" loops, the format is much stricter.



Classwork / HW
String-2
prefixAgain 
xyzMiddle 
getSandwich 
sameStarChar 
oneTwo 
zipZap

String-3:
CountTriple
SumDigits

2017-09-18 HW

posted Sep 18, 2017, 6:24 AM by Samuel Konstantinovich

Goal: While Loops


in python:

x = 0
while boolean:
  body

x=0

while x < 10

   #??? some code here

   x = x + 1


in netlogo:

while [boolean]
  [ body ]
let x 0
while [ x < 10]
[  
   ;???some code here
   set x (x + 1)
]

in java:

while(boolean){
   body
}

int x = 0;

while (x < 10){

   //??? Some code here

   x = x + 1;

}


GENERIC CODE:

// evaluate the boolean when it is true, go to INSIDE_LOOP

// when it is false go to AFTER_LOOP     

while (boolean){   

   //INSIDE_LOOP

//whatever code inside

//go back to boolean, redo the check.

}

//AFTER_LOOP


return one character in a string:

String s = "whatever"

            01234567


Go Over:

substring

chartAt


int i = 0;

while (i < s.length()){  // "<=" would cause an exception. "length()" is a method

System.out.println(s.substring(i, i +1));

i = i + 1; //  OR i += 1; OR i++; (only adds one)

}


Lab + Homework:

codingbat -> warmup2 ->

stringTimes

frontTimes

countXX

doubleX

stringBits

stringSplosion


String-2

doubleChar

countHi



2017-09-15 HW

posted Sep 15, 2017, 9:59 AM by Samuel Konstantinovich   [ updated Sep 15, 2017, 10:06 AM ]

Java Strings

Java Documentation:
http://docs.oracle.com/javase/8/docs/api/

Strings are not primitives, they are Objects. 

Operations that work on strings:
+    concatenation 

You cannot use == ,  >, <= etc for comparison.

They contain methods! (You saw python string methods!

Strings:
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

AP Critical Methods:
substring  : like a python slice
equals  :  determining identical contents
compareTo : for less than/ greater than / equal  comparison
length

Escape Sequences:
Special characters sometimes need to go in strings, but cannot be typed. 
We can put them in strings using the backslash to escape the character from being treated like a regular symbol. 
This works in both char and String types.

\n is the newline character, so you can write literals like:  '\n'  ,  "'\n" ,  or "fish\nfood"
\t  tab
\'  single quote
\"  double quote
\\ backslash

System.out.println("\\why\no//\"!\'?")  would print:

\why
o//"!'?

Each escaped character counts as 1 unit for the length of the string and charAt and substring treat them as single characters (only we see 2, the views these symbols as 1 thing each)


Class Critical Methods:
charAt   


Literal Strings
String variables


Homework:
http://codingbat.com/java/String-1
makeTags 
makeOutWord 
extraEnd 
firstTwo
withoutX

2017-09-14 HW

posted Sep 14, 2017, 10:14 AM by Samuel Konstantinovich

Do Now: 
Share your coding bat work with me by completing your profile.
Your name should Be:   xx,Last,First   where xx is 06,09, or 10 depending on your period. No spaces!
After you set your profile name, share your work with konstans@stuy.edu.

Then complete Logic-1   ->  in1To10

Did you use an if statement? If you did, try again without an if statement. Just return the boolean.
DO NOT do this:
if( boolean ){
 return true;
}
else{
 return false;
}


INSTEAD you SHOULD do this:
return boolean;

Lets make some bricks:


Homework:

CodingBat:

http://codingbat.com/java/Logic-2
    -loneSum
    -LuckySum
    -noTeenSum
    -roundSum


Non-CodingBat self assessment: (if you can do this,  you are on track! )
-Create a java program with a class name of HomeworkTest
-Create two functions, celsiusToFahrenheit and fahrenheitToCelsius
-What should the functions have as parameter(s) ? What type should they be?
-What should the functions return?
-Compile and run as you write this, using a main function to run and test your two functions.



2017-09-13

posted Sep 13, 2017, 10:14 AM by Samuel Konstantinovich   [ updated Sep 13, 2017, 1:42 PM ]


Windows users can run ubuntu as a virtual machine:
 https://www.lifewire.com/install-ubuntu-linux-windows-10-steps-2202108

If you want to do this then mMake sure you use Ubuntu 16.04.3 LTS

After you install the ubuntu virtual machine:

1. Install emacs:
sudo add-apt-repository ppa:kelleyk/emacs
sudo apt-get update
sudo apt-get install emacs25
2. Install git:  (we will use this later it isn't just for the next step)
sudo apt-get install git
3. Install java: 
sudo apt-get install openjdk-8-jdk
4. Add a nice config for emacs like this:
git clone https://github.com/bodil/ohai-emacs.git ~/.emacs.d

You can read about the config here: https://github.com/bodil/ohai-emacs   


Goal: More converting your prior CS into Java specific CS.

Do Now: Predict the result of each print statement

note that:
- "ab" + "cd"  results in "abcd"
- 1 + "fish"   results in "1fish"
- Strings only work with +, not other operators.
       System.out.println(1 + 2 + 3 / 3);
       System.out.println(2.0 + 1 / 2);
       System.out.println(2 + 1.0 / 2);
       System.out.println("hey" + "you");
       System.out.println("2+3" + "4");
       System.out.println("5"+ 6 + 7);
       System.out.println(1 + 2 + "3");
       System.out.println(23 % 4);

    Functions!
    public static RETURN_TYPE FUNCTION_NAME(TYPE PARAMNAME...){
        
    }

    public static int foo(int x){
        return 2 * x + 1;
    }
    public static double bar(int x, int y){
        return x * x + y + 1.0;
    }

    //void means there is no return type!
    public static void bah(int x, int y){
        System.out.println("Shhh!");
    }

    Evaluate:
    foo(2)
    foo( foo(2) )
    int u = 2;
    foo( u + foo(3) )

Boolean expressions are created using: and, or, not. Java does not have those keywords however instead use the following. 
and:    &&
or:     ||
not:     !   
example:   a && !b || !(a && b)

and, or, and not only work on boolean values or expressions. They do not work on numbers.

To turn other values into booleans we use comparisons:
>    <=
<    >=
==   !=
  
Conditional Statements:

if ( <boolean1> ) {
  // run here if boolean1 is true
}



if ( <boolean2> ) {
  //A only run this section when <boolean2> is true
}
else{
  //B only run this section when <boolean2> is false
}
//At this point either A or B have executed, but never both (always exactly one)


HW03:
1. Create an account on http://codingbat.com/ please do NOT use the Mozilla Persona thing. 
2. Do any 2 warmup-1 problems to see how the site works.
3. Be careful, when you want to work on problems you should LOG IN first, or the progress will not be saved. 
This site is another great resource and has many problems to practice on! I will also assign many problems from here.

4. Look at the Logic-1  section, and complete these 4 problems:
 > sortaSum 
 > dateFashion 
 > caughtSpeedin
 > squirrelPlay 


2017-09-12

posted Sep 12, 2017, 10:15 AM by Samuel Konstantinovich

Emacs25 

Windows:
  https://www.emacswiki.org/emacs/MsWindowsInstallation
Mac:
  https://emacsformacosx.com/builds
Linux:
  You can do it!


Recap on Languages:
  • Compiled Language
    • Human readable source code is translated (compiled) into machine language. (binary)
    • Machine language contains instructions that are run directly by the computer.
  • Source code and machine code are different files.
  • Java is a hybrid of compiled and interpreted language
  • Java programs compile into java byte code, that does not run directly on a computer, they go through the java virtual machine (JVM)
    • The JVM is like an interpreter. It translates from byte code to machine instructions.
  • Source files have a .java extension and are human readable. They _must_ end in .java 
  • Source files are compiled into java byte code by the compiler (javac) and are stored in files which have .class extension.
  • .class files are readable by the JVM
  • All .class files are cross-platform (can be run on any OS that has a JVM)
  • Each platform has a specific JVM. Mac, Windows, Linux, etc.
Java Types:

-Java is statically-typed (variables must be declared before they can be used)

The primitive data types: (you need the ones underlined)
byte/short/int/long
float/double
boolean
char

int (32 bit, values from -2^31 to +2^31-1)
double(64 bit)
boolean (size not defined)
char (16 bits , 0 to 65,535)

Other Data Types:
A String is not a primitive type. Strings are special because they are objects, and we will learn about them more later.

Note: Semicolons are used to separate statements and are placed at the end of most statements. Exceptions will be discussed.

Variables : They store values, and you can change them by re-assigning after they are assigned. You cannot use a variable before it is assigned. 

declaration:
<type> <name>;
e.g.
int x;
float z;

assignment:
<name> = <expression>;
x = 3;
z = 2*3.14159+1;

declare + assign:
<type> <name> = <expression>;
char c = 'f';
String s = "whoa!";

Reassignment - can have the original variable in the expression:
x = x + 1; 
fish = fish + cat; //assumes fish and cat have values and are compatible with addition.

New Stuff:

declare + assign multiples:
int x,y;
double a = 3.0, b = 5.123;

Literal - a fixed value written in the source code. Not a variable or expression.
e.g.
54
"hello"
1.3
true
1.23e2 (doubles can be written in engineering notation!)

Identifier - the name given to a variable/function.
May not start with a digit, and may contain letters, digits, _ , and $ . (Don't use dollar signs, and don't use underscores except when discussed in class)
e.g.
a
b
x
fish
num$dollars (terrible name)
x123
GRAVITY_OF_MOON
hi_there


Terminal Stuff

Commands you should know and love:
cp     mv     mkdir    rmdir
ls       cd      pwd      rm
cat    man

Commands you should learn to love:
emacs    ssh    less    more  grep

Cool Commands that won't be required:
|   :  (pipe)  lets you run the output of one program into another program
wc  : word count     
sort  :  sorts things...




More detailed Linux/Unix tutorial:



2017-09-11 HW

posted Sep 11, 2017, 6:23 AM by Samuel Konstantinovich   [ updated Sep 11, 2017, 9:38 AM ]

Goal: Course overview + Your terminal fu is no good here...

Homework: Test your ability to compile and run (see end of lecture)

School network:

lisa.stuy.edu  149.89.160.100
homer.stuy.edu 149.89.150.100
bart.stuy.edu  149.89.151.100
marge.stuy.edu 149.89.161.100

307:   149.89.150.xxx  
cslab1-1 ... cslab1-30  where xxx is 101-130

325:   149.89.151.xxx  
cslab2-1 ... cslab2-30  where xxx is 101-130

251:   149.89.160.xxx  
cslab3-1 ... cslab3-31  where xxx is 101-131

451:   149.89.161.xxx  
cslab4-1 ... cslab4-32  where xxx is 101-132

Inside the building you can SSH to any host using its ip address.

The *nix command is: 
ssh user@host

Win: you have to use puTTY or another ssh program.



Resources:
Very Basic Linux Tutorial for n00bs and forgetful people:  https://www.digitalocean.com/community/articles/an-introduction-to-linux-basics

More detailed Linux/Unix tutorial:







Java code for reference:

EXAMPLE 1:

file: helloworld.java

public class helloworld{
    public static void main(String[]args){
        System.out.println("Hello world");
    }
}

EXAMPLE 2
file: Demo.java

public class Demo{

    public static void print( int x){
        System.out.println("This was a function!");
        System.out.println("The parameter is "+ x);        
    }

    public static void main(String[]args){    
        print(5);
        print(-2);

    }
}



HW Test the JDK by running this on a terminal:  
javac -version
1. Paste the following into HelloWorld.java :
public class HelloWorld{
    public static void main(String[]args){
        System.out.println("Hello, my name is Inigo Montoya, You killed my");
        System.out.println("father, prepare to die!");
    }
}

2. Open a terminal and cd into the same directory as your file, then run the commands:
javac HelloWorld.java
java HelloWorld



If in a terminal you cannot just type 
java
javac

Then you need to set your environment variables. Google the following:

javac environment variables <OS>           

*Replace <OS> with your operating system.

e.g.
javac environment variables windows 10
javac environment variables windows 7

1-10 of 11