java eclipse calculator
finished product from lesson 8, Do-It-Yourself Java Games, by Annette Godtland.
https://drive.google.com/file/d/0B3jCoMOxti9fdmlsWDMtRDdkZ1U/view?usp=sharing
or
package nellie.tobey.calculator;
import com.godtsoft.diyjava.DIYWindow;
public class Calculator extends DIYWindow {
public Calculator() {
print("Do some math?");
String s = input();
while (s.startsWith("Y")|| s.startsWith("y")) {
double a = promptForDouble("Enter a number:");
String operation = promptForString("Enter an operator: * - + / ?");
double b = promptForDouble("Enter another number:");
double c = 0;
switch(operation) {
case "+":
c = a + b;
print(a + "+" + b + "="+ c);
break;
case "*":
c = a * b;
print(a + "*" + b + "="+ c);
break;
case "/":
try {
c = a / b;
print(a + "/" + b + "="+ c);}
catch (ArithmeticException e) {
print("can not divide by zero.");
}
break;
case "-":
c = a - b;
print(a + "-" + b + "="+ c);
break;
default:
print("that is not a valid operator. Try again.");
}
s = promptForString("Do some math?");
}}
private double promptForDouble(String prompt) {
double i = 0;
print(prompt);
String s = input();
try {
i = Double.parseDouble(s);
}
catch (NumberFormatException e) {
print(s + " is not a valid number. Try again.");
i = promptForDouble(prompt);
}
return i;}
private String promptForString(String prompt) {
print(prompt);
String s = input();
return s;}
public static void main(String[] args) {
new Calculator();
}
}
https://drive.google.com/file/d/0B3jCoMOxti9fdmlsWDMtRDdkZ1U/view?usp=sharing
or
package nellie.tobey.calculator;
import com.godtsoft.diyjava.DIYWindow;
public class Calculator extends DIYWindow {
public Calculator() {
print("Do some math?");
String s = input();
while (s.startsWith("Y")|| s.startsWith("y")) {
double a = promptForDouble("Enter a number:");
String operation = promptForString("Enter an operator: * - + / ?");
double b = promptForDouble("Enter another number:");
double c = 0;
switch(operation) {
case "+":
c = a + b;
print(a + "+" + b + "="+ c);
break;
case "*":
c = a * b;
print(a + "*" + b + "="+ c);
break;
case "/":
try {
c = a / b;
print(a + "/" + b + "="+ c);}
catch (ArithmeticException e) {
print("can not divide by zero.");
}
break;
case "-":
c = a - b;
print(a + "-" + b + "="+ c);
break;
default:
print("that is not a valid operator. Try again.");
}
s = promptForString("Do some math?");
}}
private double promptForDouble(String prompt) {
double i = 0;
print(prompt);
String s = input();
try {
i = Double.parseDouble(s);
}
catch (NumberFormatException e) {
print(s + " is not a valid number. Try again.");
i = promptForDouble(prompt);
}
return i;}
private String promptForString(String prompt) {
print(prompt);
String s = input();
return s;}
public static void main(String[] args) {
new Calculator();
}
}
Comments
Post a Comment