Principles f Cmputer Science Intrductin (Part II) Yanyan Zhuang Department f Cmputer Science http://www.cs.uccs.edu/~yzhuang UC. Clrad Springs
Review Terminlgy Class } Every Java prgram must have at least 1 class (same name as Java file) Methd } Java prgrams cntains a special methd called main public static vid main (String[] args) {..} The main methd is where a Java prgram starts executin Statements } Statements represent actins } Statements must end with a ; UC. Clrad Springs
Review Terminlgy Reserved wrds (keywrds) } Wrds that have specific meaning/cannt be used fr ther purpses } public, class, byte, int, lng, flat, duble, Blcks } Class blck and methd blck, using {} Cmments } // This is a line f cmment } /* This cmment can span acrss several lines */ UC. Clrad Springs
Review Identifier A name chsen by the prgrammer fr: classes, methds, variables, and cnstants Can start with letter, _ r $ (_ and $ are nt used much) UC. Clrad Springs
Overview Numerical Data Types Variables and cnstants Packages Data frmatting Data casting UC. Clrad Springs
Numerical Data Types Name Range Strage Size byte 2 7 t 2 7 1 (-128 t 127) 8-bit signed shrt 2 15 t 2 15 1 (-32768 t 32767) 16-bit signed int 2 31 t 2 31 1 (-2147483648 t 2147483647) 32-bit signed lng 2 63 t 2 63 1 64-bit signed (i.e., -9223372036854775808 t 9223372036854775807) flat Negative range: 32-bit flating pint -3.4028235E+38 t -1.4E-45 Psitive range: 1.4E-45 t 3.4028235E+38 duble Negative range: 64-bit flating pint -1.7976931348623157E+308 t -4.9E-324 Reading fr primitive data types: Psitive range: 4.9E-324 t 1.7976931348623157E+308 https://dcs.racle.cm/javase/tutrial/java/nutsandblts/datatypes.html UC. Clrad Springs
Numeric Operatrs Name Meaning Example Result + Additin 34 + 1 35 - Subtractin 34.0 0.1 33.9 * Multiplicatin 300 * 30 9000 / Divisin 1.0 / 2.0 0.5 % Remainder 20 % 3 2 UC. Clrad Springs
Integer Divisin +, -, *, /, and % 5 / 2 yields an integer 2 5.0 / 2 yields a duble value 2.5 5 % 2 yields 1 (the remainder f the divisin) ften called mdularperatin UC. Clrad Springs
Remainder Operatr % Remainder is very useful in prgramming Fr example, an even number % 2 is always 0 and an dd number % 2 is always 1 S yu can use this prperty t determine whether a number is even r dd Example: CmputeExpressin.java System.ut.println() prints nly strings, but cnverts number t string t print UC. Clrad Springs
Java Identifiers An identifier Rule } A sequence f characters that cnsist f letters, digits, underscres (_), and dllar signs ($), NO SPACES } Must start with a letter, _ r $, CANNOT start with a digit } CANNOT be a reserved wrd, true, false, r null } Can be f any length Example } Class/methd/variable/cnstant name (can refer by name later) Cnventin } Class names start with an upper case letter, variable/methd names start with a lwer case letter, cnstants all caps UC. Clrad Springs
Variables and Cnstants Variable Used t stre a value that may change E.g., duble length; length = 3.5; //length can change duble length = 3.5; // an (almst) equivalent way as abve Hw t use: Declare à assign a value à d smething t it } A variable can nly be declared nce } A variable must have a value (be initialized) befre we use it } Can mdify their value, display their value, use them in frmulas } Example: Arithmetic.java (hw t declare/use variables) UC. Clrad Springs
Variables and Cnstants Cnstant Used t stre a value that will NEVER change Cnstants fllw certain rules } Must have a name (a meaningful name, like variables) With all uppercase letters (Java cnventin) } Declared using the keywrd final Example: final duble PI = 3.14159; UC. Clrad Springs
Write pseudcde Nt real cde, but help rganize prgram lgic Can use a mix f prgramming language + natural language Example: Calculate the area f a circle (Circle.java) Input: radius Output: area f the circle area = pi * radius * radius Print area Als see Rectangle.java UC. Clrad Springs
Reading Input frm the Cnsle 1. Create a Scanner bject Scanner keybard = new Scanner(System.in); 2. Use the methd nextduble() t btain t a duble value. Fr example, System.ut.print("Enter a duble value:"); duble d = keybard.nextduble(); 3. After finishing the Scanner bject, clse it keybard.clse(); UC. Clrad Springs
Reading Input frm the Cnsle Scanner keybard = new Scanner(System.in); int value = keybard.nextint(); Example: Average.java, CmputeArea1.java, CmputeArea2.java Methd nextbyte() nextshrt() nextint() nextlng() nextflat() Descriptin reads an integer f the byte type. reads an integer f the shrt type. reads an integer f the int type. reads an integer f the lng type. reads a number f the flat type. nextduble() reads a number f the duble type. UC. Clrad Springs
Packages A bunch f related classes gruped tgether Mechanism fr rganizing Java classes Java cntains many predefined packages T access class/methd in a predefined package use imprt imprt java.util.scanner; UC. Clrad Springs
Packages T create yur wn package File (with prject selected) à New à Package First line in yur Java class: package yur_package_name Cnventin: package name lwer case Structure A prject cntains package(s) A package cntains Java file(s) A Java file cntains class(es) UC. Clrad Springs
Let s Practice! Please write a prgram CmputeRadius.java: input the area f a circle, calculate its radius Write pseudcde t guide yur lgic Use cnstant PI Use Scanner t get input value area (a duble variable) Print the value f the radius } radius = the square rt f (area/pi) } Hw t d square rt? Math.sqrt(area/PI) yu will use this in a hmewrk questin UC. Clrad Springs
Prblem: Cnverting Temperatures Write a prgram that cnverts a Fahrenheit degree (read frm keybard) t Celsius using the frmula: celsius 5 = ( 9 )( fahrenheit - 32) Print the resulting Celsius with tw decimal pints. 19
Cnverting Temperatures Pseudcde Input? Output? Hw t calculate Celsius given a Fahrenheit value? celsius 5 = ( 9 )( fahrenheit - 32) Nte: yu have t write celsius = (5.0 / 9) * (fahrenheit 32) Hw t print the result using tw decimal pints? } Data frmatting UC. Clrad Springs
Frmatting decimal utput Use DecimalFrmat class imprt java.text.decimalfrmat; DecimalFrmat df = new DecimalFrmat("000.##"); System.ut.println(df.frmat(celsius)); 0: a digit #: a digit, zer shws as absent } 72.5 is shwn as 072.5 } 21.6666.. is shwn as 021.67 Mre infrmatin https://dcs.racle.cm/javase/tutrial/i18n/frmat/decimalfrmat.html UC. Clrad Springs
Frmatting decimal utput Use System.ut.frmat System.ut.frmat("the %s jumped ver the %s, %d times", "cw", "mn", 2); } the cw jumped ver the mn, 2 times System.ut.frmat("%.1f", 10.3456); } 10.3 // ne decimal pint System.ut.frmat("%.2f", 10.3456); } 10.35 // tw decimal pints System.ut.frmat("%8.2f", 10.3456); } 10.35 // Eight-wide, twdecimal pints UC. Clrad Springs
Let s Practice! Please write a prgram: given the radius f a circle, calculate its perimeter, and print the result with 4 decimal pints Write pseudcde t guide yur lgic Use cnstant PI Use Scanner t get input value radius Print the value f the perimeter UC. Clrad Springs
Data Casting When yu explicitly tell Java t cnvert a variable frm ne data type t anther type Think f data types as cups f different sizes } Can put the cntents f a smaller variable (cup) int a larger variable (cup) } Cannt put the cntents frm a larger variable (cup) int a smaller variable (cup), withut lsing infrmatin } Cheat sheet: int (32 bits), lng (64 bits), flat (32 bits), duble (64 bits) UC. Clrad Springs
Cnversin Rules When perfrming a binary peratin invlving tw perands f different types, Java autmatically cnverts the perand based n the fllwing rules: 1. If ne f the perands is duble, the ther is cnverted int duble. 2. Otherwise, if ne f the perands is flat, the ther is cnverted int flat. 3. Otherwise, if ne f the perands is lng, the ther is cnverted int lng. 4. Otherwise, bth perands are cnverted int int. 25