Chapter 3. Numerical Data Reference: Chapter 3, and powerpoint presentation from publisher. Objectives of this chapter: - Understand the type of numerical data - Difference between primitive data (variable) and object - Understand arithmetic expressions (operations due to different types) - Get to know math class, GregorianCalendar class, DecimalFormat class, input and output with System.in and System.out Note also: - Program is read from top to bottom, and left to right…we need to behave like a Java compiler - There can be some “differences” in running a program in DrJava vs in a Command Prompt – Command Prompt is used by our courseMarker. - By now, it should be clear to you that we are wrapping around with (passing to) method to perform some task that we don’t want (or don’t know how) to do. I. Introduction Major challenge: “=” is actually assignment rather than equality. II. Types of primitive data values II.1. Variable has three properties: - A memory location to store the value - The type of data stored in the memory location, and - The name used to refer to the memory location Six numerical data types: byte, short, int, long, float, and double. II.2. Constant: If we want the value to remain the same, we use a constant. final double PI = 3.14159 final int MONTH_IN_YEAR = 12; The constant PI is called a named constant or symbolic constant. The second type of constant is called a literal constant – the actual value. What is the type of literal constant 345.79? It is double. So, the following will create compilation error: float number; number = 345.79; This is because the variable (float) has lower precision than that of the constant (double). To correct this error, we have to write the assignment statement as: number = (float) 345.79; or number = 345.79f; final double SPEED_OF_LIGHT = 3.0E+10D (literal constant suffixed by f, F, d or D). CS1101Z 1 of 4 II.3. Primitive vs Reference Numerical data are called primitive data types Objects are called reference data types, because the contents are addresses that refer to memory locations where the objects are actually store. III. Arithmetic Expressions Assignment statement, precedence rules, (implicit and explicit) type casting. To input a numerical value, we have to first input a String object and then convert it to a numerical representation. We call such operation a type conversion. To perform the necessary type conversion in Java, we use different utility classes called wrapper classes. The name wrapper derives from the fact that these classes surround, or wrap, primitive data with useful methods. int num = Integer.parseInt(“14”); String str = JOptionPane.showInputDialog(null, “Enter age:”); int age = Integer.parseInt(str); String radiusStr = JOptionPane.showInputDialog(null, “Enter radius:”); double radius = Double.parseDouble(radiusStr); IV. Useful Classes Useful classes: System.out System.in (use it together with Scannar) Scanner (import java.util.*) DecimalFormat (import java.text.*) Math class (import java.lang.*) GregorianCalender (import java.util.*) See/Demo of examples come with your textbook: - Ch3Circle.java (page 99) ….use Integer.parseInt(str) - Ch3Circle3.java (page 105) ….use DecimalFormat - Ch3Circle4.java (page 112) ….use Scanner - Ch3PoleHeight (page 116) ….use Math class - Ch3SelectWinner (page 118) ….use Math.random() - Ch3TestCalendar (page 121) ….use GregorianCalendar() IV.1. System.out, System.in and Scanner System.out refers to a precreated PrintStream object we use to output multiple lines of text to the standard output window. The actual appearance of the standard output window depends on which Java tool we use. e.g. System.out.print(“x + x =” + ans); System.out.println(“”); System.out.println( “x + x =” + ans); Analogous to System.out for output, we have System.in for input. We call the technique to input data using System.in standard input. We also use the term console input to refer to standard input. Using System.in for input is slightly more complicated than using System.out for output. System.in is an instance of the InputStream class that provides only a facility to input 1 byte at a time with its read method. CS1101Z 2 of 4 However, multiple bytes are required to represent a primitive data type or a string (for example, 4 bytes is used to store an int value). So to input primitive data values or strings easily, we need an input facility to process multiple bytes as a single unit. The most common way of using System.in for input is to associate a Scanner object to the System.in object. A Scanner object will allow us to read primitive data type values and strings. First we create a new Scanner object by passing System.in as an argument: Import java.util.*; Scanner scanner; scanner = new Scanner (System.in); Once we have a Scanner object, then we can call its nextInt method to input an int. int age; Age = scanner.nextInt(); Or other types of numeric data, such as: double dNum1; dNum1 = scanner.nextDouble(); Note that reading a string input is slightly more complicated than reading numerical data. Compare the following: System.out.print (“Enter your name: “); name = scanner.next(); The above does not get all the words in a name. To remedy the problem, Scanner scanner = new Scanner (System.in); String lineSeparator = System.getProperty(“line.separator”); Scanner.useDelimiter(lineSeparator); System.out.print(“Enter your name: “); String name = scanner.next(); Note: the above does not quite work out in DrJava but in the Command Prompt. For DrJava, you need the following note: Scanner scanner = new Scanner ( System.in); Scanner.useDelimiter (“\n”); System.out.print (“Enter your name:”); String name = scanner.next(); You can achieve the same with scanner.nextLine ( ) if you do not want to use the delimiter. Read up the Java API documentation to know more. IV.2. DecimalFormat Import java.text.*; DecimalFormat df = new DecimalFormat(“0.000”); double radius = 0.123456; System.out.println(“Radius : “ + df.format(radius)) ; IV.3. Math Class doube alpha = 10.0; // angle doube alphaRad = Math.toRadians(alpha); double height = Math.sqrt(Math.sin(alphaRad)); // select the winner int min = startingNumber + 1; int max = startingNumber + count; winningNumber = (int)(Math.floor(math.random() * (max – min +1)) + min); System.out.println(“The Winning Number is “ + winningNumber); CS1101Z 3 of 4 IV.4. GregorianCalendar Class Import java.util.*; e.g. GregorianCalendar cal = new GregorianCalendar(); System.out.println(cal.getTime()); System.out.println(“ “); System.out.println(“Year: “ + cal.get(Calendar.YEAR)); // Calendar.YEAR is a class constant System.out.println(“MONTH: “ + cal.get(Calendar.MONTH)); // .MONTH is a class constant System.out.println(“DATE: “ + cal.get(Calendar.DATE)); // .DATE is a class constant System.out.println(“MINUTE: “ + cal.get(Calendar.MINUTE)); e.g. GregorianCalendar independenceDay = new GregorianCalendar(1965, Calendar.AUGUST, 9); SimpleDateFormat sdf = new SimpleDateFormat(“EEEE”); JOptionPane.showMessageDialog(null, “Our independence day was on “ + sdf.format(independenceDay.getTime())); V. Sample Development Problem statement: Write a loan calculator program that computes both monthly and total payments for a given loan amount, annual interest rate, and loan period. Objects consideration – design – code – test Objects consideration: JOptionPane, System.out, Math classes. One way of design: input, process, output. Monthly payment = L R 1 1 1 R N where L is the loan amount, R is the monthly interest rate, and N is the number of payments. The monthly rate R is expressed in a fractional value, for example, 0.01 for 1 percent monthly rate. We do incremental coding for input, output, and then process. In this approach, we test besides coding as we go along. Also, at the end of this, we may need to do a more comprehensive understanding of monthly payment, total payment….(number of significant digits etc.) CS1101Z 4 of 4