I am trying to build a basic calculator using if statements - java

I am trying to make a basic calculator for class.
I came up with the code below but all it does it addition.
Even if I use -, *, or /.
Any tips?
Scanner input = new Scanner(System.in);
String num1, num2, operation, function;
System.out.println("Enter a simple equation: ");
function = input.nextLine();
int firstspace = function.indexOf(" ");
num1 = (function.substring(0,firstspace));
int lastspace = function.lastIndexOf(" ");
operation = (function.substring(firstspace,lastspace));
num2= (function.substring(lastspace+1,function.length()));
double n1 = Double.parseDouble(num1);
double n2 = Double.parseDouble(num2);
if (operation.equals(" + "));
{
System.out.println("your answer is " + (n1 + n2));
}
if (operation.equals(" - "))
{
System.out.println("your answer is " + (n1 - n2));
}
if (operation.equals(" / "))
{
System.out.println("your answer is " + (n1 / n2));
}
if (operation.equals(" * "))
{
System.out.println("your answer is " + ( n1*n2));
}
}
}

From what I see your code has this issue
if (operation.equals(" + "));
{
System.out.println("your answer is " + (n1 + n2));
}
Here you are putting a semi colon, which means when you run the code,it will execute this condition by default, so that means addition will always execute whether you like it or not.
So basically your code should be like this
if (operation.equals("+" ))
{
System.out.println("your answer is " + (n1 + n2));
}
if (operation.equals("-"))
{
System.out.println("your answer is " + (n1 - n2));
}
if (operation.equals("/"))
{
System.out.println("your answer is " + (n1 / n2));
}
if (operation.equals("*"))
{
System.out.println("your answer is " + ( n1*n2));
}
Hope this helps

Related

I ned a while loop statment that makes the calculations loop and ask again

im not too sure how you add a loop statement to this. I want it to be a while loop that makes it do that the calculations repeat after finishing. I've tried but it just keeps on giving me errors. ive tried doing While statements but just will not work im not sure how you set it up as my teacher did not explain very well
import com.godtsoft.diyjava.DIYWindow;
public class Calculator extends DIYWindow {
public Calculator() {
// getting number one
double number1 = promptForDouble("Enter a number");
//getting number2
int number2 = promptForInt("Enter an integer");
//getting what to do with operation
print("What do you want to do with these numbers?\nAdd\tSubtract\tMultiply\tDivide");
String operation = input();
//declaring variable here so the same one can be used
double answer = 0;
switch(operation) {
case "add":
answer = number1 + number2;
print(number1 + " + " + number2 + " = " + answer);
break;
case "subtract":
answer = number1 - number2;
print(number1 + " - " + number2 + " = " + answer);
break;
case "multiply":
answer = number1 * number2;
print(number1 + " * " + number2 + " = " + answer);
break;
case "divide":
try {
answer = number1 / number2;
}
catch(ArithmeticException e) {
print("A number cannot be divided by 0.");
}
print(number1 + " / " + number2 + " = " + answer);
break;
}
double double1 = promptForDouble("Enter a number");
double double2 = promptForDouble("Enter another number");
double double3 = promptForDouble("Enter one last number");
print("What do you want to do with these numbers?\nAdd\tSubtrack\tMultiply\tDivide");
String operation2 = input();
double answer2 = 0;
switch(operation2) {
case "add":
answer2 = double1 + double2 + double3;
print(double1 + " + " + double2 + " + " + double3 + " = " + answer2);
break;
case "subtract":
answer2 = double1 - double2 - double3;
print(double1 + " - " + double2 + " - " + double3 + " = " + answer2);
break;
case "multiply":
answer2 = double1 * double2 * double3;
print(double1 + " * " + double2 + " * " + double3 + " = " + answer2);
break;
case "divide":
try {
answer2 = double1 / double2 / double3;
}
catch(ArithmeticException e) {
print("A number cannot be divided by 0.");
}
print(double1 + " / " + double2 + " / " + double3 + " = " + answer2);
break;
}
want it to loop after the code on top
}
private double promptForDouble(String prompt) {
double number1 = 0;
print(prompt);
String number = input();
try {
number1 = Double.parseDouble(number);
}
catch(NumberFormatException e){
print("That is not a number. Please enter a number.");
number1 = promptForDouble(prompt);
}
return number1;
}
private int promptForInt(String prompt) {
int number2 = 0;
print(prompt);
String number = input();
try {
number2 = Integer.parseInt(number); }
catch(NumberFormatException e) {
print("That is not an integer. Enter an integer.");
number2 = promptForInt(prompt); }
return number2;
}
public static void main(String[] args) {
new Calculator();
}
}
Put this in your main method:
while (true)
{
Thread.sleep(1000); // optional, make some deplay for more nature
new Calculator();
}
Or you can wrap all body blocks of the constructor inside the above while statement.

My program doesn't find the variable inside the if statement even when I've defined it outside the if statement(simple calculator)

I added a if statement that parses a entered number into a double to use when I do my calculations in the second if statement block, the program has to run if only numbers where entered and not letters, the program doesn't seem to read the numbers when I entered a double(5.5) but works fine when I enter a int(5) number/numbers.
Scanner numbers = new Scanner(System.in);
Scanner operation = new Scanner(System.in);
double number1 = 0;
double number2 = 0;
String operator;
System.out.print("Enter the operator you would like to choose(+, -, *, /): ");
operator = operation.next();
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
System.out.print("Enter your second number: ");
String num2 = numbers.nextLine();
boolean check1 = num1.trim().matches("^[0-9]+$");
boolean check2 = num2.trim().matches("^[0-9]+$");
if (check1 == true && check2 == true){
number1 = Double.parseDouble(num1);
number2 = Double.parseDouble(num2);
}else {
System.out.println("Only enter numbers not letters.");
}
String calculation;
if (operator.equals("+")){
calculation = (number1 + " + " + number2 + " = " + (number1 + number2));
System.out.println(calculation);
}else if (operator.equals("-")){
calculation = (number1 + " - " + number2 + " = " + (number1 - number2));
System.out.println(calculation);
}else if (operator.equals("*")){
calculation = (number1 + " * " + number2 + " = " + (number1 * number2));
System.out.println(calculation);
}else if (operator.equals("/")){
calculation = (number1 + " / " + number2 + " = " + (number1 / number2));
System.out.println(calculation);
}else{
calculation = operator + ":" + " Is not a valid operator!";
System.out.println(calculation);
}
I think its maybe the ( . ) thats the problem,
my output to console
Enter the operator you would like to choose(+, -, *, /): +
Enter the first number: 5.5
Enter your second number: 5.5
Only enter numbers not letters.
0.0 + 0.0 = 0.0
And now the int numbers that works fine.
Enter the operator you would like to choose(+, -, *, /): +
Enter the first number: 5
Enter your second number: 5
5.0 + 5.0 = 10.0
Do not use more than one Scanner object. There is no need for more than one, and this could also have some side effects you don't want to deal with.
Since you are using regular expression and others have suggested other solutions, I decided to show you how to use regular expression to evaluate a floating-point value. The correct expression for this is
[-+]?[0-9]*\\.?[0-9]+
or better yet...
[-+]?\\d*\\.?\\d+
This expression evaluates a value that may contain an optional sign (positive or negative) followed by zero or more digits, then followed by optional decimal point and an unlimited number of decimal digits. However, if the decimal point is used, at least one digit must be present. In a case like +2., only the +2 is matched.
The code below is your version of the solution, slightly modified:
public static void main(String[] args) {
final String REGEX = "[-+]?[0-9]*\\.?[0-9]+";
Scanner scanner = new Scanner(System.in);
double number1 = 0;
double number2 = 0;
String operator;
System.out.print("Enter the operator you would like to choose(+, -, *, /): ");
operator = scanner.next();
System.out.print("Enter the first number: ");
String num1 = scanner.next();
System.out.print("Enter your second number: ");
String num2 = scanner.next();
scanner.close();
boolean check1 = num1.trim().matches(REGEX);
boolean check2 = num2.trim().matches(REGEX);
if (check1 && check2) {
number1 = Double.parseDouble(num1);
number2 = Double.parseDouble(num2);
}else {
System.out.println("Only enter numbers not letters.");
}
String calculation;
switch (operator) {
case "+":
calculation = (number1 + " + " + number2 + " = " + (number1 + number2));
break;
case "-":
calculation = (number1 + " - " + number2 + " = " + (number1 - number2));
break;
case "*":
calculation = (number1 + " * " + number2 + " = " + (number1 * number2));
break;
case "/":
calculation = (number1 + " / " + number2 + " = " + (number1 / number2));
break;
default:
calculation = operator + ":" + " Is not a valid operator!";
break;
}
System.out.println(calculation);
}
The main differences are that I used only one Scanner object and that I replaced your nested if/else with a switch.
Below is a sample run
Enter the operator you would like to choose(+, -, *, /): +
Enter the first number: 5.5
Enter your second number: -7.2
5.5 + -7.2 = -1.7000000000000002
Other recommended improvements are:
Loop until a valid operator is provided. There is no reason to wait until all inputs are provided to then determine the calculation cannot be done due to invalid operator.
Do something similar to #1 above for each number.
Use BigDecimal the calculation.
Format the result to show however many decimal values you want to show.
The regular expression "^[0-9]+$" only evaluates to true for integers, because it checks whether the string consists of 0 - 9. If you want to check for doubles as well, this might help: https://www.baeldung.com/java-check-string-number
The first suggestion there is probably the easiest. Surround Double.parseDouble with a try catch, because it will give you an NumberFormatException if its not a number.

How to append every true if, else if statement to a text file?

How do I append every user chosen equation in an if, else if statement to a text file. I am not sure where would the best place be to put the append to file because putting it in under every else if statement seems repetitive.
import java.util.Formatter;
import java.util.Scanner;
public class javaCalculator {
public static void main(String[] args){
Scanner numbers = new Scanner(System.in);
Scanner operation = new Scanner(System.in);
double number1;
double number2;
String operator;
System.out.print("Enter the operator you would like to choose(+, -, *, /): ");
operator = operation.next();
System.out.print("Enter the first number: ");
number1 = Double.parseDouble(numbers.nextLine());
System.out.print("Enter your second number: ");
number2 = Double.parseDouble(numbers.nextLine());
if (operator.equals("+")){
String calculation = (number1 + " + " + number2 + " = " + (number1 + number2));
}else if (operator.equals("-")){
String calculation = (number1 + " - " + number2 + " = " + (number1 - number2));
}else if (operator.equals("*")){
String calculation = (number1 + " * " + number2 + " = " + (number1 * number2));
}else if (operator.equals("/")){
String calculation = (number1 + " / " + number2 + " = " + (number1 / number2));
}else{
String calculation = (operator + ":" + " Is not a valid operator!");
}
try {
Formatter file1 = new Formatter("C:\\Users\\27711\\Desktop\\PROGRAMMING\\java\\JavaCalculator");
file1.format(calculation);
}
catch (Exception e){
System.out.println("Error");
}
}
}
There are two problems here:
Attempting to use a variable when it isn't in scope
The way you're writing to a file using Formatter
Making the calculation variable available
All you need to do is declare your calculation variable once, before the if/else statements:
String calculation;
if (operator.equals("+")) {
calculation = number1 + " + " + number2 + " = " + (number1 + number2);
} else if (operator.equals("-")) {
calculation = number1 + " - " + number2 + " = " + (number1 - number2);
} else if (operator.equals("*")) {
String calculation = number1 + " * " + number2 + " = " + (number1 * number2);
} else if (operator.equals("/")) {
calculation = number1 + " / " + number2 + " = " + (number1 / number2);
} else {
calculation = operator + ":" + " Is not a valid operator!";
}
// Code to append to the file
In your current code, you're declaring a different variable in each if/else block, which means no calculation variable is in scope by the time you reach the file appending code.
An alternative approach would be to use a conditional operator. Some folks really don't like multiple uses like this, but I personally think it ends up being very readable:
String calculation =
operator.equals("+") ? number1 + " + " + number2 + " = " + (number1 + number2)
: operator.equals("-") ? number1 + " - " + number2 + " = " + (number1 - number2)
: operator.equals("*") ? number1 + " * " + number2 + " = " + (number1 * number2)
: operator.equals("/") ? number1 + " / " + number2 + " = " + (number1 / number2)
: operator + ":" + " Is not a valid operator!";
Alternatively, you might want to consider a switch statement, maybe in a whole separate method:
private static String calculate(String operator, double number1, double number2) {
switch (operator) {
case "+":
return number1 + " + " + number2 + " = " + (number1 + number2);
case "-":
return number1 + " - " + number2 + " = " + (number1 - number2);
case "*":
return number1 + " * " + number2 + " = " + (number1 * number2);
case "/":
return number1 + " / " + number2 + " = " + (number1 / number2);
default:
return operator + ":" + " Is not a valid operator!"
}
}
... or a switch expression if you're using a recent version of the language.
Writing to the file
The documentation for Formatter starts:
An interpreter for printf-style format strings.
While you can use a Formatter to write to a file, you don't want to interpret printf-style format strings at all... and you're currently not closing the formatter, either.
I'd suggest using the Files class instead. You can just write:
Files.write(Paths.get(filename), Arrays.asList(calculation));
To append, you can pass in StandardOpenOptions.APPEND:
Files.write(
// Where to write...
Paths.get(filename),
// The lines to write...
Arrays.asList(calculation),
// How to open the file...
StandardOpenOption.APPEND);

Java clarification on += assignment operator

I'm a bit confused about how += assignment operator works. I know that x += 1 is x = x+1. However, in this code there is a string variable called 'String output' and initialized with an empty string. My confusion is that that there are 5 different outputs for the variable 'output' but I don't see where it's being stored. Help clarify my misunderstanding. I can't seem to figure it out.
import java.util.Scanner;
public class SubtractionQuiz {
public static void main(String[] args) {
final int NUMBER_OF_QUESTIONS = 5; //number of questions
int correctCount = 0; // Count the number of correct answer
int count = 0; // Count the number of questions
long startTime = System.currentTimeMillis();
String output = " "; // Output string is initially empty
Scanner input = new Scanner(System.in);
while (count < NUMBER_OF_QUESTIONS) {
// 1. Generate two random single-digit integers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
// 2. if number1 < number2, swap number1 with number2
if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
// 3. Prompt the student to answer "What is number1 - number2?"
System.out.print(
"What is " + number1 + " - " + number2 + "? ");
int answer = input.nextInt();
// 4. Grade the answer and display the result
if (number1 - number2 == answer) {
System.out.println("You are correct!");
correctCount++; // Increase the correct answer count
}
else
System.out.println("Your answer is wrong.\n" + number1
+ " - " + number2 + " should be " + (number1 - number2));
// Increase the question count
count++;
output += "\n" + number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "
wrong");
}
long endTime = System.currentTimeMillis();
long testTime = endTime = startTime;
System.out.println("Correct count is " + correctCount +
"\nTest time is " + testTime / 1000 + " seconds\n" + output);
}
}
Answer given by Badshah is appreciable for your program and if you want to know more about operator' usability, jst check out this question i came across
+ operator for String in Java
The answers posted have very good reasoning of the operator
Its Add AND assignment operator.
It adds right operand to the left operand and assign the result to left operand.
In your case
output += someString // output becomes output content +somestring content.
`
Maybe the proper answer was written but if I understand your question correctly, you want some clarification instead of meaning of +=
Change the code;
// Increase the question count
count++;
output += "\n" + number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "wrong");
as this:
output += "\nCount: " + count + " and the others: " +
number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "wrong");
// Increase the question count
count++;
So you can see the line and the count together. Then increase as your wish.
In Java, Strings are immutable. So output += somethingNew makes something like this:
String temp = output;
output = temp + somethingNew;
At the end, it becomes something like concat/merge

Finding roots of quadratic equation

I have this code so far but every time i run and put the three numbers in a get the roots are NaN can some one please help or point me to where i went wrong.
import java.util.Scanner;
class Quadratic {
public static void main(String[] args) {
System.out.println("Enter three coefficients");
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
double root1= (-b + Math.sqrt( b*b - 4*a*c ) )/ (2*a);
double root2= (-b - Math.sqrt( b*b - 4*a*c ) )/ (2*a);
System.out.println("The roots1 are: "+ root1);
System.out.println("The roots2 are: " + root2);
}
}
You have to remember that not every quadratic equation has roots that can be expressed in terms of real numbers. More specifically, if b*b - 4*a*c < 0, then the roots will have an imaginary part and NaN will be returned, since Math.sqrt of a negative number returns NaN, as specified in the documentation. This works for coefficients such that b*b - 4*a*c >= 0, however:
Enter three coefficients
1
5
6
The roots1 are: -2.0
The roots2 are: -3.0
If you wanted to account for non-real roots as well, you could do something like
double d = (b * b - 4 * a * c);
double re = -b / (2 * a);
if (d >= 0) { // i.e. "if roots are real"
System.out.println(Math.sqrt(d) / (2 * a) + re);
System.out.println(-Math.sqrt(d) / (2 * a) + re);
} else {
System.out.println(re + " + " + (Math.sqrt(-d) / (2 * a)) + "i");
System.out.println(re + " - " + (Math.sqrt(-d) / (2 * a)) + "i");
}
Hope this helps--
import java.util.Scanner;
class QuadraticCalculator
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
double a,b,c,quad_dis,quad_11,quad_1,quad_21,quad_2;
System.out.println("Enter the value of A");
a=s.nextDouble();
System.out.println("\nEnter the value of B");
b=s.nextDouble();
System.out.println("\nEnter the value of C");
c=s.nextDouble();
quad_dis=b*b-4*a*c;
quad_11=(-1*b)+(Math.sqrt(quad_dis));
quad_1=quad_11/(2*a);
quad_21=(-1*b)-(Math.sqrt(quad_dis));
quad_2=quad_21/(2*a);
int choice;
System.out.println("\n\nWhat do you want to do with the numbers you entered ?\n(1) Calculate Discriminant\n(2) Calculate the values\n(3) Find the nature of roots\n(4) All of the above");
choice=s.nextInt();
switch(choice)
{
case 1: System.out.println("\nDiscriminant: "+quad_dis);
break;
case 2: System.out.println("\nValues are: "+quad_1+", "+quad_2);
break;
case 3: if(quad_dis>0)
{
System.out.println("\nThe roots are REAL and DISTINCT");
}
else if(quad_dis==0)
{
System.out.println("\nThe roots are REAL and EQUAL");
}
else
{
System.out.println("\nThe roots are IMAGINARY");
}
break;
case 4: System.out.println("\nDiscriminant: "+quad_dis);
System.out.println("\nValues are: "+quad_1+", "+quad_2);
if(quad_dis>0)
{
System.out.println("\nThe roots are REAL and DISTINCT");
}
else if(quad_dis==0)
{
System.out.println("\nThe roots are REAL and EQUAL");
}
else
{
System.out.println("\nThe roots are IMAGINARY");
}
break;
}
System.out.println("\n\nThank You for using this Calculator");
}
}
You could use the following code. First, it will check whether input equation is quadratic or not. And if input equation is quadratic then it will find roots.
This code is able to find complex roots too.
public static void main(String[] args) {
// Declaration of variables
float a = 0, b = 0, c = 0, disc, sq_dis;
float[] root = new float[2];
StringBuffer number;
Scanner scan = new Scanner(System.in);
// Input equation from user
System.out.println("Enter Equation in form of ax2+bx+c");
String equation = scan.nextLine();
// Regex for quadratic equation
Pattern quadPattern = Pattern.compile("(([+-]?\\d*)[Xx]2)+((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*|((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*(([+-]?\\d*)[Xx]2)+|((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*(([+-]?\\d*)[Xx]2)+((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*");
Matcher quadMatcher = quadPattern.matcher(equation);
scan.close();
// Checking if given equation is quadratic or not
if (!(quadMatcher.matches())) {
System.out.println("Not a quadratic equation");
}
// If input equation is quadratic find roots
else {
// Splitting equation on basis of sign
String[] array = equation.split("(?=[+-])");
for (String term : array) {
int len = term.length();
StringBuffer newTerm = new StringBuffer(term);
// If term ends with x2, then delete x2 and convert remaining term into integer
if (term.endsWith("X2") || (term.endsWith("x2"))) {
number = newTerm.delete(len - 2, len);
a += Integer.parseInt(number.toString());
}
// If term ends with x, then delete x and convert remaining term into integer
else if (term.endsWith("X") || (term.endsWith("x"))) {
number = newTerm.deleteCharAt(len - 1);
b += Integer.parseInt(number.toString());
}
// If constant,then convert it into integer
else {
c += Integer.parseInt(term);
}
}
// Display value of a,b,c and complete equation
System.out.println("Coefficient of x2: " + a);
System.out.println("Coefficient of x: " + b);
System.out.println("Constent term: " + c);
System.out.println("The given equation is: " + a + "x2+(" + b + ")x+(" + c + ")=0");
// Calculate discriminant
disc = (b * b) - (4 * a * c);
System.out.println(" Discriminant= " + disc);
// square root of discriminant
sq_dis = (float) Math.sqrt(Math.abs(disc));
// conditions to find roots
if (disc > 0) {
root[0] = (-b + sq_dis) / (2 * a);
root[1] = (-b - sq_dis) / (2 * a);
System.out.println("Roots are real and unequal");
System.out.println("Root1= " + root[0]);
System.out.println("Root2= " + root[1]);
}
else if (disc == 0) {
root[0] = ((-b) / (2 * a));
System.out.println("Roots are real and equal");
System.out.println("Root1=Root2= " + root[0]);
}
else {
root[0] = -b / (2 * a);
root[1] = Math.abs((sq_dis) / (2 * a));
System.out.println("Roots are complex");
System.out.println("ROOT1= " + root[0] + "+" + root[1] + "+i");
System.out.println("ROOT2= " + root[0] + "-" + root[1] + "+i");
}
}
else {
if ((Math.sqrt(-d) / (2*a)) > 0) {
System.out.println(r + " + " + (Math.sqrt(-d) / (2*a)) + " i");
System.out.println(r + " - " + (Math.sqrt(-d) / (2*a)) + " i");
}
else if ((Math.sqrt(-d) / (2*a)) == 0){
System.out.println(r);
}
else {
System.out.println(r + " - " + (Math.sqrt(-d) / (2*a)) + " i");
System.out.println(r + " + " + (Math.sqrt(-d) / (2*a)) + " i");
}

Categories

Resources