[go: up one dir, main page]

0% found this document useful (0 votes)
19 views36 pages

Lec02 Ab

Uploaded by

breaduc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views36 pages

Lec02 Ab

Uploaded by

breaduc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

CSE 250

Data Structures
Dr. Eric Mikida
epmikida@buffalo.edu
208 Capen Hall

Lec02: Java Refresher


Announcements and Feedback
● Make sure you are on Piazza
● Academic Integrity Quiz due 9/8 @ 11:59PM (MUST GET 100%)
● PA0 due 9/8 @ 11:59PM (MUST GET 100%)
● WA1 - Coming Friday

2
Why Java?
● Strongly Typed Language: The compiler helps make sure you mean
what you say
● Compiled Language: Can run it anywhere, see the impacts of your data
structure choice and data layout
● You know it (hopefully): You learned the basics in 116

3
Hello World
1 package cse250.examples;
2
3 class MainExample {
4 /**
5 * Main function
6 * @param args The arguments to main
7 */
8 public static void main(String[] args) {
9 System.out.println("Hello World");
10 }
11 }
4
Hello World
1 package cse250.examples;
2
3 class MainExample {
4 ...
5 }

● All code in Java lives in a class


○ In general each class will be in it's own .java file
● Classes are organized into packages
○ Think directories…

5
Hello World
1 /**
2 * Main function
3 * @param args The arguments to main
4 */

● Single line comments in Java start with //


● Multi line comments in Java start with /* and end with */
● Javadoc comments start with /**

6
Hello World
1 public static void main(String[] args)

● public - the function can be called by anyone (instead of private)


● static - the function isn't tied to a specific object
○ To call this function we would write MainExample.main(...)
● void - the functions return type (in this case it doesn't return anything)
● main - the function name
● String[] args - the parameter list
○ In this case, a single parameter with the type array of String

7
Hello World
1 System.out.println("Hello World");

● System refers to java.lang.System


● System.out is the out field of System
● System.out.println is a function that prints a line of text
● Semicolons (;) are mandatory

8
Exceptions
1 public List<String> loadData(String filename) {
2 List<String> ret = new ArrayList<String>();
3 BufferedReader input =
4 new BufferedReader(new FileReader(filename));
5 String line;
6 while( (line = input.readLine()) != null ) {
7 ret.add(line);
8 }
9 return ret;
10 }

9
Exceptions
1 public List<String> loadData(String filename) {
2 List<String> ret = new ArrayList<String>();
3 BufferedReader input =
4 new BufferedReader(new FileReader(filename));
5 String line;
6 while( (line = input.readLine()) != null ) {
7 ret.add(line);
8 }
9 return ret;
10 }

java: unreported exception java.io.IOException; must be caught or declared to be thrown


10
What are Exceptions

They are a way to catch an error when something goes horribly wrong!

So what do you do?

11
Catching Exceptions
1 public List<String> loadData(String filename) {
2 try {
3 BufferedReader input =
4 new BufferedReader(new FileReader(filename));
5 String line;
6 while ((line = input.readLine()) != null) {
7 ret.add(line);
8 }
9 return ret;
10 } catch(IOException e) {
11 // Handle the exception, ie print out what went wrong
12 e.printStackTrace();
13 }
14 }
Catching Exceptions
1 public List<String> loadData(String filename) {
2 try {
Try something that isn't
3 BufferedReader input =
guaranteed to work….
4 new BufferedReader(new FileReader(filename));
5 String line;
6 while ((line = input.readLine()) != null) {
7 ret.add(line);
8 }
9 return ret;
10 } catch(IOException e) {
11 // Handle the exception, ie print out what went wrong
12 e.printStackTrace();
13 }
14 }
Catching Exceptions
1 public List<String> loadData(String filename) {
2 try {
3 BufferedReader input =
4 new BufferedReader(new FileReader(filename));
5 String line;
6 while ((line = input.readLine()) != null) {
7 ret.add(line); …and "catch" the exception in
8 } case something goes wrong
9 return ret;
10 } catch(IOException e) {
11 // Handle the exception, ie print out what went wrong
12 e.printStackTrace();
13 }
14 }
Passing Along Exceptions
1 public List<String> loadData(String filename)
2 throws IOException // Communicate the explosive potential
3 {
4 BufferedReader input =
5 new BufferedReader(new FileReader(filename));
6 String line;
7 while ((line = input.readLine()) != null) {
8 ret.add(line);
9 }
10 return ret;
11 }
15
Passing Along Exceptions
1 public List<String> loadData(String filename)
2 throws IOException // Communicate the explosive potential
3 {
4 BufferedReader input =
5 new BufferedReader(new FileReader(filename));
6 String line;
7 while ((line = input.readLine()) != null) { If your function does not
8 ret.add(line); handle the exception itself,
9 } then you need to let the outside
world know something might
10 return ret; go wrong
11 }
16
Coding Style is IMPORTANT!!
1 class neatClass
2 {
3 public static void
4 doSomething(String wowwww)
What the heck is going on here!?
5 {
6 String weee = "Yes";
7 // this is definitely a for loop
8 for (q : wowwww)
9 System.out.println(q);
10 System.out.println(wee);
11 }
12 }
Naming
These are all valid variable names…
● neatClass
● doSomething
● wowwww
● weee
But are not helpful to anyone reading your code (including you)
Use variable names that summarize the variable's role or contents

18
Naming
Use variable names that summarize the variable's role or contents
● username: a string containing a users login name
● nextNode: a pointer to the next node in a linked list
● data: the contents of an ArrayList
● leftChild: a pointer to the left child of a BST

19
Indentation/Spacing
1 class neatClass {
2 public static void doSomething(String wowwww) {
3 String weee = "Yes";
4 // this is definitely a for loop
5 for (q : wowwww) System.out.println(q);
6 System.out.println(wee);
7 }
8 }

Consistent spacing helps the reader more quickly understand the structure
of the code
20
Comments
1 // this is definitely a for loop

This comment doesn't actually tell us anything useful (we can clearly see
that what follows is a for loop…)
Comments should provide info that's not already present in the code
● Assumptions you have made when writing the code
● References to documentation/citations
● Clean descriptions of any non-obvious math
● The reasoning behind the chosen solution (especially if it is not the
"obvious" way) 21
Brackets/Braces
1 for (q : wowwww) System.out.println(q);

Java supports one-line for loops. This is a really nifty and easy way
to…introduce bugs into your code.

ALWAYS USE BRACES!

22
Ways to Succeed when Coding
● NEVER start with code
● What do you have to start with? How is it organized?
○ Draw pictures
○ Try examples on paper
● What do you want the result to be? How should it be organized?
○ DRAW MORE PICTURES/EXAMPLES
● Now figure out how the given input and desired output relate
○ Connect your drawings/diagrams
● Break down bigger problems into smaller ones as needed
23
Ways to Obtain Assistance
● Explain what you've tried
○ Which test cases fail (and if you don't have test cases, make them!)
○ What approaches have you tried and how do they break
● Explain what it is you want to accomplish, and why you want to
○ Make sure we have all the context
● Follow coding style guidelines!

24
If you don't feel comfortable with Java…
Remember: Don't start with coding, you should already have plenty of
pictures/examples/ideas before coding
If you bring us (mostly working) pseudocode, the course staff will happily
help you translate it to Java

25
If you don't feel comfortable with Java…
Typical Questions:
● Syntax Questions (eg: How do I break out of a for loop?)
○ Ask on Piazza, Office hours, etc
○ We can give a very direct answer (ie: you can use the break keyword)
● Semantics Questions (eg: How do I insert an item into a linked list?)
○ Still ask the question!
○ …but the answer will generally not involve code

Many of the "syntax" questions we get are actually about semantics 26


Basic Debugging

Live Demo

27
Unit Testing
● When we write code we make a lot of assumptions
○ Often statements of the form [piece of code] should [do a thing]
○ The computer does not know about these assumptions…unless…

28
Unit Testing
● Tests allow us to encode our assumptions in a way that the computer
can understand and automatically check
● Phrases like "[piece of code] should [do a thing]" can become a unit test
● A typical unit test will:
○ Set up a minimal input
○ Invoke the code you want to be tested
○ Test the output/program state to make sure it matches your assumptions

29
JUnit
1 package cse250.examples.debugging;
2
3 import org.junit.Test;
4 import static org.junit.Assert.*;
5
6 public class BreakItDownTest {
7 ArrayList<FarmersMarket> data =
8 BreakItDown.readMarkets(/*...*/);
9
10 @Test
11 void shouldCount75BakedGoods() throws IOException {
12 int count = BreakItDown.countTheBakedGoods(data);
13 assertEquals(75, count);
14 }
15 }
JUnit
1 package cse250.examples.debugging;
2
3 import org.junit.Test; Import the junit package so you can
4 import static org.junit.Assert.*; use its functionality
5
6 public class BreakItDownTest {
7 ArrayList<FarmersMarket> data =
8 BreakItDown.readMarkets(/*...*/);
9
10 @Test
11 void shouldCount75BakedGoods() throws IOException {
12 int count = BreakItDown.countTheBakedGoods(data);
13 assertEquals(75, count);
14 }
15 }
JUnit
1 public class BreakItDownTest {
2 ...
3 }

● Test cases go in normal class files


● Usually they will be in a separate directory (test instead of src)

32
JUnit
1 @Test
2 void shouldCount75BakedGoods() throws IOException {
3 int count = BreakItDown.countTheBakedGoods(data);
4 assertEquals(75, count);
5 }

● Test cases are any normal function, labeled with the @Test annotation
○ Function name does not matter (should still follow good coding style)
○ The return type should be void
○ The function may throw exceptions

33
JUnit
1 assertEquals(75, count);

● Your tests should include one or more assertions


○ This is how you encode your assumptions
○ Usually you will use them to check the output of whatever code your test
just executed

34
JUnit

Live Demo

35
JUnit Advice
● Keep individual test cases (and their inputs) small
○ Try to focus on tests that just test ONE of your functions
○ Tests that test multiple functions working together are still important, but
not that useful if you don't have the small ones working first
● If you are stuck, describe your code out loud
○ If you ever find yourself saying: "well this part should…", make sure you
have a test that confirms that
● At first, try not to think about implementation details
● Write plenty of your own tests, don't just rely on ours
36

You might also like