Java Methods 11/10/2015. Learning Objectives  Be able to read a program that uses methods.  Be able to write a write a program that uses methods.

Slides:



Advertisements
Similar presentations
CS110 Programming Language I Lab 10: Arrays I Computer Science Department Spring 2014.
Advertisements

Building Java Programs Chapter 1 Lecture 1-2: Static Methods reading:
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Copyright 2010 by Pearson Education Building Java Programs Chapter 1 Lecture 1-2: Static Methods reading:
Copyright 2008 by Pearson Education Building Java Programs Chapter 1 Lecture 1-2: Static Methods, Avoiding Redundancy reading: self-check:
LAB 10.
Computer Programming Lab(5).
The for-statement. Different loop-statements in Java Java provides 3 types of loop-statements: 1. The for-statement 2. The while-statement 3. The do-while-statement.
Week #2 Java Programming. Enable Line Numbering in Eclipse Open Eclipse, then go to: Window -> Preferences -> General -> Editors -> Text Editors -> Check.
1 2 2 Introduction to Java Applications Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic.
Static methods. 2 Algorithms algorithm: a list of steps for solving a problem Example algorithm: "Bake sugar cookies" –Mix the dry ingredients. –Cream.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
Input/Output in Java. Output To output to the command line, we use either System.out.print () or System.out.println() or System.out.printf() Examples.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Java Arrays and Methods MIS 3023 Business Programming Concepts II The University of Tulsa Professor: Akhilesh Bajaj All slides in this presentation ©Akhilesh.
Copyright 2010 by Pearson Education Building Java Programs Chapter 1 Lecture 1-2: Static Methods reading:
Chapter 6. else-if & switch Copyright © 2012 Pearson Education, Inc.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Java methods Methods break down large problems into smaller ones Your program may call the same method many times saves writing and maintaining same code.
Java Variables, Types, and Math Getting Started Complete and Turn in Address/Poem.
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.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Martin T. Press.  Main Method and Class Name  Printing To Screen  Scanner.
 CSC111 Quick Revision. Problem Write a java code that read a string, then show a list of options to the user to select from them, where:  L to print.
CiS 260: App Dev I. 2 Introduction to Arrays n An array is an object that contains a collection of components (_________) of the same data type. n For.
Computer Programming Lab 9. Exercise 1 Source Code package excercise1; import java.util.Scanner; public class Excercise1 { public static void main(String[]
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Array Review Selection Sort Get out your notes.. Learning Objectives Be able to dry run programs that use arrays Be able to dry run programs that use.
Methods. Creating your own methods Java allows you to create custom methods inside its main body. public class Test { // insert your own methods right.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Permutations and Combinations Review Plus a little Dry Run, Sorting and Code.
CSC111 Quick Revision.
Yanal Alahmad Java Workshop Yanal Alahmad
Java Methods Making Subprograms.
Control Statement Examples
Array Review Selection Sort
Java Enter your code from FRQ to Shell
Java Fix a program that has if Online time for Monday’s Program
Java Variables, Types, and Math Getting Started
Java Methods Making Subprograms.
Truth tables: Ways to organize results of Boolean expressions.
Sorts on the AP Exam Insertion Sort.
AP Java Review If else.
More on Classes and Objects
Selection Insertion and Merge
Java Fix a program that has if Online time for Monday’s Program
Java Methods Making Subprograms.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Building Static Methods
Building Java Programs
Building Java Programs
Introduction to Java Applications
Dry Run Practice Use Methods with an Insertion Sort
AP Java Review If else.
Python Basics with Jupyter Notebook
Building Java Programs
Chapter 1 Lecture 1-2: Static Methods reading:
Java 1/31/2017 Back to Objects.
Building Java Programs
Array Review Selection Sort
Building Java Programs
Random Numbers while loop
Building Java Programs
Presentation transcript:

Java Methods 11/10/2015

Learning Objectives  Be able to read a program that uses methods.  Be able to write a write a program that uses methods.

Program with static method public class FreshPrince { public static void main(String[] args) { rap(); System.out.println(); rap(); } public static void rap() { System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); } } Output: Now this is the story all about how My life got flipped turned upside-down Now this is the story all about how My life got flipped turned upside-down

Method Syntax [static] ( parameter-list ) { return something } public: It can be called from outside the class. For now we will make them all public. private: Can only be called from within the class. (Later) Default (No modifier) Can be accessed within the class and the package (folder). static You do not need to make an instance of the object to use it. For now our methods will be static. If not defined as static, then it is not static. void: Nothing. Like a procedure int, double, char, int [], String [],Class name (Later): Defines the thing being returned. Start with a lowercase letter, and describes what the method is doing. Everything is a value parameter! (type var, type var, type var) return: Jumps out of the method and returns the answer.

Example import java.util.Scanner; // program uses class Scanner public class Addition { // main method begins execution of Java application public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int number1, number2, sum; System.out.print( "Enter first integer: " ); // prompt number1 = input.nextInt(); // read first number from user System.out.print( "Enter second integer: " ); // prompt number2 = input.nextInt(); // read second number from user sum = total(number1, number2); // add numbers System.out.printf( "Sum is %d\n", sum ); // display sum } // end method main public static int total(int first, int second) { return first+second; } } // end class Addition Can be called from outside the class. Does not need to be instantiated, made into an object, to use. Returns an integer

Breaking down the method public static int total(int first, int second) { return first+second; } Can be called from outside the class Can be called without first making an object Returns an integer value Name of the method Parameters/ messages. Everything is a value parameter! Used to return a value from the method and kick out of the method

Dry run in your notebook public static void fun(int a, int b) { a+=b; b+=a; } What is the output from the following code int x = 3, y = 5; fun(x, y); System.out.println(x + “ “ + y);

Dry run public static int fun2(int x, int y) { y -= x; return y; } What are the values of a and b after the following? int a = 3, b = 7; b = fun(a, b); a = fun(b, a);

What does the following method do? public static int process(double amt) { return (int) (amt * ) % 100; } A) Returns the cent portion of amt. B) Returns the number of whole dollars in amt. C) Returns amt converted to the nearest cent D) Returns amt rounded to the nearest integer E) Returns amt truncated to the nearest integer Order of ops 1)() 2)[], x++, x--, !x, (type casting) 3)*, /, % 4)+, - 5) = 6)==, != 7)&& 8)|| 9)=, +=, -=,

Dry run R2 (A2.6). Consider the following method public int change(int value) { if(value < 3) return value % 3; else return value % * change(value/3); } What will be returned by the call change(45)? A.0 B. 21 C.150 D.500 E.1200

12 When a method is called, the program's execution... –"jumps" into that method, executing its statements, then –"jumps" back to the point where the method was called. public class MethodsExample { public static void main(String[] args) { message1(); message2(); System.out.println("Done with main."); }... } public static void message1() { System.out.println("This is message1."); } public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with message2."); } public static void message1() { System.out.println("This is message1."); } Control flow

Style Declare the main method as the first method. Declare other methods later.

Stats Pack: Write a program with methods to calculate the following. Factorial –Sent a positive integer, returns its factorial. (Note: 0! = 1) Combinations Write a method that will find the number of combinations of n items taken r at a time. Combinations of n items take r at a time= n!/((r!)(n-r)!) –Enter the values for n and r in the main body –Calculate and return the number of combinations in the method –Show the number of combinations in the main body. Permutations Write a method that will find the number of permutations of n items taken r at a time. Permutations of n items taken r at a time= n!/(n-r)! –Enter the values for n and r in the main body –Calculate and return the number of combinations in the method –Show the number of combinations in the main body.

public static void sort(String [] list) { for(int start = 0; start < list.length-1; start++) { int index = start; for(int k = start + 1; k < list.length; k++) { if(list[k].compareTo(list[index]) > 0) index = k; } String temp = list[start]; list[start] = list[index]; list[index] = temp; } Assume the String array words is initialized as shown below. word BillJoeSueAnnMelZeb What will the array word look like after the third pass through the outer loop in the call sort(word)? Note how an array is passed to a method.

Insertion Sort // a is the name of the array // nElems stores the number of elements being sorted // This example is for sorting an array of ints int in, out; for(out=1; out<nElems; out++) // out is dividing line { int dummy = a[out]; // dummy Need to modify for sorting different types in = out; // start shifts at out while(in>0 && a[in-1] >= dummy) // until one is smaller, { a[in] = a[in-1]; // Slide: shift item right, in--; // go left one position } a[in] = dummy; // Back: insert marked item } // end for

Second Method Program Main Body –Get 9 scores –Call methods –Show results Scores in order Low to High Mean, median Push: Mode, standard deviation Methods –Insertion Sort –Mean –Median –Push: Mode, standard deviation