41
Anything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great examples Variables – symbolic names to refer to memory locations int number = 142 (stored in memory) Declaring Variables - all variables must be declared before they can be used - declare by reserved words - Ex. data type variable int number; - REMEMBER DATA TYPES FROM INTRO Variable names/naming convention can be any length up to 32 letters name can not be a number o int 100; // ERROR o name must start with a letter or a “_” (underscore) o name could contain a number as long at letters attached int laneNumber2; make variable name meaningful o ex. counter o ex. points 1 142

Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Anything with Variables

Thanks to: Sue Bogar-UMBC for some ideas and great examples

Variables – symbolic names to refer to memory locations

int number = 142 (stored in memory)

Declaring Variables- all variables must be declared before they can be used- declare by reserved words- Ex. data type variable int number; - REMEMBER DATA TYPES FROM INTRO

Variable names/naming convention can be any length up to 32 letters name can not be a number

o int 100; // ERRORo name must start with a letter or a “_” (underscore)o name could contain a number as long at letters attached

int laneNumber2; make variable name meaningful

o ex. countero ex. points

variable names ARE VERY CASE SENSITIVE!!! CAMEL CASE!!

o newValueo studentAverageo setAverageGradeo REQUIRED!!!

1

142

Page 2: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

2

Page 3: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Initializing variables all are instructions “initialize” each variable

o o variable = value;o ints

int a; // NOT COMPLETE!!! int a = 0; // YES

o chars char quit; // NOT COMPLETE!!! char quit = ‘q’; char answer = ‘ ‘; // (EMPTY, and yes a space in between)

Using variables in Expressions set up right to left

c = a + b(ends here) (comes first)

1. Get value for “b” and value for “a”2. Add “a” and “b”3. Assign to “c”

Order of OperationsHighest priority ! ++x --x

* / % (Modulus)+ -< <= > >== = (Identical) ! = (Not Identical)&& (And)

Lowest priority | | (Or) x++ x--

3

Page 4: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Explanation of OperationsSymbol Means Example

! not if(answer != ‘Q’)++ / -- incrementing/decrementing covered later% modulus - remainder covered later+ - / * normal arithmetic symbols< less than 4 < 8 = = True<= less than or equal to 6 <= 6 = = True> greater than 6 > 4 = = True>= greater than or equal to 6 > = 6 = = True= = used to COMPARE – if they are equal if ( answer = = ‘Q’)! = used to COMPARE – if they are NOT equal if(answer != ‘Q’)&& and covered later| | or covered later

Difference between == and == assigns a value == compare 2 value (!=)

Difference between == and !=Lupoli == Person 2 Lupoli != Person 2

Modulus Operations - % a % b = “a mod b”

o *remainder of a/b ex. 31 % 7 = 3 7 √ 31 Used for Leap year problems!!! Why?? has SAME precedence as /!!! Be careful

o what the difference between 2 % 60 / 10 2 % (6 /10)??

4

Page 5: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Using variables (step by step)1. Declare and initialize the value2. Use the variable in some calculation3. Display the Value in a System.out.println()

An Example using Variablespublic static void main(String args[])// HIGHLIGHTS MUST BE DONE IN THIS ORDER!!{ /* Declare variables */ int setInches = 0, setFeet = 0, setFathoms = 0;

float setPressure = 12.23;

/* Assign fathoms the depth of the wreck */ setFathoms = 7;

/* Do conversions into feet or inches */ setFeet = 6 * setFathoms; // what will setFeet equal?? setInches = 12 * setFeet; // what will setInches equal??

/* Print out the depths */ System.out.print(" Its depth at sea: “ + “\n”); System.out.print(" “ + setFathoms + ” fathoms” + “\n”); System.out.print(" “ + setFeet + ” feet” + “\n”); System.out.print(" “ + setInches + ” inches” + “\n”);}

Which way do we go?int x = 3 * 4 / 12; Right to Left OR Left to Right?? (answer = 1)

5

Page 6: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Arithmetic ProblemsCalculation Faux-pas

code calculation (1) assignment (2)int x = 5;int y = 2;

float a = x/y

5 (int) 2 (int) = 2 (int) a = 2

Remember, calculations are done in 2 steps!!!!

Addition/Subtraction, Multiplication ScenariosHIGHEST PRECISION DICTATES FINAL RESULT!!!

int * int = int int * float = float float * int = floatdouble * int = double int * double = double programmer set * float = float

Division scenarios

= int = float = float

= float = int = float

= computer/program BEST setComputer set example weeks = days/7;

THIS PROBLEM WILL BE FIXED BELOW!!Given the following declarations, what is the value of each expression (as the computer would!!)? int a = 2; int b = 4; int c = 6; float f = 5.0; float g = 8.0; 1. a + b - c 2. a + b * c 3. c / b 4. c % b 5. b % c6. g / f 7. g / c 8. 12 / f 9. 4 / 3 * 3.14159 10. 12 - 18 % b / c + a11. (5 + b / c) % 2 12. 5 * 3 % 7 + 8 / 3 - 6 13. (14 + 5) % 5 - 6 / 5.0 14. f / (10 % c) 15. 20 * a + (g - c)

6

Page 7: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

do work here:

7

Page 8: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Arithmetic Problem Solutions

See "explanations" below to see how the answer in red was calculated

1. a + b - c = 0

2. a + b * c = 26

3. c / b = 1

4. c % b = 2

5. b % c = 4

6. g / f = 1.6

7. g / c = 1.33333

8. 12 / f = 2.4

9. 4 / 3 * 3.14159 = 3.14159

10. 12 - 18 % b / c + a = 14

11. (5 + b / c) % 2 = 1

12. 5 * 3 % 7 + 8 / 3 - 6 = -3

13. (14 + 5) % 5 - 6 / 5.0 = 2.8

14. f / (10 % c) = 1.25

15. 20 * a + (g - c) = 42.0

Problem ExplanationsExplanation of Problem 1

a + b - c is equivalent to 2 + 4 - 6. Since + and - have the same level of precedence, we perform them from left to right.2 + 4 - 6 = 6 - 6 = 0

Explanation of Problem 2

By the rules of operator precedence, multiplication is performed before addition, so 2 + 4 * 6 = 2 + (4 * 6) = 2 + 24 = 26

Explanation of Problem 3

c / b is an example of "integer division". Do the division, but ignore the remainder. In this case, 6 / 4 = 1 1/2, but throw away the 1/2 and the result is 1.

Explanation of Problem 4

The result from of mod operator (%) is the remainder after dividing.6 / 4 = 1 with remainder of 2, so the value of 6 % 4 is 2.

8

Page 9: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Explanation of Problem 5

The result from of mod operator (%) is the remainder after dividing. 4 / 6 = 0 with remainder of 4, so the value of 4 % 6 is 4.

Explanation of Problem 6

g / f is equivalent to 8.0 / 5.0. Since both operands are floating point variables, the result is a floating point variable. 8.0 / 5.0 = 1.6

Explanation of Problem 7

g / c is equivalent to 8.0 / 6. Since one of the operands is floating point and one is an integer, the integer is changed to floating point and the result is floating point.... so 8.0 / 6 becomes 8.0 / 6.0 = 1.33333

Explanation of Problem 8

12 / f is equivalent to 12 / 5.0. Once again, since one of the operands is floating point and one is an integer, the integer is changed to floating point and the result is floating point.... 12 / 5.0 = 12.0 / 5.0 = 2.4

Explanation of Problem 9

Since division (/) and multiplication (*) have the same precedence, the operations are performed from left to right.Since 4 and 3 are both integers, 4 / 3 is integer division and the result is 1. Then 1 * 3.14159 is an integer times a floating point so the result is floating point 3.14159.

Explanation of Problem 10

12 - 18 % b / c + a is equivalent to 12 - 18 % 4 / 6 + 2Since % and / have higher precedence than - and +, they are performed first, from left to right.First 18 % 4 is the remainder after dividing so 18 % 4 = 2. So we now have 12 - 2 / 6 + 2. Since 2 and 6 are integers, integer division id performed and 2 /6 = 0, which simplifies the problem to 12 - 0 + 2 = 14.

Explanation of Problem 11

(5 + b / c) % 2 is equivalent to (5 + 4 / 6) % 2.Starting inside the parenthesis, we first perform the integer division 4 / 6, which is 0. Since 5 + 0 = 5, the problem simplifies to 5 % 2. The % operator is the remainder after division. 5 / 2 is 2 with remainder of 1, so 5 % 2 = 1.

Remember that doing x % 2 tells us if x is odd or even. If x is odd, the result is 1. If x is even the result is 0.

Explanation of Problem 129

Page 10: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

5 * 3 % 7 + 8 / 3 - 6Since there are no parenthesis, and /, * and % have higher precedence than + and -, let's put parenthesis to indicate the order of operations:( (5 * 3) % 7) + (8 / 3) - 6In the first set of parenthesis, 5 * 3 = 15 and then 15 % 7 = 1.In the second set of parenthesis, 8 / 3 = 2 (integer division).So the problem reduces to 1 + 2 - 6 = -3.

Explanation of Problem 13

(14 + 5) % 5 - 6 / 5.0Parenthesis first, so 14 + 5 = 19, yielding 19 % 5 - 6 / 5.0% and / have higher precedence than -, so first 19 % 5 = 4.Second, 6 / 5.0 is mixed division (integer and floating point), so it becomes all floating point, so 6.0 / 5.0 = 1.2.Our problem has reduced to 4 - 1.2 which is 2.8

Explanation of Problem 14

f / (10 % c) is equivalent to 5.0 / (10 % 6)Inside the parenthesis, 10 % 6 = 4. Then 5.0 / 4 is mixed division (integer and float), so it becomes all float andthe result is of type float..... 5.0 / 4.0 = 1.25

Explanation of Problem 15

20 * a + (g - c) is equivalent to 20 * 2 + (8.0 - 6)Inside the parenthesis, 8.0 - 6 becomes 8.0 - 6.0 which is 2.0Our problem is then 20 * 2 + 2.0Since * is higher precedence than +, we first multiply, then add.20 * 2 = 40.... 40 + 2.0 = 42.0

10

Page 11: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Casting/static-casting- converts value, from one data type to another- fixes problem of above

Calculation Faux-pascode calculation (1) assignment (2)

int x = 5;int y = 2;

double a = x/y;

5 (int) 2 (int) = 2 (int) a = 2

Calculation Fix using Castingcode calculation (1) answer

int x = 5;int y = 2;

double a = (double) x / y;ORdouble a = x / (double) y;

x (double) y (int) = 2.5

OR

x (int) y (double) = 2.5

// given from Division scenarios

a = 2.5

Incrementing and Decrementing ++ = add 1 -- = subtract 1 the position of the ++/-- determines WHEN to increment/decrement value STICKS afterwards

Shortcut For

a++ a = a + 1 after calculation is donea-- a = a – 1++a a = a + 1 before calculation is done--a a = a –1

ex. for(int b = 0; b < 5; b++)

11

Page 12: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Incrementing– What does AFTER mean??

Example 1 Example 2int a = 9, b = 6, c = 0, d;

c = a++ - --b;d = a + b--;

System.out.print( a + “\n”); // answer:System.out.print( b + “\n”); // answer:System.out.print( c + “\n”); // answer:System.out.print( d + “\n”); // answer:

int a = 9, b = 6, c = 0, d;

c = ++a – b--;d = a + b--;

System.out.print( a + “\n”); // answer:System.out.print( b + “\n”); // answer:System.out.print( c + “\n”); // answer:System.out.print( d + “\n”); // answer:

Compound Assignment OperatorsC's Shorthand Assignment Operatorsoperator shorthand equivalent

+= X += Y Xnew = Xold + (Y)

-= X -= Y X = X – (Y)

*= X *= Y X = X * (Y)

/= X /= Y X = X / (Y)

%= X %= Y X = X % (Y)

(Y) = denotes PRESIDENCE!!

int x = 10;int y = 15;int z = 6;int a, b, c;

z *= x-- + 5;

// z = z * (x-- + 5);

// Thank you Bob Ayella for the exampleint setLupoliIsDaMan = 10, setLupoliIQ = 210, setLupoliWeight = 210;setLupoliIsDaMan = setLupoliIsDaMan + setLupoliIQ;

OR

setLupoliIsDaMan += setLupoliIQ; // just less typingsum += total; // another example

12

Page 14: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Assignment Operator Problem SolutionsSee "explanations" below to see how the answer in red was calculated

1. x++; yields x = 11

2. --y; yields y = 14

3. a = ++z - 5; yields a = 2 and z = 7

4. b = 16 - y++; yields b = 1 and y = 16

5. c = ++x + z--; yields x = 11, z = 5 and c = 17

6. x += 2 * y yields x = 40

7. y -= x / --z; yields y = 13 and z = 5

8. z += x-- + 5; yields x = 9 and z = 21

9. y /= z + 2; yields y = 1

10. x * = ++y – z--; yields x = 100, y = 16 and z = 5

Problem Explanationsx++;

x++ is an example of post-increment. If x++ appears in an expression, we would use the current value of x in the expression, and then increment x afterwards. The same would be true in the case of post-decrement. In this case, however, there is no expression, so we simply increment x from 10 to 11. Used this way, x++; and ++x; are equivalent.

--y:

--y; is an example of pre-decrement. If --y appears in an expression, we would first decrement y and use the new value of y in the expression. The same would be true in the case of pre-increment. In this case, however, there is no expression to evaluate, so we simply decrement y from 15 to 14. Used this way, --y; and y--; are equivalent.

a = ++z - 5;

First, look at the expression on the right for any pre-increment and/or pre-decrement operators and perform them first. In this case, ++z is a pre-increment, so we increment z from 6 to 7. We then evaluate the expression... 7 - 5 is 2, which gets stored in a.

14

Explanation of Problem 1

Explanation of Problem 2

Explanation of Problem 3

Explanation of Problem 4

Page 15: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

b = 16 - y++;

Since the expression on the right has no pre-increment or pre-decrement operators, we use the current value of y to evaluate the expression. 16 - 15 = 1. So 1 is stored in b, then y is incremented from 15 to 16.

c = ++x + z--;

Since ++x is pre-increment, we first increment x from 10 to 11 and use that value in the expression. Since z-- is post-decrement, we use the current value of z (which is 6) in the expression, then decrement z from 6 to 5. So the steps are:

1. increment x from 10 to 11 2. evaluate 11 + 6, which is 17 and store in c 3. decrement z from 6 to 5

x += 2 * y;

x += 2 * y; is equivalent to x = x + (2 * y);Since y = 15, x = 10 + (2 * 15) = 10 + 30 = 40

y -= x / --z;

We need to evaluate x / --z, then subtract that answer from y to get the new value of y. We know that "--" is the decrement operator, but we must pay attention to whether it's used as pre-decrement or post-decrement. In this case --z is pre-decrement, so we decrement z from 6 to 5 first, then we use the new value of z and evaluate x / 5. Since x is 10, x / 5 = 10 / 5 = 2. Finally, y -= 2; is equivalent to y = y - 2; so y = 15 - 2 which is 13.

z += x-- + 5;

We first need to evaluate x-- + 5, then add that value to zThe fundamental question is whether we decrement x before (pre-decrement) or after (post-decrement) we use x's value in the calculation.In this case, x-- is post-decrement, so we calculate x-- + 5 as 10 + 5 which is 15 then we decrement x from 10 to 9. Finally, z += 15 is equivalent to z = z + 15. Since z is currently 6, we get z = 6 + 15 which is 21.

15

Explanation of Problem 5

Explanation of Problem 6

Explanation of Problem 7

Explanation of Problem 8

Page 16: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

y /= z + 2;

This is one of the simpler problems, but reminds us about integer division.Since z is 6, z + 2 = 8. y /= 8 is equivalent to y = y / 8. Since the value of y is currently 15, this becomes y = 15 / 8, which is 1 because we are doing integer division.

x *= ++y - z--;

In order to evaluate ++y - z--, we must decide which values of y and z to use..... do we use the current values, or do we increment (decrement) first and use the new values. In this problem it's both. Because ++y is pre-increment, we first increment y from 15 to 16. Next look at z--. This is post-increment, so we use the current value of z, which is 6, then decrement z. So the steps are:

1. increment y from 15 to 16 2. use the current value of z (which is 6) and calculate 16 - 6 = 10 as the value of the expression 3. calculate x *= 10 which is equivalent to x = x * 10. Since x is currently 10, this evaluates to x = 10 * 10

which is 100 4. now decrement z from 6 to 5

16

Explanation of Problem 9

Explanation of Problem 10

Page 17: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Variable Constants done by programmer usually in GLOBAL SECTION will NEVER CHANGE!!! usually an important variable used thru-out the program makes hamburger 1.19 and nothing will change it!! good if used a lot if you need to change it you know where to go!

Variable Const Example

Notice the errors!! (18 & 21)

17

Page 18: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Big Picture: what to watch for remember that order of your code matters completed from top to bottom in a linear fashion

static Scanner sc = new Scanner(System.in);

public static void main(String args[]){

int game1 = 0; int game2 = 0; int game3 = 0;

int total = game1 + game2 + game3;

System.out.print( “Enter your three scores?” + “\n”);game1 = sc.nextInt();game2 = sc.nextInt();game3 = sc.nextInt();

System.out.print( “Your total was: “ + total + “\n”);}// Why will this program ONLY print 0 for total when run?Hint: Remember a program is completed linearly, from top to bottom

18

Page 19: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Characters as variablesCharacters are SINGLE letter variables that have several special features:

Character variable functionschar letter = Character.toUpperCase(getLetter) Will uppercase any letter passed in

works for strings (words)

char letter = Character.toLowerCase(‘Z’); opposite as above

boolean answer = Character.isUpperCase(‘a’); will return a TRUE or FALSE answer if value passed in is UPPER or LOWER

boolean answer = Character.isLowerCase(‘a’); opposite as above

boolean answer = Character.isWhiteSpace(‘a’); will return a TRUE or FALSE answer if value passed in is a “White space” (just a space)

boolean answer = Character.isLetter(‘a’); same as above just determines if an actual letter of the alphabet

boolean answer = Character.isDigit(‘7’); same as above just determines if an actual digit

What value will isDigit return?

Some basics on Strings Strings can be ONE or more characters of text strung together

o “c” is a stringo “Mr. Lupoli stinks” is a stringo “123-213-1232” is a stringo “123123123” is a string

A character data type cannot be a String To create a string

o notice when using Strings “” are usedo CHARACTERS use ‘ ’, you cannot use “”

String professor = “Lupoli”;String two = professor; // equals is not just used for math

19

Page 20: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Comparing strings CANNOT USE <, >, !=, ==, etc…

Values compareTo( ) returnsString x = “cat”;String y = “dog”;x.compareTo(y);returns when< 0 string1 alphabetically/ASCII before string2 cat dog0 string1 alphabetically/ASCII INDENTICAL string2 cat cat> 0 string1 alphabetically/ASCII” after string2 dog cat

Values equals( ) returnsString x = “cat”;String y = “dog”;if( x.equals(y) ) // usually inside an IF statementif( x.equals(“Lupoli”))returns when0 (false) string1 alphabetically/ASCII NOT IDENTICAL string21 (true) string1 alphabetically/ASCII IDENTICAL string2

A < Z < a < z

String comparing exerciseString 1 (x) String 2 (y) comparison Answer (t, f,<0, >0, 0)cat dog x.equals(y) falseLupoli Luppold x.compareTo(y)Zach Emily x.compareTo(y)Eric Eric x.compareTo(y)Mandy MANDY x.equals(y)

20

Page 21: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Math functions using variables Import java.lang.Math

Square Rootint x = Math.sqrt(4);

Maximum and Minimum (of 2 values)int y = Math.max(10,100); // int y = Math.max(a,b);int a = 10;int b = 100;

int y = Math.min(a,b);

Absolute Valueint z = Math.abs(-1001); // z = 1001int a = Math.abs(117); // z = 117

21

Page 22: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

All of the wonderful Math functions it has!!

Introduction to Output Formatting Most of us are used to using System.out.println to display the data Using “printf” can display AND format the output Printf is a OLD C command used to display

o Literally the same syntax! A “placeholder” is used to determine the exact output of the variable

22

Page 23: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Placeholder A placeholder is used WITHIN the string of text you wish to be displayed that

place holder will display the value given a certain format

Notice %i is not used!! (%i is used for int in C)

Printf Exampleint grade1 = 80;char grade2 = ‘B’;String grade3 = “Passing”;

System.out.printf(“Lupoli received a %d, or %c, or %s”, grade1, grade2, grade3);

// answer displayed is Lupoli received a 80, or B, or Passing// those in red are the place holders// those in green are the actual variablesNotice that order or variables are important!

23

Placeholder

Variable Type

%c char%d int%f double%s String

Page 24: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Placeholder “flags” %c, %d, is NOT the full extent the placeholder have flags that will change the format of the output \n will be needed to end the line

Placeholder Variable Type%c char%d int%f double%s String

printf() flagsDoes Ex.

minimum field width %4dsets decimal precision only for double variable type. %.4fleft justifies a string by a # of spaces %-20sadd +/- symbols to values %+fPositive values are given a blank space in front.Negative values with a “-“.

% f

You can combine symbols!!! Look below!!Coded Example of Placeholders and Flags

final double grade = 3.66666666;

// regular displaySystem.out.println("grade is equal to " + grade);

// just using printfSystem.out.printf("grade is equal to %f \n" , grade);

// format to show 2 decimal placesSystem.out.printf("grade is equal to %.2f \n" , grade);

24

Page 25: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Planning an output layout begin with a variables that you know you will need to layout differently

Layout gasoline price at register

(float) gasPerGallon = 3.999999

1. Pick the correct data type for variable

%c char%d int%f float/double (Eclipse likes double)%s String

2. (Optional) Pick the width for your output. Will automatically right align.

%8f _ _ _ . _ _ _ _%f 3.999999 (left aligned)%12f _ _ _ _ _ _ _ . _ _ _ _

# testing the width…printf(“:%8f:” ,gasPerGallon)…printf(“:%f:” ,gasPerGallon)…printf(“:%12f:” ,gasPerGallon)

*notice the “.” Counts!!*if the width of the value is larger than the number, then width is ignored

3. (Optional) Pick the precision.

%.2f _ _ _ _ . _ _%f 3.999999%.6f _ _ _ _ . _ _ _ _ _ _

# testing the precision…printf(“:%.2f:” ,gasPerGallon)…printf(“:%f:” ,gasPerGallon)…printf(“:%.6f:” ,gasPerGallon)

4. (Optional) Pick a sign? (+/-)

%+f + 3.999999%f 3.999999

# testing the sign (+/)…printf(“:%+f:” ,gasPerGallon)…printf(“:%f:” ,gasPerGallon)

* + will do BOTH + and – signs

25

Page 26: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

5. print the value

System.out.printf(“:%4d: \n” ,a )System.out.printf(“:%f: \n” ,b )System.out.printf(“:%9.6f: \n” ,b )

Give an example of a value that would fit %9.6f. Please use just 1’s in the digit so we can all have the same answer.

printf() flag coded examplesint a = 5;float b = 5.3235743876;String c = “hi”;

System.out.println("========================");System.out.printf(“:%4d: \n", a); System.out.printf(“:%4.4f: \n", b);System.out.printf(“%-20s :\n", c); // 20 spacesSystem.out.printf(“:%+6.2f: \n", b);System.out.printf(“:% 6.2f: \n", b);System.out.println("========================");

========================: 5::5.3235:hi :: +5.32:: 5.32:========================

26

Page 27: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

Decimal Formatting much easier to work with is simple decimal formatting than above must import java.text.DecimalFormat can add these to values

o how many decimal places to displayo commas, $o many more

Playing with Decimal FormattingCode Results

double gasPrice = 2.299;int mySalary = 123456;

System.out.println("Here is what the values print normally:");System.out.println("gasPrice -> " + gasPrice);System.out.println("mySalary -> " + mySalary);

DecimalFormat bigOilPriceForGas = new DecimalFormat(".###");DecimalFormat WhatWeSeeForGas = new DecimalFormat(".##");

DecimalFormat WhatIGet = new DecimalFormat("00,000.00");DecimalFormat WhatMyWifeGets = new DecimalFormat("###,###,###.##");DecimalFormat WhatMyKidsGet = new DecimalFormat("$###,###,###.00");

System.out.println("\nResults of Decimal Formatting:");System.out.println("bigOilPriceForGas -> " + bigOilPriceForGas.format(gasPrice));System.out.println("WhatWeSeeForGas -> " + WhatWeSeeForGas.format(gasPrice));

System.out.println("WhatIGet -> " + WhatIGet.format(mySalary));System.out.println("WhatMyWifeGets -> " + WhatMyWifeGets.format(mySalary));System.out.println("WhatMyKidsGet -> " + WhatMyKidsGet.format(mySalary));

Here is what the values print normally:gasPrice -> 2.299mySalary -> 123456

Results of Decimal Formatting:bigOilPriceForGas -> 2.299WhatWeSeeForGas -> 2.3WhatIGet -> 123,456.00WhatMyWifeGets -> 123,456WhatMyKidsGet -> $123,456.00

27

Page 28: Anything with Variables - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/VariableNotes.… · Web viewAnything with Variables Thanks to: Sue Bogar-UMBC for some ideas and great

FYI SectionInfinity as a valueDouble.POSITIVE_INFINITY

28