Kiến trúc máy tính và hợp ngữ - Data types, variables, and arithmetic

To get the correct double result, use double constants or the cast operator: double ratio = 2.0 / 3; double ratio = 2 / 3.0; int m = ., n = .; double factor = (double)m / (double)n; double factor = (double)m / n; double r2 = n / 2.0;

ppt32 trang | Chia sẻ: huyhoang44 | Lượt xem: 778 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Kiến trúc máy tính và hợp ngữ - Data types, variables, and arithmetic, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Data Types, Variables, and Arithmetic int chapter = 6;Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.Java MethodsObject-Oriented Programmingand Data StructuresMaria Litvin ● Gary Litvin2nd AP edition  with GridWorld1Objectives:Discuss primitive data typesLearn how to declare fields and local variablesLearn about arithmetic operators, compound assignment operators, and increment / decrement operatorsDiscuss common mistakes in arithmetic2VariablesA variable is a “named container” that holds a value.q = 100 - q; means:1. Read the current value of q2. Subtract it from 1003. Move the result back into qcount5mov ax,qmov bx,100sub bx,axmov q,bx 3Variables (cont’d)Variables can be of different data types: int, char, double, boolean, etc.Variables can hold objects; then the type is the class of the object.The programmer gives names to variables.Names of variables usually start with a lowercase letter.4Variables (cont’d)A variable must be declared before it can be used: int count; double x, y; JButton go; Bug bob; String firstName; TypeName(s)5Variables (cont’d)The assignment operator = sets the variable’s value:count = 5;x = 0;go = new JButton("Go");firstName = args[0]; 6Variables (cont’d)A variable can be initialized in its declaration:int count = 5;JButton go = new JButton("Go");String firstName = args[0];7Variables: ScopeEach variable has a scope — the area in the source code where it is “visible.”If you use a variable outside its scope, the compiler reports a syntax error.Variables can have the same name when their scopes do not overlap.{ int k = ...; ...}for (int k = ...){ ...}8FieldsFields are declared outside all constructors and methods.Fields are usually grouped together, either at the top or at the bottom of the class.The scope of a field is the whole class.9Fields (cont’d)public class SomeClass{}FieldsConstructors and methodsScopepublic class SomeClass{}FieldsConstructors and methodsScopeOr:10Local VariablesLocal variables are declared inside a constructor or a method.Local variables lose their values and are destroyed once the constructor or the method is exited.The scope of a local variable is from its declaration down to the closing brace of the block in which it is declared.11Local Variables (cont’d)public class SomeClass{ ... public SomeType SomeMethod (...) { { } } ...}ScopeLocal variable declaredLocal variable declared12Variables (cont’d)Use local variables whenever appropriate; never use fields where local variables should be used.Give prominent names to fields, so that they are different from local variables.Use the same name for local variables that are used in similar ways in different methods (for example, x, y for coordinates, count for a counter, i, j, k for indices and loop control variables, etc.).13Variables (cont’d)Common mistakes:public void someMethod (...){ int x = 0; ... int x = 5; // should be: x = 5; ...Variable declared twice within the same scope — syntax error14Variables (cont’d)Common mistakes:private double radius;...public Circle (...) // constructor{ double radius = 5; ...Declares a local variable radius; the value of the field radius remains 0.015Primitive Data TypesintdoublecharbooleanbyteshortlongfloatUsed inJava Methods16StringsString is not a primitive data typeStrings work like any other objects, with two exceptions:Strings in double quotes are recognized as literal constants+ and += concatenate strings (or a string and a number or an object, which is converted into a string)"Catch " + 22 "Catch 22" 17Literal Constants'A', '+', '\n', '\t'-99, 2010, 00.75, -12.3, 8., .5“coin.gif", "1776", "y", "\n"new linetabcharintdoubleString18Symbolic ConstantsSymbolic constants are initialized final variables:private final int sideLength = 8;private static final int BUFFER_SIZE = 1024;public static final int PIXELS_PER_INCH = 6;19Why Symbolic Constants?Easy to change the value throughout the program, if necessaryEasy to change into a variableMore readable, self-documenting codeAdditional data type checking by the compiler20ArithmeticOperators: +, -, /, * , %The precedence of operators and parentheses is the same as in algebram % n means the remainder when m is divided by n (for example, 17 % 5 is 2; 2 % 8 is 2)% has the same rank as / and *Same-rank binary operators are performed in order from left to right21Arithmetic (cont’d)The type of the result is determined by the types of the operands, not their values; this rule applies to all intermediate results in expressions.If one operand is an int and another is a double, the result is a double; if both operands are ints, the result is an int.22Arithmetic (cont’d)Caution: if a and b are ints, then a / b is truncated to an int 17 / 5 gives 3 3 / 4 gives 0even if you assign the result to a double: double ratio = 2 / 3;The double type of the result doesn’t help: ratio still gets the value 0.0.23Arithmetic (cont’d)To get the correct double result, use double constants or the cast operator: double ratio = 2.0 / 3; double ratio = 2 / 3.0; int m = ..., n = ...; double factor = (double)m / (double)n; double factor = (double)m / n; double r2 = n / 2.0; Casts24Arithmetic (cont’d)A cast to int can be useful: int ptsOnDie = (int)(Math.random() * 6) + 1; int miles = (int)(km * 1.61 + 0.5); Returns a doubleConverts kilometers to miles, rounded to the nearest integer25Arithmetic (cont’d)Caution: the range for ints is from -231 to 231-1 (about -2·109 to 2·109)Overflow is not detected by the Java compiler or interpreter:n = 8 10^n = 100000000 n! = 40320n = 9 10^n = 1000000000 n! = 362880n = 10 10^n = 1410065408 n! = 3628800n = 11 10^n = 1215752192 n! = 39916800n = 12 10^n = -727379968 n! = 479001600n = 13 10^n = 1316134912 n! = 1932053504n = 14 10^n = 276447232 n! = 127894528026Arithmetic (cont’d)Compound assignment operators:a = a + b; a += b;a = a - b; a -= b;a = a * b; a *= b;a = a / b; a /= b;a = a % b; a %= b;Increment and decrement operators:a = a + 1; a++;a = a - 1; a--;Do not use these in larger expressions27From Numbers to StringsThe easiest way to convert x into a string is to concatenate x with an empty string: String s = x + "";The same rules apply to System.out.print(x)'A'123-1.13.14Math.PI"A""123""-1""0.1""3.14""3.141592653589793"Empty string28From Objects to StringsThe toString method is called:public class Fraction{ private int num, denom; ... public String toString () { return num + "/" + denom; }}Fraction f = new Fraction (2, 3);System.out. println (f) ;Output: 2/3f.toString() is called automatically29Review:What is a variable? What is the type of a variable that holds an object?What is meant by the scope of a variable?What is the scope of a field?What is the scope of a local variable?30Review (cont’d):Is it OK to give the same name to variables in different methods?Is it OK to give the same name to a field and to a local variable of the same class?What is the range for ints?When is a cast to double used?31Review (cont’d):Given double dF = 68.0; double dC = 5 / 9 * (dF - 32); what is the value of dC?When is a cast to int used?Should compound assignment operators be avoided?32

Các file đính kèm theo tài liệu này:

  • pptch06_8868.ppt
Tài liệu liên quan