Basic Calculator - java

Im having problems with my program. the program displays the first JOption message dialog box, but when you input a value, it fails to display the second dialog box??
import java.util.Scanner;
import javax.swing.JOptionPane;
public class javaCalculator
{
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
JOptionPane.showInputDialog(null,"please enter the first number");
num1 = input.nextInt();
JOptionPane.showInputDialog(null,"please enter the second number");
num2 = input.nextInt();
JOptionPane.showInputDialog(null,"Please enter operation");
operation = input.next();
if (operation.equals ("+"))
{
JOptionPane.showMessageDialog(null,"your answer is" + " " + (num1 + num2));
}
if (operation.equals ("-"))
{
JOptionPane.showMessageDialog(null,"your answer is" + " " + (num1 - num2));
}
if (operation.equals ("/"))
{
JOptionPane.showMessageDialog(null,"your answer is" + " " + (num1 / num2));
}
if (operation.equals ("*"))
{
JOptionPane.showMessageDialog(null,"your answer is" + " " + (num1 * num2));
}
}
}

Read the numbers from the dialog output instead of from System.in:
String firstNumber = JOptionPane.showInputDialog(null,"please enter the first number");
if (firstNumber != null) {
num1 = Integer.parseInt(firstNumber);
}
Scanner is unnecessary in your code.

You can try using that sample code:
import javax.swing.JOptionPane;
public class Hw4_3 {
private static boolean flag;
public static void main(String[] args) {
do {
String[] expression = getTask();
double result = calculate(expression);
display(expression, result);
repeat();
} while (flag);
}
public static String[] getTask()
{
String bleh = JOptionPane.showInputDialog(null, "Please enter what you would like to calculate: ");
String[] tokens = bleh.split(" ");
return tokens;
}
public static double calculate(String[] data)
{
double num1 = Double.parseDouble(data[0]);
double num2 = Double.parseDouble(data[2]);
double result = 0;
if(data[1].equals("+"))
{
result = add(num1, num2);
return result;
}
else if(data[1].equals("-"))
{
result = subtract(num1, num2);
return result;
}
else if(data[1].equals("*"))
{
result = multiply(num1, num2);
return result;
}
else
{
if(num2 == 0)
{
JOptionPane.showMessageDialog(null, "Sytax error, divide by zero");
}
result = divide(num1, num2);
return result;
}
}
public static double add(double num1, double num2)
{
return num1 + num2;
}
public static double subtract(double num1, double num2)
{
return num1 - num2;
}
public static double multiply(double num1, double num2)
{
return num1 * num2;
}
public static double divide(double num1, double num2)
{
return num1 / num2;
}
public static void display(String[] data, double result)
{
if(data[1].equals("/") && data[2].equals("0"))
{
}
else
{
JOptionPane.showMessageDialog(null, data[0] + " " + data[1] + " " + data[2] + " = " + result);
}
}
public static void repeat()
{
int bleh = JOptionPane.showConfirmDialog(null, "More?",null, JOptionPane.YES_NO_OPTION);
if(bleh == JOptionPane.NO_OPTION)
{
flag = false;
JOptionPane.showMessageDialog(null, "Have a good day.");
}
else
flag = true;
}
}

Related

How can i make this code simpler? Also how can i check if input is an int?

Hi im a beginner in Java. How could i make this bais calculator simpler?
Also, i want the user to get an error if num1 or num2 arent Integers. How could i do that?
I already tried parseint and scanner.hasnextint but couldnt get them to work.
import java.util.Scanner;
public class topfirst{
public static void main(String[] args) {
int num1;
int num2;
int result;
String yesorno;
String yes = "yes";
String op;
while(yesorno.equals(yes)){
System.out.println("Please enter the first number :");
Scanner inputnum1 = new Scanner(System.in);
num1 = inputnum1.nextInt();
System.out.println("Please enter the second number :");
Scanner inputnum2 = new Scanner(System.in);
num2 = inputnum2.nextInt();
System.out.println("Please enter an operation :");
Scanner inputop = new Scanner(System.in);
op = inputop.next();
String minus = "-";
String plus = "+";
String multipl = "*";
String div = "/";
while ((!op.equals(minus)) && (!op.equals(plus)) && (!op.equals(multipl)) && (!op.equals(div)))
{
System.out.println("Incorrent operation, try again.");
op = inputop.next();
}
switch(op){
case "+":
result = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + result);
break;
case "-":
result = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + result);
break;
case "*":
result = num1 * num2;
System.out.println(num1 + " * " + num2 + " = " + result);
break;
case "/":
result = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + result);
break;
}
System.out.println("Do you want to calculate something else?");
Scanner inyesorno = new Scanner(System.in);
yesorno = inyesorno.next();
}}
}
import java.util.Scanner;
public class TopFirst {
private static final String PLUS = "+";
private static final String MINUS = "-";
private static final String MULTIPLY = "*";
private static final String DIV = "/";
private static final Scanner INPUT = new Scanner(System.in);
public static void main(String[] args) {
do {
System.out.print("Please enter the first number: ");
int num1 = readInt();
System.out.print("Please enter the second number: ");
int num2 = readInt();
System.out.print("Please enter an operator: ");
String operator = readOperator();
int result = countResult(num1, num2, operator);
System.out.printf("%d %s %d = %d%n", num1, operator, num2, result);
System.out.println("Do you want to calculate something else?");
} while (INPUT.next().equals("yes"));
}
private static String readOperator() {
String operator = INPUT.next();
if (isCorrect(operator)) {
return operator;
} else {
System.out.print("Incorrect operator, try again: ");
return readOperator();
}
}
private static int readInt() {
try {
return Integer.parseInt(INPUT.next());
} catch (NumberFormatException e) {
System.out.print("Incorrect number, try again: ");
return readInt();
}
}
private static boolean isCorrect(String operator) {
return MINUS.equals(operator)
|| PLUS.equals(operator)
|| MULTIPLY.equals(operator)
|| DIV.equals(operator);
}
private static int countResult(int num1,
int num2,
String operator) {
switch (operator) {
case PLUS:
return num1 + num2;
case MINUS:
return num1 - num2;
case MULTIPLY:
return num1 * num2;
case DIV:
return num1 / num2;
default:
return 0;
}
}
}
One Error that needs fixing before anything else:
String yesorno;
String yes = "yes";
String op;
while(yesorno.equals(yes)){
[...]
}
Your String yesorno does NOT equal "yes", so the while-loop is never executed in the first place!

How to give 2 different data types from a method

I want to do a simple beginner project using methods, if statements, and user input. I am having an issue though with the calc() method. How can I return two different data types in java, and if I cannot, how could I do it, still by using more than the main method?
import java.util.Scanner; //allow user input
public class fourFunctionCalculator{
public static void main(String[] args) {
Scanner keyboardInput = new Scanner(System.in);
System.out.print("Enter your first number:"); //get first number
double num1 = keyboardInput.nextDouble();
System.out.print("Enter your operator: "); // get operator
String name = keyboardInput.next(); //grabs everything user types until a space
System.out.print("Enter your second number: "); //get second number
double num2 = keyboardInput.nextDouble();
System.out.println(calc(num1,op,num2));
}
//troublesome part is here
public static double calc(double num1, String op, double num2){
if (op == "+") {
return (num1 + num2);
}
else if (op == "-") {
return (num1 - num2);
}
else if (op == "*") {
return (num1 * num2);
}
else if (op == "/") {
return (num1 / num2);
}
else {
return ("INVALID OPERATOR");
}
}
}
you could generate a custom Exception, also you need to use the method .equals() inside the if validations, otherwise it is not going to work.
fourFunctionCalculator.java
import java.util.Scanner; //allow user input
public class fourFunctionCalculator{
public static void main(String[] args) {
Scanner keyboardInput = new Scanner(System.in);
System.out.print("Enter your first number:"); //get first number
double num1 = keyboardInput.nextDouble();
System.out.print("Enter your operator: "); // get operator
String name = keyboardInput.next(); //grabs everything user types until a space
System.out.print("Enter your second number: "); //get second number
double num2 = keyboardInput.nextDouble();
try {
System.out.println(calc(num1,name,num2));
} catch (InvalidOperatorException e) {
System.out.println(e);
}
}
public static double calc(double num1, String op, double num2){
if (op.equals("+")) {
return (num1 + num2);
}
else if (op.equals("-")) {
return (num1 - num2);
}
else if (op.equals("*")) {
return (num1 * num2);
}
else if (op.equals("/")) {enter code here
return (num1 / num2);
}
throw new InvalidOperatorException("INVALID OPERATOR : " + op);
}
}
InvalidOperatorException.java
public class InvalidOperatorException
extends RuntimeException {
private static final long serialVersionUID = 1L;
public InvalidOperatorException(String errorMessage) {
super(errorMessage);
}
}
I recommend returning an OptionalDouble object as placeholder of something valid or not...
Ex #1: return OptionalDouble.of(num1 + num2); // first if outcome
Ex #2: return OptionalDouble.empty(); // for the last else
Then your main(...) method needs to be something like...
System.out.println(calc(num1,op,num2).orElseThrow(() -> new IllegalArgumentException("INVALID OPERATOR")));
I suggest returning always String.
public static String calc(double num1, String op, double num2){
if (op == "+") {
return String.valueOf(num1 + num2);
}
else if (op == "-") {
return String.valueOf(num1 - num2);
}
else if (op == "*") {
return String.valueOf(num1 * num2);
}
else if (op == "/") {
return String.valueOf(num1 / num2);
}
else {
return ("INVALID OPERATOR");
}
}

Double not being passed down in from method to method

I designed a small program where I have three exam grades and I use the Grades class to compute the average of the three. Also, I prompt for the exam number (1,2, or 3) and it should return it. However, I keep getting 0.0 as the output for both the average exam score and chosen exam score.
package GradesClass;
import java.util.Scanner;
public class GradesDriver {
public static void main(String[] args) {
Grades school = new Grades(90.9,87.9,99.9);
Scanner in = new Scanner(System.in);
System.out.println("Enter desired test number: ");
int testnumber = in.nextInt();
System.out.println(school);
System.out.println("Exam score: " + school.getGrades(testnumber));
}
}
package GradesClass;
public class Grades {
private double num1, num2, num3;
private int testnumber;
private double average;
public Grades(double num1, double num2, double num3) {
num1 = 0;
num2 = 0;
num3 = 0;
}
public void setGrades(double scorenumber, int testnumber) {
if (testnumber == 1) {
num1 = scorenumber;
} else if (testnumber == 2) {
num2 = scorenumber;
} else {
num3 = scorenumber;
}
}
public double getGrades(int testnumber) {
if (testnumber == 1) {
return(num1);
} else if (testnumber == 2) {
return(num2);
} else {
return(num3);
}
}
public double average(double num1, double num2, double num3) {
average = ((num1+num2+num3)/3.0);
return(average);
}
public String toString() {
return("Average: " + average);
}
}
In your constructor for Grades you are setting the member variables to zero instead of the values supplied in the parameters. Change the constructor to
public Grades(double num1, double num2, double num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}

In Java code, need to figure out how to get back to the main menu after doing one of the options in the menu?

I am working on Java code. I have a menu, the user selects an option, does something in the option then returns to the menu until the exit is selected. I'm not sure how to get it to go back to the menu.
Here is what I have:
/**
*
* #author Lisa Hergert
*/
import java.util.Scanner;
import java.util.Random;
public class MathTutor {
//Create scanner for user input
Scanner keyboard = new Scanner(System.in);
//Declare variables
int choice;
Random generator = new Random();
public MathTutor () {
choice = 0;
}
public int getQuestionType() {
while (choice < 1 || choice >3) {
System.out.println("Math Tutor");
System.out.println("\t1) Addition problem");
System.out.println("\t2) Subtraction problem");
System.out.println("\t3) Quit");
System.out.println("Enter your choice (1 - 3): ");
choice = keyboard.nextInt();
if (choice < 1 || choice > 3) {
System.out.println("You must choose a number from 1-3");
}
}
return choice;
}
public void askQuestions () {
for (int i = 0; i < 4; i++) {
int num1 = genRandomNum();
int num2 = genRandomNum();
int max = choice;
if (max == 3) {
max = (int)(Math.random() * 3 + 1);
}
switch (max) {
case 1: addition(num1, num2);
break;
case 2: subtraction(num1, num2);
break;
default: System.out.println("Error");
System.exit(1);
}
}
}
public int genRandomNum() {
return (int)generator.nextInt(1000);
}
public void addition(int num1, int num2) {
if (num1 > num2) {
System.out.printf("%5d\n", num1);
System.out.printf("+ %3d\n", num2);
System.out.println("-------");
} else {
System.out.printf("%5d\n", num2);
System.out.printf("+ %3d\n", num1);
System.out.println("-------");
}
int sum = num1 + num2;
int answer = keyboard.nextInt();
if (num1 + num2 == answer) {
System.out.println("Good job, you got it right!");
} else {
System.out.println("Good try, the correct answer is: " + sum);
}
}
public void subtraction (int num1, int num2) {
if (num1 > num2) {
System.out.printf("%5d\n", num1);
System.out.printf("- %3d\n", num2);
System.out.println("-------");
int diff = num1 - num2;
int answer = keyboard.nextInt();
if (num1 - num2 == answer) {
System.out.println("Good job, you got it right!");
} else {
System.out.println("Good try, the correct answer is: " + diff);
}
} else {
System.out.printf("%5d\n", num2);
System.out.printf("- %3d\n", num1);
System.out.println("-------");
int diff = num2 - num1;
int answer = keyboard.nextInt();
if (num2 - num1 == answer) {
System.out.println("Good job, you got it right!");
} else {
System.out.println("Good try, the correct answer is: " + diff);
}
}
}
public static void main(String[] args) {
MathTutor tutor = new MathTutor();
int choice = tutor.getQuestionType();
tutor.askQuestions();
return;
}
}
Maybe I'm missing something but can't you just loop all the functionality?
public static void main(String[] args) {
MathTutor tutor = new MathTutor();
int choice = tutor.getQuestionType();
while(choice != 3) {
tutor.askQuestions();
choice = tutor.getQuestionType();
}
return;
}
import java.util.Scanner;
import java.util.Random;
/**
*
* #author Lisa Hergert
*/
public class MathTutor {
//Create scanner for user input
Scanner keyboard = new Scanner(System.in);
//Declare variables
int choice;
Random generator = new Random();
public MathTutor () {
choice = 0;
}
public int getQuestionType() {
while (choice < 1 || choice >3) {
System.out.println("Math Tutor");
System.out.println("\t1) Addition problem");
System.out.println("\t2) Subtraction problem");
System.out.println("\t3) Quit");
System.out.println("Enter your choice (1 - 3): ");
choice = keyboard.nextInt();
if (choice < 1 || choice > 3) {
System.out.println("You must choose a number from 1-3");
}
}
return choice;
}
public void askQuestions () {
int num1 = genRandomNum();
int num2 = genRandomNum();
int max = choice;
if (max == 3) {
max = (int)(Math.random() * 3+3);
}
switch (max) {
case 1: addition(num1, num2);
break;
case 2: subtraction(num1, num2);
break;
default: System.out.println("Thank you for your time.");
System.exit(1);
}
}
public int genRandomNum() {
return (int)generator.nextInt(1000);
}
public void addition(int num1, int num2) {
if (num1 > num2) {
System.out.printf("%5d\n", num1);
System.out.printf("+ %3d\n", num2);
System.out.println("-------");
} else {
System.out.printf("%5d\n", num2);
System.out.printf("+ %3d\n", num1);
System.out.println("-------");
}
int sum = num1 + num2;
int answer = keyboard.nextInt();
if (num1 + num2 == answer) {
System.out.println("Good job, you got it right!");
} else {
System.out.println("Good try, the correct answer is: " + sum);
}
MathTutor tutor = new MathTutor();
int choice = tutor.getQuestionType();
tutor.askQuestions();
}
public void subtraction (int num1, int num2) {
if (num1 > num2) {
System.out.printf("%5d\n", num1);
System.out.printf("- %3d\n", num2);
System.out.println("-------");
int diff = num1 - num2;
int answer = keyboard.nextInt();
if (num1 - num2 == answer) {
System.out.println("Good job, you got it right!");
} else {
System.out.println("Good try, the correct answer is: " + diff);
}
} else {
System.out.printf("%5d\n", num2);
System.out.printf("- %3d\n", num1);
System.out.println("-------");
int diff = num2 - num1;
int answer = keyboard.nextInt();
if (num2 - num1 == answer) {
System.out.println("Good job, you got it right!");
} else {
System.out.println("Good try, the correct answer is: " + diff);
}
}
MathTutor tutor = new MathTutor();
int choice = tutor.getQuestionType();
tutor.askQuestions();
}
public static void main(String[] args) {
MathTutor tutor = new MathTutor();
int choice = tutor.getQuestionType();
tutor.askQuestions();
}
}

I have used several system.out.print statements , but I am required to use only one sop statement

This is the code and it completely works fine. But I just need to use one SOP statement and I do not know how to do it :(
import java.util.Scanner;
public class Lab4
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
String Expression;
int exp=0;
String Val1=null,Val2=null;
String Compute=null;
Expression=input.nextLine().trim();
if(Expression.trim().contains("<")&&!Expression.trim().contains("="))
{
exp=Expression.trim().indexOf("<");
Compute="<";
Val1=Expression.trim().substring(0, exp);
Val2=Expression.trim().substring(exp+1,Expression.trim().length());
}
else if(Expression.trim().contains(">")&&!Expression.trim().contains("="))
{
exp=Expression.trim().indexOf(">");
Compute=">";
Val1=Expression.trim().substring(0, exp);
Val2=Expression.trim().substring(exp+1,Expression.trim().length());
}
else if(Expression.trim().contains("<="))
{
exp=Expression.trim().indexOf("<=");
Compute="<=";
Val1=Expression.trim().substring(0, exp);
Val2=Expression.trim().substring(exp+2,Expression.trim().length());
}
else if(Expression.trim().contains(">="))
{
exp=Expression.trim().indexOf(">=");
Compute=">=";
Val1=Expression.trim().substring(0, exp);
Val2=Expression.trim().substring(exp+2,Expression.trim().length());
}
int num1,num2;
num1=Integer.parseInt(Val1.trim());
num2=Integer.parseInt(Val2.trim());
if(Compute.equals("<"))
{
if(num1<num2)
System.out.println("True");
else
System.out.println(""+num1+">="+num2+"");
}
else if(Compute.equals(">"))
{
if(num1>num2)
System.out.println("True");
else
System.out.println(""+num1+"<"+num2+"");
}
else if(Compute.equals("<="))
{
if(num1<=num2)
System.out.println("True");
else
System.out.println(""+num1+">="+num2+"");
}
else if(Compute.equals(">="))
{
if(num1>=num2)
System.out.println("True");
else
System.out.println(""+num1+"<"+num2+"");
}
}
}
You could modify your println calls, and instead assign a single String message in your if blocks and then print that message afterwards. Something like,
String message = "";
int num1 = Integer.parseInt(Val1.trim());
int num2 = Integer.parseInt(Val2.trim());
if (Compute.equals("<")) {
if (num1 < num2)
message = "True";
else
message = "" + num1 + ">=" + num2;
} else if (Compute.equals(">")) {
if (num1 > num2)
message = "True";
else
message = "" + num1 + "<=" + num2;
} else if (Compute.equals("<=")) {
if (num1 <= num2)
message = "True";
else
message = "" + num1 + ">" + num2;
} else if (Compute.equals(">=")) {
if (num1 >= num2)
message = "True";
else
message = "" + num1 + "<" + num2;
}
System.out.println(message);

Categories