EMB1006 JAVA Part 2 Arrays and onwards Jonathan-Lee Jones.

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

1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 7.9Arrays of Pointers Arrays can contain pointers For.
© Glenn Rowe AC Lab 2 A simple card game (twenty- one)
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
EXAMPLES. Example 1: Write a Java method that performs addition on two binary numbers. Each binary number is kept in an integer array
CS110 Programming Language I Lab 10: Arrays I Computer Science Department Spring 2014.
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
CS102--Object Oriented Programming Discussion 2: (programming strategy in java) – Two types of tasks – The use of arrays Copyright © 2008 Xiaoyan Li.
12 Pontoon1May Pontoon program CE : Fundamental Programming Techniques.
2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need.
Arrays Liang, Chpt 5. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Arrays Horstmann, Chapter 8. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer Variable Declarations and Initialization 7.3Pointer.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Arrays Declare the Array of 100 elements 1.Integers: int[] integers = new int[100]; 2.Strings: String[] strings = new String[100]; 3.Doubles: double[]
An Overview of JAVA From basic to slightly less basic Jonathan-Lee Jones.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
A Semantic Error in Google last weekend! Someone in Google typed an extra ‘/’ character into their URL List Link to CNN video report posted on Collab.
CPT: Ptr+Str/ Computer Programming Techniques Semester 1, 1998 Objective of these slides: –to discuss how pointers are used with structs.
1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008.
1.4 Arrays "... By the way, we rank 10 th among the industrialized world in broadband technology and its availability. That’s not good enough for America.
JAVA Array 8-1 Outline  Extra material  Array of Objects  enhanced-for Loop  Class Array  Passing Arrays as Arguments to Methods  Returning Arrays.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
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.
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
An Overview of JAVA From basic to slightly less basic Jonathan-Lee Jones.
Session Three Review & Conditional Control Flow. Java File Hierarchy Projects Packages Classes Methods.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Recap of Functions. Functions in Java f x y z f (x, y, z) Input Output Algorithm Allows you to clearly separate the tasks in a program. Enables reuse.
Java Arrays and Methods MIS 3023 Business Programming Concepts II The University of Tulsa Professor: Akhilesh Bajaj All slides in this presentation ©Akhilesh.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
C Lecture Notes 1 Structures & Unions. C Lecture Notes Introduction Structures –Collections of related variables (aggregates) under one name Can.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
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.
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Building Java Programs Chapter 15 Lecture 15-2: testing ArrayIntList; pre/post conditions and exceptions reading:
11 PART 2 ARRAYS. 22 PROCESSING ARRAY ELEMENTS Reassigning Array Reference Variables The third statement in the segment below copies the address stored.
 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.
1 Lecture 8 Pointers and Strings: Part 2 Section 5.4, ,
int [] scores = new int [10];
L19 a 1 Example Using Arrays Using Top-Down Design and Functions to Simplify Code and Create Modules.
 2000 Prentice Hall, Inc. All rights reserved Introduction Structures –Collections of related variables (aggregates) under one name Can contain.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
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.
Arrays. What is an array? An array is a collection of data types. For example, what if I wanted to 10 different integers? int num1; int num2; int num3;
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.
Last Revision. Question1 Novice Java programmers often write code similar to, class C { public int x;... }... C[] a = new C[10]; for(int i = 0; i < a.length;
Methods. Creating your own methods Java allows you to create custom methods inside its main body. public class Test { // insert your own methods right.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
Single Dimensional Arrays
Exceptions and User Input Validation
2.5 Another Java Application: Adding Integers
Repetition Chapter 6 12/06/16 & 12/07/16 1 1
Introduction to Programming
An Introduction to Java – Part I, language basics
Announcements Lab 7 due Wednesday Assignment 4 due Friday.
Announcements Lab 6 was due today Lab 7 assigned this Friday
Task 2 Implementation help
1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2002–2010 · 2/6/11 12:33.
Array Review Selection Sort
Presentation transcript:

EMB1006 JAVA Part 2 Arrays and onwards Jonathan-Lee Jones

Overview Array Recap Using an Array Example Finding the lowest and highest values in an array Defensive Programming

What is an Array As mentioned previously, an array is a method for storing multiple values that are linked together. The name of the array is a pointer to the first address in memory. An array can be of any type, primitive or object (even user defined object for example student records) and can even be made up of other arrays to give a 2 dimensional, 3 dimensional or even greater array.

An Example Array Arrays can be initialised as empty arrays, or just assigned values. To initialise as an empty array we use the following structure: Int N = 100; Int[] testArray = new int[N]; To Initialise by assigning values we use the following structure: Int[] testArray = {1,2,3,4,5,6,7,8,9};

An Example Array class Deck { public static void main(final String args[]) { final String suit[] = {"Clubs", "Diamonds", "Hearts", "Spades" }; final String rank[] = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace" }; final int nr_suits = suit.length; final int nr_ranks = rank.length; final int nr_cards = nr_suits * nr_ranks; final String deck[] = new String[nr_cards]; for (int r = 0, base_index = 0; r < nr_ranks; ++r, base_index+=nr_suits) { for (int s=0; s < nr_suits; ++s) deck[base_index+s] = rank[r] + " of " + suit[s]; }

Shuffling the Deck Using an Array for (int i = 0; i < nr_cards; ++i) { final int rand = i + (int) (Math.random() * (nr_cards-i)); final String t = deck[rand]; deck[rand] = deck[i]; deck[i] = t; } The above code snippet will perform a shuffle on the deck. This is the best method to use with the tools you have for creating a mathematically fair shuffle. You can test this if you want! Below is how you print contents of array (remember printing out the name just prints the memory address pointer!) for (int i = 0; i < nr_cards; ++i) System.out.println(deck[i]);

Finding the Lowest and Highest Values Write a short piece of code to find both the highest and lowest numbers from an array of size N, and print these out, alongside their position in the array. You may need the following:- Integer.MIN_VALUE; Integer.MAX_VALUE; Array.length; For Loop Integer.parseInt();

Finding the Lowest and Highest Values class minmax{ public static void main(String[] args){ int N = args.length; int[]numbers = new int[N]; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; int maxPos =0; int minPos =0; for(int i=0;i<N;++i){ numbers[i]=Integer.parseInt(args[i]); if (numbers[i]>max){ max=numbers[i]; maxPos=i; } if (numbers[i]<min){ min=numbers[i]; minPos=i;}} System.out.println("Max = " + max + " at position " + maxPos +"."); System.out.println("Min = " + min + " at position " + minPos +"."); }} What would happen if zero arguments were entered? What else could go wrong?

Validating Input, Defensive programming When you allow the user to input values into the program, you inevitably invite errors at run time. If you ask for an int and they give a string for example. A large number of these can be avoided by using various scanner tools, but how would you validate command line input? You are tasked with writing a program to take in 3 numbers from the command line, then add the first 2 together then divide by the third. It is a trivial task, but you would be surprised how many problems may occur. Try to make sure that the program will not crash by throwing a run time exception, and also the program gives the expected values. What do you need to check to ensure this.

Validating Input, Defensive programming class threeNums{ public static void main(String[] args){ int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = Integer.parseInt(args[2]); double ans = (a+b)/c; System.out.println(“ans = ” + ans); }

Validating Input, Defensive programming lass threeNums{ public static void main(final String[] args){ final int a = Integer.parseInt(args[0]); final int b = Integer.parseInt(args[1]); final int c = Integer.parseInt(args[2]); double ans = (a+b)/c; System.out.println("ans = " + ans); }

Validating Input, Defensive programming Possible Errors that can occur:- 1.Not enough input arguments (program requires 3, what happens if it gets 2?) 2.If the third input is 0 what will happen? 3.What happens if a= 2,000,000,000 and b = 1,999,999,999? 4.What happens if the user inputs the following values by mistake:- 4 8u 22? Is there anything else that can go wrong with this code? What if the following numbers are input 1, 2 & 2? What output do you expect, and what do you get?