¡GoConqr estrena diseño! Cuéntanos qué te parece.

Apuntes

Semester 2 Java

Amanda McCauley Computer Science Inglés 2 páginas

Contenido del apunte (2)

Página 1

Review of Semester 1

Objects

Variables

Selection

Repetition

Arrays

Array Lists

Java program:

public class HelloWorld { the fist line of a java program, public means that it can be seen by anyone looting to view the code, every java program contains at least one class, it is contained within curly brackets.

/**

* main

method to print out Hello

*/ comments to document the code, what is does etc.

public static void main(String[ ]

args)

{ every Java program that you need to produce output from contains a main method.It is a method contained within curly brackets.

System.out.println(“Hello World”); A Java program can have many statements.This is one that will run and print to the console panel.

TV Series Class will contain all information about a book

Series Library Class contains all information about a library

Tester Class contains the main method and actually runs the application

boolean = 1 bit

byte = 8 bits

short = 2 bytes

char = 2 bytes

float = 4 bytes

integer = 4 bytes

double = 8 bytes

long numbers = 8 bytes

PEMDAS - Parenthesis, Exponents, Multiplication, Division, Addition, Subtraction. This needs to be considered when doing calculations in Java because different values for number will have an effect on outcome.

Methods in Java

A collection of statements grouped together to perform an operation,

usually to reduce repetition. Each

method consists of a method header and a method body e.g.

modifier

returnValueType methodName (parameter

list)

{

// Method body;

}

A modifier e.g. public, returnValueType e.g. void, methodName e.g. myMethod, (parameter list) e.g. ()

some methods have a parameter type:

public int addInts(int a, int b)

{

int ans = a+b;

return

ans;

}

Selection

Structure for if statement:

if (condition) {

statement(s)

}

if (condition) {

statement(s)

} else {

statement(s)

}

> is Greater than

>= is Greater than or equal to

< is Less than

<= is Less than or equal to

== is Equal to

!= is Not equal to

Comparing strings

To test is two strings are equal use: if (string1.equals(string2)){

Don't use: == for strings it tests if two strings are stored in the same memory location. There is also a compareTo method, this compares strings in lexicographic order (i.e. similar to how words are stored in a dictionary). A statement in the switch block can be labeled with one or more case default labels. The switch statement evaluates its expression then executes all statements of the following label.

The switch statement

A statement in the switch block can be labeled with one or more case default labels. The switch statement evaluates its expression then executes all statements of the following label. e.g.

int

digit = in.NextInt();

switch

(digit) {

case 1: digitName =

“one”; break;

case

2: digitName = “two”;

break;

case

3: digitName = “three”;

break;

default: digitName = “”; break;

}

Boolean variables and operators:

"boolean failed = true; " can then be used later in your program to make a decision e.g.

if (failed) {

}

While loops

while (condition) {

statements

}

e.g. while balance < (less than) target balance true increment year, calculate interest and add interest to balance. false? do non of that.

double

balance = 0; //this variable is declare outside the loop and is updated in the loop.

//if the following condition never becomes false, an infinite loop occurs

while

(balance < targetBalance) {

//the following statements are executed while the condition is true

year++;

double

interest = balance * RATE / 100;

balance

= balance + interest;

}

Infinite Loops

This is a loop that runs forever and can be stopped only by killing the program or restarting the computer. e.g. code like this will produce an infinite loop because 'year' which is initialized as 1 is always less than 20.

int year = 1;

while (year <=20)

{

double interest =

balance * RATE / 100;

balance = balance +

interest;

}

For Loops

Executing a sequence of statements a given number of times. A while loop can be conrolled by a counter. e.g.

int counter = 1;

while (counter <=

10) {

System.out.println(counter);

counter++;

} // this means the loop will run 9 times because the counter++ makes the number increase by 1 every time which it will run until it reaches 10. But.....

The for loop: for(initialization;

condition; update) {

statements

}

for (int counter = 1;

counter <= 10; counter++) {

System.out.println(counter);

}

can do the same thing is less lines of code. It The initializes before

the loop starts, then the condition is checked before each iteration, then the update is executed after each iteration.

Counting down and in steps

A for loop can count down rather than up and increment is steps more than 1:

for (int counter = 10;

counter >= 0; counter--)

for (int counter = 0; counter <= 10; counter+2)

The Do Loop

it is sometimes necessary to execute the body of a loop at least once and then perform the condition test. e.g. for input validation

do {

statements

}

while (condition);

Suppose you ask a user to enter a value <100 and they do not enter a value less than 100 then you need to ask again until a correct value is entered. But remember you cannot test until a value has been input.

int value;

do{

System.out.println("Enter an integer < 100");

value = in.nextInt();

} while (value >=100);

Break statement and continue statement

A break statement in a loop terminates it. It is to breakout of a set of nested statements.

while (true) {

String input = in.next();

if (input.equals(“Q”)) {

break;

}

double x = Double.parseDouble(input);

data.add(x);

}

The continue statement jumps to the end of the current iteration of the loop:

while (!done) {

String input = in.next();

if (input.equals(“Q”)) {

done = true;

continue;

}

double x = Double.parseDouble(input);

data.add(x);

// continue

statement jumps here

}

Arrays

Constructing and Accessing an Array: to construct and array - new typeName[length]

to access an element - arrayReference[index]

double[] values =

new double[10];

double[] moreValues = {32, 54, 67.5,

29, 35};

values[i] = 0;

**double is the type of array

**values is the name of array variable

**double is the element type

** [10] is the length

**{32, 54, 67.5, 29, 35} is the list of initial values

** [i] means the index must be >+0 and < the length of the array. Square brackets are used to access an element.

Limitations of Arrays

•The

length of an array is fixed. If we start out with an array of 10 elements and later decide to add

additional elements we create a new array (and we can copy all of the elements from

the existing array into the new one before adding more).

Testing for the end of the array

for (int i = 0; i < values.length; i++) {

System.out.println(values[i]);

}

Partially filled arrays

An array cannot change size at run time. What if you don't know how many elements you need? You must guess the maximum number of elements that you will need to store. e.g. you will need at least 10 but no more than 100.

In

this instance you will also need a variable to determine how many elements are

currently stored in the array:

int currentSize = 0;

Scanner in = new

Scanner(System.in);

while(in.hasNextDouble()) {

if (currentSize < values.length) {

values[currentSize] = in.NextDouble();

currentSize++;

}

}

Array Lists

To construct an array: new ArrayList<typeName>

To access an element: arraylistReference.get(index);

arraylistReference.set(index, value);

ArrayList<String>

friends = new ArrayList<String>();

friends.add(“Cindy”);

String name = friends.get(i);

friends.set(i, “Harry”);

**ArrayList<String> is varibale type

** friends is variable name

** ArrayList<String>() is an array list object of size 0

**friends.add(“Cindy”) the add method appends an element to the array list increasing its size.

** String name = friends.get(i) // friends.set(i, “Harry”) to use the get and set methods to access an element.

An array list must be initialized i.e. ArrayList<String> names

= new ArrayList<String>()

The "new ArrayList<String>()" is needed for the variable to be initialized. Once it is initialized the array list has a size of 0 and then we can add elements.

Typical array list operations:

•names.add(“Emily”);

•string name = names.get(2);

•names.set(2, “Carolyn”);

•names.add(1,”Ann”);

•names.remove(2);

The enhanced for loop

for(typeName variable : collectionArrayOrArrayList){

statements

}

e.g.

for (double element

: values) {

sum = sum + element;

}

Choosing between array lists and arrays

For

most programming tasks, arrays lists are easier to use than arrays. Array

lists can grow and shrink. But arrays have nicer syntax for element access and initialization. Use an array if

the size of a collection never changes and if

you collect a long sequence of primitive type values and you are concerned

about efficiency. Otherwise,

use an array list.

Objects

Objects share two characteristics: They all have state and behavior. e.g. For a Student:

STATES = stuNo, stuName, stuCourse, stuModules

BEHAVIOURS = getStuNo, getStuName, getStuCourse, getStuModules, setStuNo, setStuName, setStuCourse, setStuModules

Basic structure of an Object class:

// Declaring Class Name

public class StudentReg {

// Declaring Member Variables

private String stuNo, stuName, stuCourse; (private meaning they cannot be accessed outside of the classes

private ArrayList<String> stuModules; (Each registered student will undertake

many modules.)

A list of modules is needed for each

registration.

// Constructor (is public and has no explicit return type)

public StudentReg(String stuNo, String stuName, String stuCourse, ArrayList<String> stuModules) {

this.stuNo = stuNo;

this.stuName = stuName;

this.stuCourse = stuCourse;

this.stuModules = stuModules;

// Object Methods (Behaviours)

getStuNo, getStuName, getStuCourse, getStuModules, setStuNo, setStuName, setStuCourse, setStuModules

}

Página 2

Información

Descripción
Computer Science Apunte sobre Semester 2 Java, creado por Amanda McCauley el 06/03/2017.
Creado por
Amanda McCauley
Visitas
4
Valoración

Escríbenos

¿Sobre qué es tu mensaje?

¿Qué te parece el nuevo diseño?

¿Te gusta?