Math methods. Lecture Seven Math methods. GUI review Interest Calculator. Read Chapter 5, pg. 115



Similar documents
public class Craps extends JFrame implements ActionListener { final int WON = 0,LOST =1, CONTINUE = 2;

Programming with Java GUI components

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

CS 335 Lecture 06 Java Programming GUI and Swing

// Correntista. //Conta Corrente. package Banco; public class Correntista { String nome, sobrenome; int cpf;

Homework/Program #5 Solutions

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

Graphical User Interfaces

The Method of Partial Fractions Math 121 Calculus II Spring 2015

How To Build A Swing Program In Java.Java.Netbeans.Netcode.Com (For Windows) (For Linux) (Java) (Javax) (Windows) (Powerpoint) (Netbeans) (Sun) (

Week 13 Trigonometric Form of Complex Numbers

Advanced Network Programming Lab using Java. Angelos Stavrou

Extending Desktop Applications to the Web


Lab 1A. Create a simple Java application using JBuilder. Part 1: make the simplest Java application Hello World 1. Start Jbuilder. 2.

Callbacks. Callbacks Copyright 2007 by Ken Slonneger 1

5.3 SOLVING TRIGONOMETRIC EQUATIONS. Copyright Cengage Learning. All rights reserved.

Using A Frame for Output

CS170 Lab 11 Abstract Data Types & Objects

Unit 1 Number Sense. In this unit, students will study repeating decimals, percents, fractions, decimals, and proportions.

Session 7 Fractions and Decimals

SAT Math Facts & Formulas Review Quiz

public class demo1swing extends JFrame implements ActionListener{

MATH Fundamental Mathematics IV

Review of Fundamental Mathematics

Tom wants to find two real numbers, a and b, that have a sum of 10 and have a product of 10. He makes this table.

Math 10C. Course: Polynomial Products and Factors. Unit of Study: Step 1: Identify the Outcomes to Address. Guiding Questions:

Math 115 Spring 2011 Written Homework 5 Solutions

4. How many integers between 2004 and 4002 are perfect squares?

x 2 + y 2 = 1 y 1 = x 2 + 2x y = x 2 + 2x + 1

PYTHAGOREAN TRIPLES KEITH CONRAD

Java GUI Programming. Building the GUI for the Microsoft Windows Calculator Lecture 2. Des Traynor 2005

THE COMPLEX EXPONENTIAL FUNCTION

Algebra. Exponents. Absolute Value. Simplify each of the following as much as possible. 2x y x + y y. xxx 3. x x x xx x. 1. Evaluate 5 and 123

Vieta s Formulas and the Identity Theorem

Binary Adders: Half Adders and Full Adders

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

Essentials of the Java(TM) Programming Language, Part 1

Continued Fractions and the Euclidean Algorithm

Welcome to Basic Math Skills!

MATH 90 CHAPTER 6 Name:.

Trigonometric Functions and Triangles

Part I. Multiple Choice Questions (2 points each):

MATLAB Workshop 3 - Vectors in MATLAB

SAT Subject Math Level 2 Facts & Formulas

The following four software tools are needed to learn to program in Java:

AP Computer Science Java Mr. Clausen Program 9A, 9B

Finding Rates and the Geometric Mean

Solving Rational Equations

The Center for Teaching, Learning, & Technology

The Basic Java Applet and JApplet

MATHS ACTIVITIES FOR REGISTRATION TIME

file://c:\dokumente und Einstellungen\Marco Favorito\Desktop\ScanCmds.html

Math Review. for the Quantitative Reasoning Measure of the GRE revised General Test

Interactive Applications (CLI) and Math

Lecture 2 Mathcad Basics

Algebra 2: Themes for the Big Final Exam

Lies My Calculator and Computer Told Me

Lab 5: Bank Account. Defining objects & classes

C Programming Language

Schueler-Organisiertes Lernen am Beispiel von Grafischen Benutzer-Schnittstellen in Java Tag der Offenen Tür - GTS 2008

Prime Time: Homework Examples from ACE

Click on the links below to jump directly to the relevant section

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

How to Convert an Application into an Applet.

FACTORING QUADRATICS and 8.1.2

COMPLEX NUMBERS. a bi c di a c b d i. a bi c di a c b d i For instance, 1 i 4 7i i 5 6i

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

1 Hour, Closed Notes, Browser open to Java API docs is OK

Factorizations: Searching for Factor Strings

public class Application extends JFrame implements ChangeListener, WindowListener, MouseListener, MouseMotionListener {

Essentials of the Java Programming Language

ACT Math Facts & Formulas

Part 1 Expressions, Equations, and Inequalities: Simplifying and Solving

Comp 248 Introduction to Programming

Here's the code for our first Applet which will display 'I love Java' as a message in a Web page

Mathematics. ( : Focus on free Education) (Chapter 5) (Complex Numbers and Quadratic Equations) (Class XI)

Zero: If P is a polynomial and if c is a number such that P (c) = 0 then c is a zero of P.

This activity will guide you to create formulas and use some of the built-in math functions in EXCEL.

Session 6 Number Theory

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

TRIGONOMETRY Compound & Double angle formulae

AP Physics 1 Summer Assignment

Core Maths C2. Revision Notes

Java Basics: Data Types, Variables, and Loops

SOLVING TRIGONOMETRIC EQUATIONS

ALGEBRA 2/TRIGONOMETRY

MATH 140 Lab 4: Probability and the Standard Normal Distribution

MATH 108 REVIEW TOPIC 10 Quadratic Equations. B. Solving Quadratics by Completing the Square

Inner Product Spaces

Quick Reference ebook

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

1 Math Circle WARM UP

Second Order Linear Nonhomogeneous Differential Equations; Method of Undetermined Coefficients. y + p(t) y + q(t) y = g(t), g(t) 0.

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

Situation Analysis. Example! See your Industry Conditions Report for exact information. 1 Perceptual Map

Answer Key for California State Standards: Algebra I

3.2. Solving quadratic equations. Introduction. Prerequisites. Learning Outcomes. Learning Style

Transcription:

Lecture Seven Math methods GUI review Interest Calculator Math methods Math comparisons Math constants Formatting numbers Roll Dice program Random numbers Rounding numbers Casting Drill Read Chapter 5, pg. 115 1

GUI review In the last lesson we created a simple calculator GUI. We will continue to build from that GUI in this lesson. There are still some GUI concepts that we are using but have not gone over in detail. Don t t worry too much about why things work the way they do we will go over in detail the inner workings of GUIs in future lessons. 2

GUI review Recall the major steps we took when we constructed our SimpleCalc program 1. Import library packages 2. Open the class 3. Declare the components 4. Write a main method 5. Begin the constructor method 6. Select a layout manager 7. Add components to the layout 8. Add listeners to buttons and the window 9. Write the actionperformed method 10. Complete the WindowListener 3

Interest calculator Suppose we have just written a Java program and a major software company has purchased it from us for $500,000. We decide we want to invest this money but there are so many options! There are CDs at 4.5%, compounded yearly for 10 years; money market accounts at 4.0%, compounded monthly, etc. Our goal is to write a simple interest calculator that we can use to determine how much money we would earn by investing our money in these different types of accounts. 4

Interest calculator Compound interest is determined by the following equation: B = P * (1 + r/c) c*n Where B = ending balance P = initial principal amount invested r = interest rate c = number of times amount is compounded per year n = number of years invested Furthermore, we can determine the amount of money we made by subtracting our initial principal from our ending balance (B( P) 5

Interest calculator We decide we want our interface to look something like this: 6

Interest calculator We will now write our InterestCalc using the same steps we took to create our SimpleCalc Follow along and (as always) write the program as we go! 7

Step 1: Import library packages // For GUI stuff import java.awt.*;.*; import javax.swing.*;.*; import java.awt.event.*;.*; // For Math functions and NumberFormat import java.lang.math; import java.text.*;.*; This is just like the SimpleCalc program except we also add libraries for Math and NumberFormat classes 8

Step 2: Declare the class InterestCalc // For Math functions and NumberFormat import java.lang.math; import java.text.*;.*; // Create class public class InterestCalc extends JFrame implements ActionListener, WindowListener { 9

Step 3: Declare the components { // Declare GUI components private JLabel principallabel; private JTextField principalfield; private JLabel ratelabel; private JTextField ratefield; private JLabel compoundlabel; private JTextField compoundfield; private JLabel yearslabel; private JTextField yearsfield; private JLabel balancelabel; private JTextField balancefield; private JLabel moneylabel; private JTextField moneyfield; private JButton calculatebutton; 10

Step 4: Write the main method... private JButton calculatebutton; // main method public static void main(string args[]) { } JFrame frame = new InterestCalc(); frame.setsize(350, 250); frame.settitle("interest Calculator"); frame.setvisible(true); 11

Step 5: Begin the constructor method // constructor public InterestCalc() { principallabel = new JLabel(" Initial Principal: "); principalfield = new JTextField(); // no initial value or width ratelabel = new JLabel(" Interest Rate: "); ratefield = new JTextField(); compoundlabel = new JLabel(" Compound Times Per Year:"); compoundfield = new JTextField(); yearslabel = new JLabel(" Years: "); yearsfield = new JTextField(); balancelabel = new JLabel(" Ending Balance: "); balancefield = new JTextField(); moneylabel = new JLabel(" Money Made: "); moneyfield = new JTextField(); calculatebutton = new JButton("Calculate"); "); 12

Step 6: Select and set a layout manager In the SimpleCalc we used a FlowLayout.. For our InterestCalc we will learn about a new layout, GridLayout (see pg 115) When creating a new GridLayout,, you must pass two arguments to the method. The first is the number of rows in your grid, the second is the number of columns in your grid. GridLayout will then divide the frame into a grid and will add components from left to right, top to bottom One thing to note about GridLayout is that components are resized to fit entirely into the grid space allocated for that component. (This is why there was no need to specify a field width when we created our JTextFields in the previous slide.) 13

Step 6: Select and set a layout manager... calculatebutton = new JButton("Calculate"); "); // create layout // grid layout with 7 rows and 2 columns GridLayout layout = new GridLayout(7, 2); Container window = getcontentpane(); window.setlayout(layout); 14

Step 7: Add the components to the layout // add components to window window.add(principallabel); window.add(principalfield); window.add(ratelabel); window.add(ratefield); window.add(compoundlabel); window.add(compoundfield); window.add(yearslabel); window.add(yearsfield); window.add(balancelabel); window.add(balancefield); window.add(moneylabel); window.add(moneyfield); window.add(calculatebutton); 15

Step 8: Add listeners to button and window... window.add(calculatebutton); // add action listeners calculatebutton.addactionlistener(this); addwindowlistener(this); } // close constructor 16

Step 9: Write the actionperformed method // action performed method public void actionperformed (ActionEvent e) { String tempstring; double principal, rate, compound, balance, years, moneymade; NumberFormat currency = NumberFormat.getCurrencyInstance(); if (e.getsource( e.getsource() == calculatebutton) { // get data and convert to doubles tempstring = principalfield.gettext().trim(); (); principal = (new Double(tempString)).doubleValue(); (); tempstring = ratefield.gettext().trim(); (); rate = (new Double(tempString)).doubleValue() () / 100.0; tempstring = compoundfield.gettext().trim(); (); compound = (new Double(tempString)).doubleValue(); (); tempstring = yearsfield.gettext().trim(); (); years = (new Double(tempString)).doubleValue(); (); 17

Step 9: Write the actionperformed method (cont)... years = (new Double(tempString)).doubleValue(); (); // calculate balance and money made balance = Math.pow(1.0 +rate/compound, compound * years) * principal; moneymade = balance - principal; } } // output balance and money made in text box as currency balancefield.settext(currency.format(balance)); moneyfield.settext(currency.format(moneymade)); 18

Step 10: Complete the WindowListener // window actions public void windowclosing(windowevent e) { System.exit(0); } public void windowactivated(windowevent e){} public void windowclosed(windowevent e){} public void windowdeactivated(windowevent e){} public void windowiconified(windowevent e){} public void windowdeiconified(windowevent e){} public void windowopened(windowevent e){} } // close InterestCalc class 19

Interest calculator Compile the code and see if it works. Investing my money into a 10 year CD at 4.5% interest compounded monthly looks like a good deal! 20

Math methods The InterestCalc program uses a method from the Math class pow() which takes 2 arguments: a base and an exponent In order to use methods from the Math class we must import java.lang.math; A list of commonly used Math methods are listed in your textbook on pg. 57 21

Math methods (cont) Most of the methods listed take a single argument (with the exception of max(), min(), and pow() which all take 2 arguments) Most methods also have a return type of type double Exceptions: abs() returns the same type of value that was used as an argument max() & min() returns a value that is the same type as the argument with the most precision (more on this later) round() returns the int value that is closest to the double passed in as an argument 22

Math comparisons Two special Math methods max() and min() can be used to compare two numbers Each method takes two numbers as arguments and will return the number that is either the greatest (max) or the least (min) The return type is determined by the argument with the greatest precision For example, System.out.println(Math.max(24, 23.0)); // this will print 24.0 NOT 24 since the argument with // greatest precision is 23.0, which is a double 23

Math constants In addition to the Math methods, there are also 2 Math constants These constants are of type double and can be used in programs to perform certain calculations The two constants are: Math.PI value of pi Math.E value of base of natural logs For example, to calculate the area of a circle given a radius, r,, would be area = Math.PI * pow(r,, 2); 24

Formatting numbers In addition to using Math methods in the InterestCalc program, we also used some methods from the NumberFormat class in order to format the output of our balance as currency In order to use NumberFormat we need to import java.text.*;.*; Once we import the library we then need to create a NumberFormat instance. In our program we did this with this line of code: NumberFormat currency = NumberFormat.getCurrencyInstance(); 25

Formatting numbers (cont) NumberFormat currency = NumberFormat.getCurrencyInstance(); This line of code created a currency format. We can also create other formats by calling the getnumberinstance() or getpercentinstance() methods. getnumberinstance() will format numbers with added commas (Ex: 1000000 becomes 1,000,000) getpercentinstance() will format numbers as percentages (Ex: 0.75 becomes 75%) 26

Formatting numbers (cont) Once we create a format we must then specify which value we want to format. In our example we created a format named currency and wanted to apply it to our variable named balance To do this we called the format() method which then returns a String that we could display in our JTextField balancefield balancefield.settext(currency.format(balance)); 27

Roll Dice program Let s s take a look at another example that uses other Math methods For this example we are going to create a Dice emulator (i.e. a program that mimics the act of rolling dice) We will pretend we have a pair of dice and want to generate a random roll each time the Roll button is pressed Again, we can modify our previous GUIs to achieve this However, we will not go through the 10 steps to create the GUI (you should be familiar with them by now) 28

Roll Dice program code (1) // For GUI stuff import java.awt.*;.*; import javax.swing.*;.*; import java.awt.event.*;.*; // For Math functions import java.lang.math; // Create class public class RollDice extends JFrame implements ActionListener, WindowListener { // Declare GUI components private JLabel displaylabel; private JButton rollbutton; 29

Roll Dice program code (2) // main method public static void main(string args[]) { JFrame frame = new RollDice(); frame.setsize(150, 100); frame.settitle("roll Dice"); frame.setvisible(true); } // constructor public RollDice() { displaylabel = new JLabel("Click Roll"); rollbutton = new JButton("Roll"); "); 30

Roll Dice program code (3) // create layout FlowLayout layout = new FlowLayout(); Container window = getcontentpane(); window.setlayout(layout); // add components to window window.add(displaylabel); window.add(rollbutton); // add action listeners rollbutton.addactionlistener(this); addwindowlistener(this); } 31

Roll Dice program code (4) // action performed method public void actionperformed (ActionEvent e) { } int die1, die2; if (e.getsource( e.getsource() == rollbutton) { } die1 = (int( int) Math.ceil(Math.random() () * 6); die2 = (int( int) Math.ceil(Math.random() () * 6); displaylabel.settext("you rolled a " + die1 + " and a " + die2); 32

Roll Dice program code (5) } // window actions public void windowclosing(windowevent e) { } System.exit(0); public void windowactivated(windowevent e){} public void windowclosed(windowevent e){} public void windowdeactivated(windowevent e){} public void windowiconified(windowevent e){} public void windowdeiconified(windowevent e){} public void windowopened(windowevent e){} 33

Random numbers Our RollDice program should not have any unfamiliar components in terms of the GUI The only lines of code that should be new to you are: die1 = (int( int) Math.ceil(Math.random() () * 6); die2 = (int( int) Math.ceil(Math.random() () * 6); Let s s take a look at this line of code piece by piece 34

Random numbers (cont) die1 = (int( int) Math.ceil(Math.random Math.random() * 6); 6 We ll start by looking from the inside out. The first thing we see is Math.random() * 6 The random() method is used to create a random number of type double that is between 0.0 and 1.0 Because we want to generate a number that is a valid die roll we need to multiply our number by 6 which then gives us a random number between 0.0 and 6.0 35

Rounding numbers die1 = (int( int) Math.ceil(Math.random Math.random() * 6); 6 The next command we use is Math.ceil() which is a rounding command used to round numbers up Since it is impossible to have a die roll of 0 we use this command to round our random number up, thus giving us a new range of random numbers between 1.0 and 6.0 Other rounding commands include floor() (which rounds a number down) and round() (which rounds a number either down or up) 36

Casting die1 = (int) Math.ceil(Math.random() () * 6); The final part of this statement is the (int) part which is called a cast Since the result of our Math methods are doubles we must cast the results to an int (because we wouldn t want a die roll of 5.9) Casting is used to convert numbers of one type to another type In our example we cast down because we cast a value of type double down to a value of type integer (which has less precision). We can also cast values up. When casting down there is the potential for precision and data loss because values may be truncated. For example, casting a double (say 5.9) down to an integer will result in 5 (not 6). 37

Drill 7 1.Create an angle calculator GUI. That is, allow the user to enter an angle into a field as degrees. Display that value as radians and also give the sin, cos,, and tan of the angle. Try using the GridLayout like we did in the InterestCalc.. Hint: the trig methods require their arguments be in radians, not degrees. 38

Drill 7 (cont.) 2.Create a GUI that can find the two roots of a quadratic function. Allow the user to specify values for a, b, and c. For those of you who are rusty on your algebra that means we want to find where ax 2 + bx + c = 0 To do this we can solve using the quadratic equation: x = -b ± b 2a 2 4ac 39

Drill 7 (cont.) 3.Create a GUI that asks a user to guess a number between 1 and 10. Then, randomly generate a number between 1 and 10 and tell the user whether or not he or she guessed correctly. 40