Download Variable - Computer Science, Stony Brook University

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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?
–
–
–
–
ask user for input
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
{
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
4. Code your solution
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
http://1.bp.blogspot.com/_wsmQgCGIMbQ/SZ3MPdDstHI/AAAAAAAAEd0/d9uE-y5fJIg/s400/Shea+Stadium+AP.jpg
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
2. Step through your program, following your code and
all its consequences
3. As variables change, update your table
4. When a variable reaches an illegal or incorrect value,
you have found your error.
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
What about names?
• 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
Your Identifiers (Names)
• 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”,
“my4Variable”,
“my_class”,
“myClass_”
• Illegal:
“4myVariable”,
“my!Variable”,
“_myclass”
“@#$myClass”
Naming Conventions
• Variables & Methods start with lower case letters
• Classes start with upper case letters
• 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?
area = PI * radius * radius;
// OR
a = p * r * r;
• The API likes descriptive names. Ex:
– LinkedList
– 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);
}
public void methodWithBadDeclaration()
{
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);
}
public void methodWithBadReference()
{
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);
}
public void methodWithBadDeclaration()
{
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);
}
}
public void methodWithBadScope()
{
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:
int sumGrades, gradeX, gradeY;
gradeX = 1;
sumGrades = 1473;
sumGrades = 1472 + 1;
sumGrades = 1472 + gradeX;
sumGrades = true;
sumGrades = 1472 + gradeY;
LEGAL
LEGAL
LEGAL
LEGAL
ILLEGAL
ILLEGAL
What about mixing numeric types?
• Are these assignment statements ok?
int x = 5;
long y = x;
double z = y;
• What about these?
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 badInt = myReal;
int goodInt = (int)myReal;
double myNum = goodInt;
So how can we fix these?
double a = 6.5;
long b = a;
int c = b;
• Add type casts:
double a = 6.5;
long b = (long)a;
int c = (int)b;
• What are the values of b and c?
Arithmetic Operators
+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulo (integer operands only)
What’s the output?
int x = 5;
int y = 10;
int z = 2;
int num1 = (x + y) * z;
System.out.println(num1);
int a = 5;
int b = 10;
int c = 2;
int num2 = a + b * c;
System.out.println(num2);
30
25
My Advice: avoid rules of precedence
• Instead use full parenthesization
• What’s the output?
12
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;
average = 100.0/8;
average = 100/8;
int sumGrades = 100/8;
sumGrades = 100.0/8.0;
sumGrades = (int)100.0/8.0;
sumGrades = (int)(100.0/8.0);
int fifty_percent = 50/100;
double fiftyPercent = 50/100;
fiftyPercent = 50.0/100.0;
12.5
12.5
12.0
12
ERROR
ERROR
12
0
0.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);
System.out.println(y);
System.out.println(z);
6
6
6
What’s the output?
int a=5, b=5, c=5;
a = a + 2;
b++;
b++;
c += 2;
System.out.println(a);
System.out.println(b);
System.out.println(c);
7
7
7
What’s the output?
int i=2, j=2, k=2;
i = i * 2;
j++;
j++;
k *= 2;
System.out.println(i);
System.out.println(j);
System.out.println(k);
4
4
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
{
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
Remember our
program?
What’s next?
• User input
• Text processing
• Output