Commit b8685438 authored by Steven Brandt's avatar Steven Brandt
Browse files

Added 05

parent 1d58d9ee
No related merge requests found
Showing with 538 additions and 0 deletions
+538 -0
<?php include("../../header2.php") ?>
<h2>Basic Graphics: The Calculator</h2>
<p>This lab will make you familiar with the basic
graphics programming environment. It is a necessary
preparation for your final project. This lab should
also help you become familiar with anonymous inner
classes.
</p>
<p>The basic graphics package is distributed as
<a href="https://www.cct.lsu.edu/~sbrandt/csc1351/BasicGraphics.zip">
a Netbeans package,</a> and Calculator.java is one of the
applications it comes with (look in the basicgraphics.calculator package). By default, the Calculator looks
like this:</p> <img src="CalcPic.jpg" />
<p>All the buttons work. For example, if you type the sequence "3.2+1.1=" you
will see the result "4.3". The "Clr" button clears the screen so you
can type a new expression for evaluation.</p>
<p>Obviously, on Mars we will need a more advanced calculator.
Our survival will depend upon it.
Your assignment is to modify the Calculator.java file so that the
calculator looks like this:</p>
<img src="CalcPicAssignment.png" width="500"/>
<p>The first thing you will need to get working are the various functions
to fetch data about Mars. This is available to you from the
<a href="MarsData.java">MarsData class,</a>
which will fetch live information about the Red Planet from the
internet. To use this class, simply instantiate it and read its fields.
(Note: You do not need to download this file or the tester if you have the latest <a href="https://www.cct.lsu.edu/~sbrandt/csc1351/BasicGraphics.zip">BasicGraphics.zip</a> installed, since they are already present inside it)
<pre>
MarsData md = new MarsData();
setValue(md.declination); // sets the current value of the calculator
update(); // updates the calculator display
</pre>
The next thing you should work on is the sin() function. You
can find this as a static method on the java.lang.Math package. You call
it like this:
<pre>
double val1 = ...;
double val2 = Math.sin(val1);
</pre>
All the other functions, i.e. cos(), log(), exp() are also in the java.lang.Math
package and must be called in the same manner.
</p>
<p>When you update the layout in Calculator.java,
use the name "Sin" for the "Sin" button, "Exp" for
the "Exp" button and so on. Use the name "M" for the "M+" button,
"R" for the "MR" button, and "?" for the "+/-" button.</p>
<p>The tester requires you to let go of the mouse button quickly after
you start your application. Java will take over and move the mouse as
well as press the buttons to test your app. The first thing it will test
is sin(), then cos(), etc.</p>
<p>The tester consists of two files. <a href='CalcTester.java'>CalcTester.java</a>
and <a href='Auto.java'>Auto.java</a>. (If you get the latest
version of BasicGraphics, they will already be included)
<p>The "M+" button saves a value into the memory. The "MR" button recalls
the last value saved to memory with "M+".</p>
<p>The "+/-" button will negate the current value. It can be pressed at
any time. So the sequence "3" "+/-" "." "4" should enter the value "-3.4".</p>
<table border='1' cellpadding='5' cellspacing='0'>
<tr><th>Layout Key</th><th>Button Text</th><th>Function</th></tr>
<tr><td>RA</td><td>Right Ascension</td><td>Get the right ascension of Mars from the MarsData class.</td></tr>
<tr><td>DECL</td><td>Declination</td><td>Get the declination of Mars from the MarsData class.</td></tr>
<tr><td>ED</td><td>Earth Distance</td><td>Get the distance between Mars and the Earth from the MarsData class.</td></tr>
<tr><td>SD</td><td>Sun Distance</td><td>Get the distance between Mars and the Sun from the MarsData class.</td></tr>
<tr><td>Sin</td><td>Sin</td><td>Take the sin of the current value</td></tr>
<tr><td>Cos</td><td>Cos</td><td>Take the cos of the current value</td></tr>
<tr><td>Exp</td><td>Exp</td><td>Take the exponential of the current value</td></tr>
<tr><td>Log</td><td>Log</td><td>Take the log of the current value</td></tr>
<tr><td>M</td><td>M+</td><td>Store the current value to memory</td></tr>
<tr><td>R</td><td>MR</td><td>Retrieve the value in memory</td></tr>
<tr><td>?</td><td>+/-</td><td>Negate the current value</td></tr>
</table>
<?php showFile("Calculator.java"); ?>
<?php showFile("MarsData.java"); ?>
<?php showFile("CalcTester.java"); ?>
<?php showFile("Auto.java"); ?>
<?php include("../../footer.php") ?>
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package basicgraphics.calculator;
import basicgraphics.BasicFrame;
import java.awt.AWTException;
import java.awt.Component;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
/**
*
* @author sbrandt
*/
public class Auto {
Robot robot;
public Auto() throws AWTException {
robot = new Robot();
}
public void press(Component c) {
delay();
Point pt = new Point(c.getLocationOnScreen());
robot.mouseMove(pt.x+1, pt.y+1);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
public void press(BasicFrame bf, String b) {
press(bf.getComponent(b));
}
private void delay() {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
}
public String getValue(BasicFrame bf, String txt) {
delay();
Component c = bf.getComponent(txt);
if(c instanceof JLabel) {
return ((JLabel) c).getText();
} else if(c instanceof JTextArea) {
return ((JTextArea) c).getText();
} else if(c instanceof JTextComponent) {
return ((JTextComponent) c).getText();
}
throw new Error("Not a text component");
}
}
website/csc1351/05/CalcPic.jpg

15.7 KB

website/csc1351/05/CalcPicAssignment.png

33.1 KB

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package basicgraphics.calculator;
import basicgraphics.BasicFrame;
import java.text.DecimalFormat;
import java.util.Random;
/**
*
* @author sbrandt
*/
public class CalcTester {
public static final Random RAND = new Random();
public static final DecimalFormat df = new DecimalFormat("#.######");
public static void press(Auto a, BasicFrame bf, double d) {
if (d < 0) {
a.press(bf, "?");
d = -d;
}
String s = df.format(d);
for (int i = 0; i < s.length(); i++) {
a.press(bf, "" + s.charAt(i));
}
}
static double reval(double d) {
return Double.parseDouble(df.format(d));
}
public static void main(String[] args) throws Exception {
try {
assert false;
throw new Error("Enable assertions");
} catch (AssertionError ae) {
}
Auto a = new Auto();
Calculator c = (Calculator) Class.forName(args[0]).newInstance();
c.init();
Thread.sleep(1000);
for (int i = 0; i < 3; i++) {
double d1, d2, dval;
String val;
System.out.println("Test Sin");
d1 = Math.PI * RAND.nextInt(10);
a.press(c.bf, "C");
press(a, c.bf, d1);
val = a.getValue(c.bf, "D");
d1 = Double.parseDouble(val);
a.press(c.bf, "Sin");
val = a.getValue(c.bf, "D");
dval = Double.parseDouble(val);
d2 = reval(Math.sin(d1));
assert dval == d2 : "" + dval + " != " + d2;
System.out.println("Test Cos");
d1 = Math.PI * RAND.nextInt(10);
a.press(c.bf, "C");
press(a, c.bf, d1);
val = a.getValue(c.bf, "D");
d1 = Double.parseDouble(val);
a.press(c.bf, "Cos");
val = a.getValue(c.bf, "D");
dval = Double.parseDouble(val);
d2 = reval(Math.cos(d1));
assert dval == d2 : "" + dval + " != " + d2;
System.out.println("Test Exp");
d1 = 0.1 * RAND.nextInt(10);
a.press(c.bf, "C");
press(a, c.bf, d1);
val = a.getValue(c.bf, "D");
d1 = Double.parseDouble(val);
a.press(c.bf, "Exp");
val = a.getValue(c.bf, "D");
dval = Double.parseDouble(val);
d2 = reval(Math.exp(d1));
assert dval == d2 : "" + dval + " != " + d2;
System.out.println("Test Log");
a.press(c.bf, "Log");
val = a.getValue(c.bf, "D");
dval = Double.parseDouble(val);
assert dval == d1 : "" + dval + " != " + d1;
}
for (int i = 0; i < 3; i++) {
int v1,v2;
double dval;
String val;
v1 = RAND.nextInt(10);
v2 = RAND.nextInt(10);
a.press(c.bf, "C");
a.press(c.bf, "" + v1);
a.press(c.bf, "-");
a.press(c.bf, "" + v2);
a.press(c.bf, "=");
val = a.getValue(c.bf, "D");
System.out.println("val=" + val);
dval = Double.parseDouble(val);
assert dval == v1 - v2;
System.out.println("Test M+ and MR");
a.press(c.bf, "C");
a.press(c.bf, "" + v1);
a.press(c.bf, "M");
a.press(c.bf, "C");
a.press(c.bf, "R");
a.press(c.bf, "-");
a.press(c.bf, "" + v2);
a.press(c.bf, "=");
val = a.getValue(c.bf, "D");
System.out.println("val=" + val);
dval = Double.parseDouble(val);
assert dval == v1 - v2;
System.out.println("Test +/-");
a.press(c.bf, "C");
a.press(c.bf, "" + v1);
a.press(c.bf, "?");
a.press(c.bf, "-");
a.press(c.bf, "" + v2);
a.press(c.bf, "=");
val = a.getValue(c.bf, "D");
System.out.println("val=" + val);
dval = Double.parseDouble(val);
assert dval == -v1 - v2;
a.press(c.bf, "C");
a.press(c.bf, "?");
a.press(c.bf, "" + v1);
a.press(c.bf, "-");
a.press(c.bf, "" + v2);
a.press(c.bf, "=");
val = a.getValue(c.bf, "D");
System.out.println("val=" + val);
dval = Double.parseDouble(val);
assert dval == -v1 - v2;
a.press(c.bf, "C");
a.press(c.bf, "" + v1);
a.press(c.bf, "-");
a.press(c.bf, "" + v2);
a.press(c.bf, "?");
a.press(c.bf, "=");
val = a.getValue(c.bf, "D");
System.out.println("val=" + val);
dval = Double.parseDouble(val);
assert dval == v1 + v2;
a.press(c.bf, "C");
a.press(c.bf, "" + v1);
a.press(c.bf, "-");
a.press(c.bf, "?");
a.press(c.bf, "" + v2);
a.press(c.bf, "=");
val = a.getValue(c.bf, "D");
System.out.println("val=" + val);
dval = Double.parseDouble(val);
assert dval == v1 + v2;
}
System.out.println("all tests passed");
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package basicgraphics.calculator;
import basicgraphics.BasicFrame;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JLabel;
/**
*
* @author sbrandt
*/
public class Calculator {
public final static String[][] layout = {
{"D","D","D","C"},
{"1","2","3","+"},
{"4","5","6","-"},
{"7","8","9","*"},
{"0",".","=","/"}
};
double value_, previousValue, memory;
String operator;
double decimal=1.0;
double sgn=1.0;
JLabel display = new JLabel("0",JLabel.CENTER);
public BasicFrame bf = new BasicFrame("Martian Calculator");
public double getValue() {
return value_ * sgn;
}
public void setValue(double v) {
if(v < 0) {
sgn = -1.0;
value_ = -v;
} else {
sgn = 1.0;
value_ = v;
}
}
public void init() {
bf.add(layout,"D",display);
for(int i=0;i<=9;i++) {
final int key = i;
JButton b = new JButton(""+i);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(decimal == 1.0) {
value_ = 10*value_+key;
} else {
value_ = value_ + key*decimal;
decimal *= 0.1;
}
update();
}
});
bf.add(layout, ""+i, b);
}
for(String s : new String[]{"+","-","/","*","="}) {
final String op = s;
JButton b = new JButton(op);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if("=".equals(op)) {
calc(operator);
setValue(previousValue);
operator = null;
} else {
previousValue = getValue();
setValue(0.0);
operator = op;
sgn = 1.0;
}
decimal = 1.0;
update();
}
});
bf.add(layout,op,b);
}
// The text on the button is "Clr"
JButton clear = new JButton("Clr");
clear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setValue(0.0);
previousValue = 0;
operator = null;
decimal = 1.0;
update();
}
});
// The place of the button in the layout is
// given by "C".
bf.add(layout,"C",clear);
JButton dot = new JButton(".");
dot.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
decimal *= .1;
}
});
bf.add(layout,".",dot);
Font f = new Font("Courier",Font.BOLD,30);
bf.setAllFonts(f);
bf.show();
}
public void calc(String op) {
if ("+".equals(op)) {
previousValue = previousValue + getValue();
} else if ("-".equals(op)) {
previousValue = previousValue - getValue();
} else if ("*".equals(op)) {
previousValue = previousValue * getValue();
} else if ("/".equals(op)) {
previousValue = previousValue / getValue();
}
}
final static DecimalFormat df = new DecimalFormat("#.######");
public void update() {
if(operator == null) {
display.setText(df.format(getValue()));
} else {
display.setText(df.format(previousValue)+operator+df.format(getValue()));
}
}
public static void main(String[] args) {
Calculator c = new Calculator();
c.init();
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package basicgraphics.calculator;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
/**
* This class fetches live data about Mars from the internet.
*
* @author sbrandt
*/
public class MarsData {
public double rightAscension;
public double declination;
public double sunDistance;
public double earthDistance;
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("MarsData{");
sb.append(String.format("rightAscension=%.6f,", rightAscension));
sb.append(String.format("declination=%.6f,", declination));
sb.append(String.format("sunDistance=%.6f,", sunDistance));
sb.append(String.format("earthDistance=%.6f", earthDistance));
sb.append("}");
return sb.toString();
}
public MarsData() {
try {
Pattern rightAscensionP = Pattern.compile("Right.*Ascension:.*>\\s*([-\\d.]+)\\s*<");
Pattern declinationP = Pattern.compile("Declination:.*>\\s*([-\\d.]+)\\s*<");
Pattern sunDistanceP = Pattern.compile("Sun.*Distance:.*>\\s*([-\\d.]+)\\s*<");
Pattern earthDistanceP = Pattern.compile("Earth.*Distance:.*>\\s*([-\\d.]+)\\s*<");
Scanner sc = null;
String info = System.getProperty("user.home", ".") + "/mars_info.txt";
File finfo = new File(info);
if (finfo.exists() && finfo.lastModified() + 10 * 60 * 1000 > System.currentTimeMillis()) {
sc = new Scanner(finfo);
} else {
URL url = new URL("https://theskylive.com/mars-tracker");
sc = new Scanner(url.openStream());
}
while (sc.hasNextLine()) {
if (sc.findInLine(rightAscensionP) != null) {
MatchResult mr = sc.match();
rightAscension = Double.parseDouble(mr.group(1));
}
if (sc.findInLine(declinationP) != null) {
MatchResult mr = sc.match();
declination = Double.parseDouble(mr.group(1));
}
if (sc.findInLine(sunDistanceP) != null) {
MatchResult mr = sc.match();
sunDistance = Double.parseDouble(mr.group(1));
}
if (sc.findInLine(earthDistanceP) != null) {
MatchResult mr = sc.match();
earthDistance = Double.parseDouble(mr.group(1));
}
sc.nextLine();
}
PrintWriter pw = new PrintWriter(finfo);
pw.printf("Right Ascension: >%f<%n",rightAscension);
pw.printf("Declination: >%f<%n",declination);
pw.printf("Earth Distance: >%f<%n",earthDistance);
pw.printf("Sun Distance: >%f<%n",sunDistance);
pw.close();
} catch (IOException ioe) {
}
}
}
......@@ -64,6 +64,8 @@ Coding Bat: Arrays: You should be able to complete
</ol>
</li>
<li><b>Exam 1:</b>
<a href="exam1.q.key.pdf">exam1.q.key.pdf</a>
<li><b>Practice Exam 1:</b>
<ol>
<li><a href='exam1_noanswers.pdf'>Practice exam 1 without answers</a>,</li>
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment