# CSE 114 – Computer Science I Lecture 1_ Introduction_7_

Document Sample

CSE 114 – Computer Science I
Variables & Expressions

Niagara Falls, Ontario/New York
Algorithms & Software Engineering

• What is an algorithm?
– a sequential set of steps used to solve a problem
Design, then code

• Generalized steps of software engineering:
1. Understand and define the problem
2. Determine the required input and output
3. Design an algorithm to solve the problem by computer
4. Implement (code) the solution
5. Debug and test the software
6. Maintain and update the software

• Which is the most challenging step?
Designing a Program Example
• Problem:
–   you have to give someone change
–   what coins do you give that person?

• Requirements:
–   make a program to do this
–   takes user input
–   displays the change breakdown as output
1. Understand and Define the Problem
• What are the needs of the program?
–   US coins (quarter, dime, nickel, penny)
–   max change: 99¢
–   display coin output

• Typically done through Requirements Analysis
Who performs a Requirements Analysis?

• IT people

• What’s involved?
– interview users
• What are their expectations?
• What data do they need to access?
• Etc.
– write a requirements analysis report
2. Determine Input and Output
• Typed input by user:
–   Amount of change requested
(an integer between 1 and 99)

• Printed output:
–   Number of quarters given
Number of dimes given
Number of nickels given
Number of pennies given
3. Design an algorithm
A. How many quarters?
–   subtract the number of quarters X 25 from the total

B. How many dimes?
–   subtract the number of dimes X 10 from remaining total

C. How many nickels?
–   subtract the number of nickels X 5 from remaining total

D. How many pennies?
–   the remaining total
3. Design an algorithm (continued)
•   Pseudocode:

User Input originalAmount
numQuarters       originalAmount div 25
remainder         originalAmount mod 25
numDimes          remainder div 10
remainder         remainder mod 10
numNickels        remainder div 5
remainder         remainder mod 5
numPennies        remainder
Output numQuarters
Output numDimes
Output numNickels
Output numPennies
import java.util.Scanner;
public class ChangeMaker       4. Code your solution
{
public static void main(String[] args)
{
int change, rem, qs, ds, ns, ps;
System.out.print("Input change amount (1-99): ");
Scanner input = new Scanner(System.in);
change = input.nextInt();
qs = change / 25;
rem = change % 25;
ds = rem / 10;
rem = rem % 10;
ns = rem / 5;
rem = rem % 5;
ps = rem;
System.out.println(qs + " quarters");
System.out.println(ds + " dimes");
System.out.println(ns + " nickels");
System.out.println(ps + " pennies");
} // main
} // class ChangeMaker
5. Debugging and Testing

• What’s the difference?

• What’s a bug?

• Note, this step may lead to a feedback loop
– To step 4
• to fix bugs, improve performance, etc.
– To step 3
• to fix design
• a disaster
Design fail

http://img2.allposters.com/images/147/SHEA.jpg
A Solution

Types of Errors
•   Syntax Errors
Grammatical mistake in program
Detected by the compiler
Example: = + z x y;

•   Runtime Errors
Illegal action during execution
Detected by runtime environment
Example: Calling a method on null

•   Logical Errors
Incorrect action during execution
May not be detected!
Example: qs = change % 25;
Finding an error’s source (debugging)

1. On a piece of paper, draw a table where each variable
in your code has its own column

all its consequences

3. As variables change, update your table

4. When a variable reaches an illegal or incorrect value,
6. Maintain the software

• This can be long-term care

http://www.animationconnection.com/view/fcc2726
On to Java

• Java is a language for giving a computer
instructions

• What does a language have?
– vocabulary
– names (identifiers)
– rules of grammar
Java Vocabulary Words (Keywords)
• abstract, assert, boolean, break,
byte,   case,  catch,    char,   class,
const, continue, default, do, double,
else, enum, extends, false, final,
finally,   float,   for,    goto,   if,
implements, import, instanceof, int,
interface, long, native, new, null,
package, private, protected, public,
return,   short,   static,    strictfp,
super, switch, synchronized, this,
throw, throws, transient, true, try,
void, volatile, while
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
Keywords
• Reserved words

• They have specific meaning to the Java
compiler

• You may not use them for your own names
– variables, methods, and classes

• From 2 sources:
– your own classes, variables, and methods
– the Sun (or someone else’s) API

• What’s an API?
– Application Programming Interface
– a library of code to use
• You may define variables, classes, and methods

• You must name them. Why?
– they are your data and commands
– you’ll need to reference them elsewhere in your program

int myDumbVariable = 5;
…
…
…
int myDumberVariable = myDumbVariable + 1;
Rules for Identifiers
1. Should begin with a letter
2. Should contain only letters, numbers, & ‘_’
3. Uppercase and lowercase letters are considered to be
different characters

• Legal:     “myVariable”,           “my_class”,
“my4Variable”,          “myClass_”

• Illegal:   “4myVariable”,          “_myclass”
“my!Variable”,          “@#\$myClass”
Naming Conventions

• Variable and Class identifiers should generally be nouns

• Method identifiers should be verbs

• Use Camel notation:          “myVariable”,          “MyClass”
Use descriptive names
• Descriptive names clarify the purpose of your code.

• Which is better?
// OR
a = p * r * r;

• The API likes descriptive names. Ex:
– DefaultMutableTreeNode
– compareToIgnoreCase
Variables
• In a program, they store data

• Primitives store single pieces of data (ex: char)
char letter = 'A';

• Objects store multiple pieces of data (ex: String)
String text = "ABCDEFG";

• All Java variables must have a declared type

• A variable’s type determines:
– what kind of value the variable can hold
– how much memory to reserve for that variable
Java’s Primitive Types
• Integers (whole numbers)
–   byte – 1 byte (-128 to 127)
–   short – 2 bytes (-32768 to 32767)
–   int – 4 bytes (-2147483648 to 2147483647)
–   long – 8 bytes (-9223372036854775808 to 9223372036854775807)

• Real Numbers
– float – 4 bytes
– double – 8 bytes

• char – 2 bytes
– stores a single character (Unicode)

• boolean – stores true or false values
Variables must be declared
before being assigned values
public void methodWithGoodDeclaration()
{
double salary;
salary = 5.0;
System.out.println("Salary is " + salary);
}

{
salary = 5.0;
double salary;
System.out.println("Salary is " + salary);
}
Variables must be initialized
before being referenced
public void methodWithGoodReference()
{
double salary;
salary = 5.0;
double raise = salary * 0.05;
System.out.println("Raise is " + raise);
}
{
double salary;
double raise = salary * 0.05;
System.out.println("Raise is " + raise);
}
Variables should only be declared once
public void methodWithGoodDeclaration()
{
double salary = 5.0;
System.out.println("Salary is " + salary);
salary = 6.0;
System.out.println("Salary is " + salary);
}
{
double salary = 5.0;
System.out.println("Salary is " + salary);
double salary = 6.0;
System.out.println("Salary is " + salary);
}
Variables can be declared
and initialized at once
char yesChar = 'y';

String word = "Hello!";

double avg = 0.0, stdDev = 0.0;

char initial3 = 'T';

boolean completed = false;
Variables can only be used inside the { …}
that they themselves are declared
public void methodWithGoodScope()
{
double x = 5.0;
if (x > 0.0)
{
System.out.println("x is " + x);
}
}
{
double y = 100.0;
if (y > 0.0)
{
double x = 5.0;
}
System.out.println("x " + x);
}
‘=’ : The Assignment Statement
variable = expression ;

• What does it do?
– solve expression first
– assign single result to variable

• What’s the output?
int x = 5;
x = x + x + x + 10;
System.out.print(x);                 25
‘=’ & Assignment Compatibility
• The variable and expression should be the same type
– if not, you may get a compiler error.

• Examples:
sumGrades = 1472 + 1;                  LEGAL

• Are these assignment statements ok?
int x = 5;
long y = x;
double z = y;

double a = 6.5;
long b = a;
int c = b;
Be careful mixing types
byte < short < int < long < float < double

• No assigning:
– big types to little types
– real types to integer types

• Why?
– potential loss of data

• Java is looking out for you
Type Casting as a type override
• You can tell Java that you can look out for yourself

• Type casting
– temporarily change a data type to another type
– use (type), ex: (int)
– no type casting to/from boolean

• Example:
double myReal = 10.0;
int goodInt = (int)myReal;
double myNum = goodInt;
So how can we fix these?
double a = 6.5;
long b = a;
int c = b;

double a = 6.5;
long b = (long)a;
int c = (int)b;

• What are the values of b and c?
Arithmetic Operators

-   Subtraction

*   Multiplication

/   Division

%   Modulo (integer operands only)
What’s the output?

int x = 5;
int y = 10;
int z = 2;
30
int num1 = (x + y) * z;
System.out.println(num1);

int a = 5;
int b = 10;
int c = 2;                  25
int num2 = a + b * c;
System.out.println(num2);
My Advice: avoid rules of precedence

12
• What’s the output?
4
int r2d2c3po;
r2d2c3po = 3 * 4 + 5 / 6;
System.out.println(r2d2c3po);
r2d2c3po = (3 * (4 + 5))/ 6;
System.out.println(r2d2c3po);
The Tricky Division Operator
• Remember, evaluate full expression first

• What values are assigned to the variables below?
double average = 100.0/8.0;                     12.5
average = 100.0/8;                              12.5
average = 100/8;                                12.0
int fifty_percent = 50/100;                     0
double fiftyPercent = 50/100;                   0.0
fiftyPercent = 50.0/100.0;                      0.5
%

• The modulo operator

• Produces division remainders

• What’s the output?           4
remainder = 100 % 8;
System.out.println(remainder);
Increment/Decrement Operators

++   Increment by one

--   Decrement by one

+=   Increment by custom amount

-=   Decrement by custom amount

*=   Multiply by custom amount

/=   Divide by custom amount
What’s the output?
int x=5, y=5, z=5;
x = x + 1;
y++;
z += 1;
System.out.println(x);        6
System.out.println(y);        6
System.out.println(z);        6
What’s the output?
int a=5, b=5, c=5;
a = a + 2;
b++;
b++;
c += 2;
System.out.println(a);        7
System.out.println(b);        7
System.out.println(c);        7
What’s the output?
int i=2, j=2, k=2;
i = i * 2;
j++;
j++;
k *= 2;
System.out.println(i);        4
System.out.println(j);        4
System.out.println(k);        4
Java Program Format
public class ClassName
{
public static void main(String[] args)
{
// ClassName PROGRAM’S POINT OF ENTRY
// THIS PROGRAM’S INSTRUCTIONS
// START HERE
}
}

• Obviously, ClassName would change for each program
Java Applications start at main
• “ClassName.java” must have a public class named
“ClassName”

• ClassName is executable because it has a main method
– we can compile and then run it

• Not all classes require main methods
– only those that initiate program execution
Example Program: HelloWorldApp.java
• javac – program to compile .java files into .class files
• java – program to run .class files
Our first program: HelloWorldApp.java
/**
* HelloWorldApp is a Java application
* that simply displays "Hello World!“ in the
* Java console.
*/
public class HelloWorldApp
{
public static void main(String[] args)
{
System.out.println("Hello World!");
// Statement above displays "Hello World!"
}
}
import java.util.Scanner;
public class ChangeMaker                   Remember our
{
public static void main(String[] args)
program?
{
int change, rem, qs, ds, ns, ps;
System.out.print("Input change amount (1-99): ");
Scanner input = new Scanner(System.in);
change = input.nextInt();
qs = change / 25;
rem = change % 25;
ds = rem / 10;
rem = rem % 10;
ns = rem / 5;
rem = rem % 5;
ps = rem;
System.out.println(qs + " quarters");
System.out.println(ds + " dimes");
System.out.println(ns + " nickels");
System.out.println(ps + " pennies");
} // main
} // class ChangeMaker
What’s next?

• User input

• Text processing

• Output

DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
 views: 4 posted: 7/6/2012 language: English pages: 52
How are you planning on using Docstoc?