Classes, methods, and conditional statements We’re past the basics. These are the roots.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Intro Programming By Trevor Decker Team 1743 By Trevor Decker Team 1743.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
 Demonstrate use of a “for loop” in the design and development of a Java program to calculate the total of a one-dimensional array of 6 integers.  Design.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
CS107 Introduction to Computer Science Loops. Instructions Pseudocode Assign values to variables using basic arithmetic operations x = 3 y = x/10 z =
Primitive Data Types byte, short, int, long float, double char boolean Are all primitive data types. Primitive data types always start with a small letter.
An intro to programming The basic nitty-gritty that’ll make you scratch your head and say, “This is programming?”
 To be able to write larger programs ◦ By breaking them down into smaller parts and passing data between the parts.  To understand the concepts of Methods.
Writing methods. Calling Methods nameOfMethod(parameters) if method returns something, use that value Math.pow(2, 3) returns 8 System.out.println(Math.pow(2,
Programming – Touch Sensors Intro to Robotics. The Limit Switch When designing robotic arms there is always the chance the arm will move too far up or.
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Arrays (Part 1) Computer Science Erwin High School Fall 2014.
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Week 6 - Wednesday.  What did we talk about last time?  Exam 1 post-mortem  Recursive running time.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Repetition & Loops. One of the BIG advantages of a computer: ­It can perform tasks over and over again, without getting bored or making mistakes (assuming.
Variables and Functions. Open your Encoder program Let’s begin by opening the “Labyrinth Auto Straight” code. Save this file as Labyrinth with variables.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 5.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
CS101 Computer Programming I Chapter 4 Extra Examples.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
COM S 207 Method Instructor: Ying Cai Department of Computer Science Iowa State University
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
VARIABLES Programmes work by manipulating data placed in memory. The data can be numbers, text, objects, pointers to other memory areas, and more besides.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
Week 61 Introduction to Programming Ms. Knudtzon C Period Tuesday October 12.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Java Review if Online Time For loop Quiz on Thursday.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Arrays-. An array is a way to hold more than one value at a time. It's like a list of items.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
OOP Basics Classes & Methods (c) IDMS/SQL News
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
TOPIC 8 MORE ON WHILE LOOPS 1 Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson,
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Introduction to Programming the Arduino Dr Gaw 3/21/14.
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
Information and Computer Sciences University of Hawaii, Manoa
CSC111 Quick Revision.
Computer Programming Methodology Introduction to Java
User input We’ve seen how to use the standard output buffer
Chapter 4 – Control Structures Part 1
Counted Loops.
Lecture 07 More Repetition Richard Gesick.
Programming – Touch Sensors
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
While Statement.
Java Fix a program that has if Online time for Monday’s Program
Coding Concepts (Sub- Programs)
Java Fix a program that has if Online time for Monday’s Program
Chapter 3: Selection Structures: Making Decisions
Just Enough Java 17-May-19.
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Loops and Iteration CS 21a: Introduction to Computing I
Class code for pythonroom.com cchsp2cs
Looping Structures.
Presentation transcript:

Classes, methods, and conditional statements We’re past the basics. These are the roots.

What is a class? A class is an object variable. Classes can be divided into subclasses that inherit some properties of the superclass. Built into the Java language are a variety of classes that contain useful functions and calculating tools. We’ll work more with classes later after we learn about methods.

The main class In Java, the main class is the actual program itself. It is executable. import extra.*; public class Graduation { public static void main(String args[]) { Std.out.println( “This is a very simple program.” ); } public – can be accessed by all parts of the program class – signifies that the code between the braces { } belongs to a class Graduation – gives the class a name, always begins with a capital letter.

What is a method? A method is a smaller block of code designated to do something. It usually takes input and gives output, but sometimes it doesn’t need one or the other (or either). A method is like a mini-program that can be run over and over. Methods are sometimes called “subroutines” or “functions.”

The main method In Java, the main method is where the computer begins to read code when the program runs. import extra.*; public class Graduation { public static void main(String args[]) { Std.out.println( “This is a very simple program.” ); } public – can be accessed by all parts of the program static – the function is permanent void – the function gives no output to the computer itself main – the function is the program’s main function String args[] – we are coding using text

Methods in action Write a program to do the following: The user will input two double variables, a and b, representing the lengths of the arms of a right triangle The program must find the value of the hypotenuse squared, that is, a 2 +b 2 How could we write a program to do this?

A solution import extra.*; public class Graduation { public static void main(String args[]) { double a; double b; double cSquared Std.out.println( “Please input a.” ); a = Std.in.readDouble(); Std.out.println( “Please input b.” ); b = Std.in.readDouble(); cSquared = Math.pow(a,2) + Math.pow(b,2) Std.out.println( “c^2 equals” + cSquared); }

A better solution: use a method Whenever there is an operation that we perform repeatedly, it is helpful to place it into its own method.

How to write a method Here’s the structure of a method: modifier resulttype name (inputs) { calculations; return; } Here’s what our method for squaring might look like: private double square (double d) { double dSquared = Math.pow(d^2); return dSquared; } private because only our class needs to be able to use it double because the return (or output) is a double

Implementing a method Place the code for the method itself inside the class, either before or after the main method To call a method from the main class, write the method’s name, followed by the method’s argument (input) in parens. Example: double aSquared = square(a);

A better solution: the code import extra.*; public class Graduation { private double square (double d) { double dSquared = Math.pow(d^2); return dSquared; } public static void main(String args[]) { double a; double b; double cSquared Std.out.println( “Please input a.” ); a = Std.in.readDouble(); Std.out.println( “Please input b.” ); b = Std.in.readDouble(); cSquared = square(a) + square(b); Std.out.println( “c^2 equals” + cSquared); }

Your turn: Write a method (not a program) that takes an integer as its argument (input), halves the integer, and returns (outputs) a double as the answer. Your method should be private.

A solution private double half (int i) { double halfOfI = i / 2.0 ; return halfOfI; } Notice: we divided an integer by a double (i/2.0). If we had divided an integer by an integer (i/2), the resulting integer would be truncated, and so would the double. Remember: the argument is input, the return is output

Conditional statements! Conditional statements are the heart of programming, they allow the program to react differently to different inputs

The while statement Suppose we want to make a program that counts to ten. We want our program to start counting at one, but we want it to know to stop counting, too! How do we get it to stop counting at ten?

Writing a while statmenet int counter = 1; while ( counter <= 10 ) { Std.out.println( counter ); counter++; }

Mechanics of a while statement If the condition inside the parens () is TRUE, the code inside the braces {} is executed. If the condition inside the parens () is FALSE, then the code inside the braces {} is NOT executed. int counter = 1; while ( counter <= 10 ) { Std.out.println( counter ); counter++; }

The if statement Revist the Graduation program that calculated the years left you had in high school. It would be prudent to put in code that prevents the input of a number greater than 12.

Writing an if statmenet The last line in our code was this: lastGrade = Std.in.readInt(); Here’s what a good if statement would look like: if ( lastGrade > 12 ) { Std.out.println(“You’ve already graduated.”); } else { int yearsLeft; yearsLeft = 12 - lastGrade;... }

Mechanics of an if statement If the condition inside the parens () is TRUE, the code inside the braces {} is executed. If the condition inside the parens () is FALSE, then the code inside the braces {} is NOT executed. Instead, the code inside the braces after else is executed. (The else and its braces are optional.) if ( lastGrade > 12 ) { Std.out.println(“You’ve already graduated.”); } else { int yearsLeft; yearsLeft = 12 - lastGrade;... }

The for loop Suppose we want to make a program that prints the squares of the first ten integers We could use a while loop, but we could also use a for loop…

Writing a for loop int counter; for ( counter = 1; counter <=10; counter++ ) { Std.out.println( (counter * counter) ); }

Mechanics of a for loop There are THREE statements in the parens(), and there are semicolons after the first two. The FIRST statement is executed the first time through the loop, and the THIRD statement is executed at the beginning of each subsequent trip through the loop. If the SECOND is true, then the code inside the braces {} is executed. If it is FALSE, then the code inside the braces {} is NOT executed. int counter; for ( counter = 1; counter <=10; counter++ ) { Std.out.println( (counter * counter) ); }

It’s your choice! while loop: int counter = 1; while ( counter <= 10 ) { Std.out.println( ( counter * counter ) ); counter++; } for loop: int counter; for ( counter = 1; counter <=10; counter++ ) { Std.out.println( (counter * counter) ); }

Combining methods and conditional statements! Write a program that asks a user for two integers: a base and an exponent. The program should check to make sure that the exponent is at least 1. Then, the program should use a method (not Math.pow) to do the multiplying. Some kind of loop should be used.