Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to Computer Science Class #5 Main Method and Debugging Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj, Isaiah, Allison,

Similar presentations


Presentation on theme: "Intro to Computer Science Class #5 Main Method and Debugging Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj, Isaiah, Allison,"— Presentation transcript:

1 Intro to Computer Science Class #5 Main Method and Debugging Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj, Isaiah, Allison, Thibault University of Pennsylvania 20 February 2008

2 Today’s Agenda Discussion/Demo (LoopingBot) Review Main Method Debugging Debugging Lab Adding a main method

3 Discussion/Demo Let’s talk about LoopingBot

4 Reminder:.hist files & comments What do we use.hist files for? –To avoid retyping the same statements into the interactions pane over and over. What do we use comments for? –Making code more readable to yourself and others // for single line comments /* for single line comments */ /* * …or multi-line comments */ –To create javadocs so the features of the program are easy to see without having to go through the code /** for single or multi-line javadoc comments */

5 Reminder:.hist files & comments What do we use.hist files for? –To avoid retyping the same statements into the interactions pane over and over. What do we use comments for? –Making code more readable to yourself and others // for single line comments /* for single line comments */ /* * …or multi-line comments */ –To create javadocs so the features of the program are easy to see without having to go through the code /** for single or multi-line javadoc comments */

6 Reminder: Control Flow if statements, while loops, for loops –These all allow the program to “decide” whether or not to execute sections of code. –Tells your program to only execute a certain section of code if a boolean expression evaluates to true. Boolean Expressions -- What are the following operators and when do they evaluate to true/false? –&&, II, !,, >=, ==, !=

7 Reminder: if Statements, while loops, for loops if statements –Execute body_of_statement once if a boolean expression evaluates to true. –Always an “if”, 0-unlimited number of “ else if ” expressions and 0-1 “else” If boolean_expression1 is true, execute body_of_ statement1, if it’s false and boolean_expression2 is true, execute body_of_statement2, etc If none of the boolean expressions evaluate to true, then execute the body of the “else” (if there is an “else”). While loops –Loops through the body until the boolean expression becomes false. For loops –initialization: Executes once before loop begins. Sets up variables. Scope: Variables declared during this step are only valid within the loop. No code outside of the loop can use it. –boolean expression: Tested before each loop iteration. If false, stops executing loop body. –increment: changes value of variable after each loop iteration. if ( boolean_expression1 ) { body_of_statement1 } else if ( boolean_expression2 ) { body_of_statement2 } else { body_of_statement3 } while (boolean_expression) { body_of_loop; } for (initialization; boolean_expression; increment) { body_of_loop; }

8 Reminder: What do these do? Examples: if(gotExerciseToday && isBedtime) isTired = true; else isTired = false; boolean likesDogs = true; while (likesDogs) { playWithDogs(); if(gotBit() == true) { likesDogs=false; } } for (int i=0; i<10; i++) { move(); eatDot(); }

9 Main Method public static void main(String[] args) { main_body } public static void – We will ignore these for now (we already know what void means…what does it mean?) main – Name of this special method –When the program sees a method named “main” it knows to start there, execute all statements in the main_body and terminate when it gets to the end. String[] args – The main method accepts one parameter: an array (we’ll learn about arrays later) of Strings. –Each String in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. main_body – We’ve been testing our class definitions and methods in the interactions pane. All of that can go here now.

10 Main Method //This program creates a LoopingBot who eats all the dots in a BotWorld public class LoopingBotDemo { public static void main(String[] args) { BotWorld world = new BotWorld(); LoopingBot myBot = new LoopingBot(world); myBot.eatAllDots(); } /* after compiling, type (into the interactions pane): * java LoopingBotDemo * this causes the computer to execute the main method body found in * the LoopingBotDemo class. * demo of this… */

11 Debugging What is a bug? –An error in code 3 general types of bugs/errors: Compile-time errors –Bad syntax -- missing semicolons, parentheses, or braces; type mismatches such as trying to assign a boolean to an int. Run-time errors (Exceptions) –Program “breaks” – not caught during compilation -- Divide by zero, run out of memory (infinite loop). Logic errors –Bad semantics -- Doesn't behave as it should, e.g. calculation is done incorrectly.

12 Compile-Time Errors public class Hello{ int h; public Hello() { h=0 } public myMethod() { h=1; } } 2 errors found: File: C:\blahblah\Hello.java [line: 5] Error: C:\blahblah\Hello.java:5: ';' expected File: C:\blahblah\Hello.java [line: 8] Error: C:\blahblah\Hello.java:8: invalid method declaration; return type required  Click on the Error in the interactions pane and it will highlight the line that contains the error

13 Compile-Time Errors public class Hello{ int h; public Hello() { h=0 } public myMethod() { h=1; } } 2 errors found: File: C:\blahblah\Hello.java [line: 5] Error: C:\blahblah\Hello.java:5: ';' expected File: C:\blahblah\Hello.java [line: 8] Error: C:\blahblah\Hello.java:8: invalid method declaration; return type required  Click on the Error in the interactions pane and it will highlight the line that contains the error

14 Compile-Time Errors What to do: –Start from the top –Look at description, line number and file –Note that DrJava highlights the line in question –If you haven't done so already, ask DrJava to display all line numbers by choosing (Edit -> Preferences -> Display Options -> Line Numbers) –After fixing ONE error, save and compile again. Fixing one error may cause other errors to appear/go away. –If there are still errors, repeat

15 Run-Time Errors (Exceptions) Two common exceptions: –NullPointerException -- Usually an attempt was made to use the dot '.' operator with a variable whose value is null. –ArrayOutOfBoundsException -- An attempt was made to access an array element that doesn't exist. Example: one tried to index less than 0 or greater than the length of the array minus 1. Haven’t learned about arrays yet, but you will probably see this one a lot. Again: Check out name, line number, program

16 NullPointerException public class Hello { int h; public Hello() { h=0 } public void myMethod() { Goodbye bye = null; //Assume there’s a Goodbye Class bye.sayGoodbye();//and that class has a sayGoodbye method} > Hello hey; > hey.myMethod(); NullPointerException: at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) What is the exception for here?

17 NullPointerException public class Hello { int h; public Hello() { h=0 } public void myMethod() { Goodbye bye = null; //Assume there’s a Goodbye Class bye.sayGoodbye();//and that class has a sayGoodbye method} > Hello hola = new Hello(); > hola.myMethod(); NullPointerException: at Hello.myMethod(Hello.java:11) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) What is the exception for here?

18 Logic Errors This is arguably the worst of the errors and the hardest to fix. Remember, the program does what you tell it. –If you don’t tell it to do the right thing, it can’t help you. –No compiler to figure out if what you did was wrong. Make sure to TEST your program in lots of different situations to see that it’s working right! –What if you wrote facebook and your showInbox method accidentally posted the contents of your inbox on your wall? –What if you write a program to automatically distribute medicine to patients and it gives them the wrong amount? –What your program controls the course of a rocket and a miscalculation causes it to crash? (The last 2 actually happened) How can we trace through the code to figure out what it’s doing? Print Statements Debugger

19 Print Statements System.out.print( string ); Used to print text on the terminal screen Use print statements to check the values of your variables if they’re not behaving as you’d expect. System.out.print(“hi”) v. System.out.print(“hi\n”) v. System.out.println(“hi”) –\n is a special newline character which is like pressing enter at the end of the line. > System.out.print(“hi”); hi> System.out.print(“hi\n”); hi > System.out.println(“hi”); hi > ‘+’ concatenates two strings together. –i.e. “Hello ”+”World” becomes “Hello World” –When ‘+’ing an int, double, boolean or char to a String, the value it holds automatically becomes a string > int x = 57; > int y = 200; > System.out.println(“x is “ + x + “, y is “ + y); > x is 57, y is 200

20 Debugger Using the Debugger –Go to Debugger menu –Select the "Debug Mode". –Set breakpoints in source files. These are places where your program will stop. Here you can interact with variables that are in scope in the suspended method. Resume the method call, or step through it a line at a time as you watch these variables. Don’t forget that if you modify the file while you’re debugging, you need to recompile it for the changes to be put into effect. Demo…

21 Now… Reaction Paper 5: Write down something you were confused about from class and a short explanation about what confused you (1-3 sentences). (Submit using the submission link). Debugging Lab https://www.seas.upenn.edu/~cis1xx/projects/Debug/CompileRuntim eLogicErrors/ -Hint: The rule for multiple constructors is that they’re allowed if their parameter lists don’t take in the same TYPE of variable in the same order (ex. if we have a constructor, BetterBot(String a, int b), we can’t have BetterBot(String x, int y) but CAN have BetterBot(int y, String x) Add a main method http://www.seas.upenn.edu/~eas285/forSLAStudents/lectures/l ecture5_MainMethodDebugging/AddAMainMethod.shtmlAdd a main method

22 Later… Finish and submit Debugging Lab with added main method. Ask questions on the bulletin board.


Download ppt "Intro to Computer Science Class #5 Main Method and Debugging Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj, Isaiah, Allison,"

Similar presentations


Ads by Google