Clumsy Java Calc that won't compile - java

I'm a newbie at programming, so that this piece of code keeps me scratching my head as it won't compile. Net Beans suggests to add return 0 and afterwards the code compiles successfully. However, the part after the printing to console Anything else to calculate? couldn't handle the input properly, displaying Please, enter a valid answer regardless of the input data.
package calc;
import java.util.Scanner;
public class Calc {
public static void main(String[] args){
Calculator();
}
static double sum (double val1, double val2){
return val1 + val2;
}
static double substract (double val1, double val2) {
return val1 - val2;
}
static double multiply (double val1, double val2) {
return val1 * val2;
}
static double divide (double val1, double val2) {
return val1 / val2;
}
public static double Calculator(){
Scanner reader = new Scanner(System.in);
System.out.println(" Enter the first number, please");
double x = reader.nextDouble();
System.out.println("Enter the second number, please");
double y = reader.nextDouble();
System.out.println("Enter desired operation, please");
char z = reader.next().charAt(0);
switch(z)
{
case '+':
double a = sum(x,y);
System.out.println(a);
break;
case '-':
double b = substract(x,y);
System.out.println(b);
break;
case '*':
double c = multiply(x,y);
System.out.println(c);
break;
case '/':
double d = divide (x,y);
System.out.println(d);
break;
}
System.out.println("Anything else to calculate?");
Scanner reader2 = new Scanner(System.in);
String Answer = reader2.nextLine();
if (Answer == "yes") {
Calculator();
} else if (Answer == "no") {
System.out.println("Thank you for using our Calculator app");
} else {
System.out.println("Please, enter a valid answer");
}
}

You don't compare strings using == instead you use equals() or even better in this case equalsIgnoreCase
if (Answer.equalsIgnoreCase("yes")) {
Calculator();
} else if (Answer.equalsIgnoreCase("no")) {
System.out.println("Thank you for using our Calculator app");
}

Dear as the function Calculator is having a double return type so any how it should return a double value.But as per your code you are not returning anything
and simply printing the result in console so no need of defining the return type of function to double mark it as void.I hope this will make you understand the concept.

Related

i cant get my calculator to work

i want to input a int to get first number then use a string to get the operator and another int for the second number. user should input some thing like 10+20.
but as soon as i enter the "+" then i get an error why?
cuz it works if i manually add the values into the sum.calc(); myself like sum.calc(12, "+", 24); then it works ill get 36
PART 1:
import java.util.Scanner;
public static void main(String[] args) {
math sum = new math();
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
String b = input.nextLine();
double c = input.nextDouble();
sum.calc(a, b, c);
input.close();
}
PART 2:
public class math {
public void calc(double a, String b, double c){
double t;
switch(b){
case "+":
t = a + c;
System.out.println(a+" + "+c+" = "+t);
break;
case "-":
t = a - c;
System.out.println(a+" - "+c+" = "+t);
break;
case "*":
t = a * c;
System.out.println(a+" * "+c+" = "+t);
break;
case "/":
t = a / c;
System.out.println(a+" / "+c+" = "+t);
break;
}
}
}
Try using input.next(); instead of input.nextLine(); Because input.nextLine(); advances this scanner past the current line and returns the input that was skipped. so if your input was 20, +, and 24, your method calc would get 20,24,null.
input.next() works instead of input.nextLine() for strings.Try it out

A Memory Calculator Program

I have this program that asks user to enter a value and it calculates it as the user like to initial value of zero, then it ask the user what process to do again and ask the user to enter a value again and it calculates it to the last value of the instance, the problem is every time it asks the user to enter value it calculates it to zero not to the last entry. Please help me find the bug:
The program has to has two classes, one for the calculator and the other for the methods:
FIRST CLASS
public class MainClass {
public static void main(String[] args) {
MemoryCalculator calc = new MemoryCalculator();
calc.getCurrentValue();
displayMenu();
}
public static int displayMenu() {
Scanner input = new Scanner(System.in);
int choice;
do {
System.out.println("Menu");
System.out.println("1.Add");
System.out.println("2.Subtract");
System.out.println("3.Multiply");
System.out.println("4.Divide");
System.out.println("5.Clear");
System.out.println("6.Quit");
System.out.println("");
System.out.println("What would you like to do?");
choice = input.nextInt();
if (choice > 6 || choice < 1) {
System.out.println("Sorry," + choice + " was not an option");
return displayMenu();
}
} while (choice > 6 || choice < 1);
MemoryCalculator calc = new MemoryCalculator();
if (choice == 5) {
calc.clear();
return 0;
} else if (choice == 6) {
System.out.println("Goodbye! ");
System.exit(0);
}
System.out.println("What is the second number? ");
double operand2 = input.nextDouble();
switch (choice) {
case 1:
calc.add(operand2);
break;
case 2:
calc.subtract(operand2);
break;
case 3:
calc.multiply(operand2);
break;
case 4:
calc.divide(operand2);
break;
}
return displayMenu();
}
public static double getOperand(String prompt) {
return 0;
}
}
SECOND CLASS
public class MemoryCalculator {
private double currentValue;
public double getCurrentValue() {
System.out.println("The current value is " + currentValue);
return 0;
}
public void add(double operand2) {
currentValue = currentValue + operand2;
getCurrentValue();
}
public void subtract(double operand2) {
currentValue -= operand2;
getCurrentValue();
}
public void multiply(double operand2) {
currentValue *= operand2;
getCurrentValue();
}
public void divide(double operand2) {
if (operand2 == 0) {
System.out.println("Sorry, you can not divide by 0");
}
currentValue /= operand2;
getCurrentValue();
}
public void clear() {
currentValue = 0;
getCurrentValue();
}
}
You probably want to keep the last value stored in "calc". I see 3 bugs.
Move this line before the start of your "do" loop. This will keep it from reseting the value inside this variable/class.
MemoryCalculator calc = new MemoryCalculator();
Move your ending "while" loop line to the bottom of your method(right before the return statement). It only appears to be working because in your return statement you are calling your method again...see #3. Also you will want to change the "or" to the "and" operator in the while statement "choice>6 && choice<1"
}while(choice>6 && choice<1);
In you displayMenu method change the return statement, because you don't want it to call itself in an infinite loop... now that the do while loop is fixed.
return displayMenu();
to this
return choice;

Why does my calculator automatically answer "0" before i can put my sign in?

Somewhere around line 15 it gives me issues.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //scanner object created
System.out.println("Enter your first number");
int nr1 = sc.nextInt();
System.out.println("Enter your second number");
int nr2 = sc.nextInt();
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
int ans = 0;
//somewhere around this line is where it is having the problems. it gives me the answer before i can put in my sign;
if(anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
}
else if(anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
}
else if(anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
}
else if(anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
}
System.out.println(ans);
System.out.println("To continue type yes");
String yes= sc.nextLine();
if(yes.equalsIgnoreCase("yes")) {
return;
}
}
}
it answers "0" whatever I enter before I can put in my sign
Enter your first number
9
Enter your second number
9
Enter your sign (+ , - , /, *)
0
To continue type yes
please tell me what I did wrong and possibly correct it so I can understand further
Try changing your sc.nextInt() lines to Integer.parseInt(sc.nextLine()). This should make your code work correctly.
EDIT: updated the code to include a while loop to make it so you can do multiple runs per your comment. This would also require you changing your last if statement to break; instead of return;
Scanner sc = new Scanner(System. in ); //scanner object created
while (true) {
System.out.println("Enter your first number");
int nr1 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your second number");
int nr2 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
int ans = 0;
//somewhere around this line is where it is having the problems. it gives me the answer before i can put in my sign;
if (anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
} else if (anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
} else if (anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
} else if (anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
}
System.out.println(ans);
System.out.println("To continue type yes");
String yes = sc.nextLine();
if (!yes.equalsIgnoreCase("yes")) {
break;
}
}
Change
String anvin = sc.nextLine();
to
String anvin = sc.next();
Also keep in mind that you might divide through zero ;-)
Edit:
also change
String yes= sc.nextLine();
to
String yes= sc.next();
Instead of sc.nextLine(); use sc.next();
I would suggest you this, you can not only learn using objects but learn a better way of writing managed codes too,
Calculator.java -> a class
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
//Instantiate
Scanner input = new Scanner(System.in);
Calculations calc = new Calculations();
// Variable declarations
double answer = 0, entry1 , entry2 ;
char operator;
// Start
System.out.println("***** Welcome to the Command line calculator program *****");
System.out.print("Please enter the first number :");
entry1 = input.nextDouble();
System.out.print("Please enter the second number:");
entry2 = input.nextDouble();
System.out.println("Please enter the operation : ");
System.out.println("***** Operations :- + -> Add ; - ->Substract ; / -> Divide ; * -> Multiply ; ^ : Power *****");
operator = input.next().charAt(0);
// Switch case
switch (operator){
case '+' : answer = calc.add(entry1, entry2);
break;
case '-' : answer = calc.substract(entry1, entry2);
break;
case '/' : answer = calc.divide(entry1, entry2);
break;
case '*' : answer = calc.multiply(entry1, entry2);
break;
case '^' : answer = calc.power(entry1, entry2);
break;
}
System.out.println(entry1 + " " + operator + " " + entry2 + " = " + answer);
}
}`
Calculations.java -->another class holding calculations
import java.math.*;
public class Calculations {
// Addition Method
double add (double first, double second){
double answer = first + second;
return answer;
}
// Substraction Method
double substract (double first, double second){
double answer = first - second;
return answer;
}
// Multiplication Method
double multiply (double first, double second){
double answer = first * second;
return answer;
}
// Division Method
double divide (double first, double second){
double answer = first / second;
return answer;
}
// Power Method
double power(double a, double b){
double answer =Math.pow(a, b);
return answer;
}
}

How can I do one-operand math with my Java calculator?

I have been trying to create a simple calculator in Java for a while now, and I have successfully been able to make the program work with two-operand equations (+, -, *, /, and ^). However, I was wondering how I would be able to do one-operand math problems - absolute value(using the symbol "|"), square root (using the symbol 'v'), rounding to the closest integer (using the symbol '~'), sin (s), cos (c), and tangent (t).
I have attempted the absolute value operand which can be seen in:
if (operator == '|') {
answer = Math.abs(numA);
}
// In the main class
and:
double absolute(double a) {
double answer = Math.abs(a);
return answer;
}
// In the maths class
This code only works if you enter in values for example like this: -3 | -3 (Note: I have noticed that it is only the first number that the absolute value operation is performed upon. The second number can be whatever you want (if you entered -3 | -4 your answer would still be 3) as long as it is, indeed, a number.
Any help for solving this problem and help figuring out the other single-operand operations would be greatly appreciated!
Thanks in advance!
The source code for my program is below:
package calculator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
System.out.println("Hello, welcome to my calculator");
System.out.println("Enter in some stuff you want to me to calculate");
Scanner scan = new Scanner(System.in);
System.out.println("If you need help please type \"help\"");
System.out.println("If at anytime you want to leave, type \"quit\"");
System.out.println("Hit enter to continue.");
String s1 = scan.nextLine();
if (s1.equals("help")){
System.out.println(" ");
System.out.println("Double operand commands:");
System.out.println("Addition: '+' (Ex: 'a + b' )");
System.out.println("Subtraction: '-' (Ex: 'a - b' )");
System.out.println("Multiplication: '*' (Ex: 'a * b' ) ");
System.out.println("Division: '/' (Ex: 'a / b' )");
System.out.println("Exponents: '^' (Ex: 'a ^ b' )");
System.out.println(" ");
}
Scanner input = new Scanner(System.in);
Maths maths = new Maths();
double answer = 0;
double numA, numB;
char operator;
boolean quit = false;
while (true) {
System.out.print("Please enter your equation: ");
String s=input.next();
if(s.equals("quit")){
System.out.println("Thank you for using my program!");
System.exit(0);
}
numA = Double.parseDouble(s);
operator = input.next().charAt(0);
numB = input.nextDouble();
if (operator == '+') {
answer = maths.add(numA, numB);
}
if (operator == '-') {
answer = maths.subtract(numA, numB);
}
if (operator == '*') {
answer = maths.multiply(numA, numB);
}
if (operator == '/') {
answer = maths.divide(numA, numB);
}
if (operator == '^') {
answer = maths.power(numA, numB);
}
if (operator == '|') {
answer = Math.abs(numA);
}
System.out.println(answer);
}
}
}
class Maths {
double add(double a, double b) {
double answer = a+b;
return answer;
}
double subtract(double a, double b) {
double answer = a-b;
return answer;
}
double multiply(double a, double b) {
double answer = a*b;
return answer;
}
double divide(double a, double b) {
double answer = a/b;
return answer;
}
double power(double a, double b){
double answer =a;
for (int x=2; x<=b; x++){
answer *= a;
}
return answer;
}
double absolute(double a) {
double answer = Math.abs(a);
return answer;
}
}
I did some modification in your existing code so that it can suit in all cases and allow future extension of functions. You can understand the changes through comments. Also, the code will be able to run, if user provide only one input for functions, where only single parameter is enough. I did not change any of your functions.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
System.out.println("Hello, welcome to my calculator");
System.out.println("Enter in some stuff you want to me to calculate");
Scanner scan = new Scanner(System.in);
System.out.println("If you need help please type \"help\"");
System.out.println("If at anytime you want to leave, type \"quit\"");
System.out.println("Hit enter to continue.");
String s1 = scan.nextLine();
if (s1.equals("help")) {
System.out.println(" ");
System.out.println("Double operand commands:");
System.out.println("Addition: '+' (Ex: 'a + b' )");
System.out.println("Subtraction: '-' (Ex: 'a - b' )");
System.out.println("Multiplication: '*' (Ex: 'a * b' ) ");
System.out.println("Division: '/' (Ex: 'a / b' )");
System.out.println("Exponents: '^' (Ex: 'a ^ b' )");
System.out.println(" ");
} else if (s1.equals("quit")) {
System.out.println("Thank you for using my program!");
System.exit(0);
}
Scanner input = new Scanner(System.in);
Maths maths = new Maths();
double answer = 0;
double numA=0.0, numB=0.0;
char operator;
boolean quit = false;
while (true) {
System.out.print("Please enter your equation: ");
//First scan the function as a string
String s = input.next();
if (s.equals("quit")) {
System.out.println("Thank you for using my program!");
System.exit(0);
}
//We will use regex to find the operator, so we will omit all alphabetic letter or numeric number or decimal
String operator1 = s.replaceAll("[a-zA-Z0-9.]","");
//For functions like -4|, the operator1 will be -| after replacing through regex, we will only take the second digit as operator to prevent error
if(operator1.length()==1)
operator = operator1.charAt(0);
else
operator = operator1.charAt(1);
String[] num11 = (s.split("[^0-9,.]"));
//String array num11 may contain null string after splitting using regex, we will remove those null string and store only variable values in an arraylist
ArrayList<String> arraylist = new ArrayList<String>();
for (int i = 0; i < num11.length; i++)
{
if (!num11[i].equals(""))
{
arraylist.add(num11[i]);
}
}
if(arraylist.size()==1){
numA = Double.parseDouble(arraylist.get(0));
numB=numA;}
else if(arraylist.size()==2){
numA = Double.parseDouble(arraylist.get(0));
numB = Double.parseDouble(arraylist.get(1));
}
if (operator == '+') {
answer = maths.add(numA, numB);
}
if (operator == '-') {
answer = maths.subtract(numA, numB);
}
if (operator == '*') {
answer = maths.multiply(numA, numB);
}
if (operator == '/') {
answer = maths.divide(numA, numB);
}
if (operator == '^') {
answer = maths.power(numA, numB);
}
if (operator == '|') {
answer = Math.abs(numA);
}
System.out.println(answer);
}
}
public static class Maths {
public void Maths(){};
double add(double a, double b) {
double answer = a + b;
return answer;
}
double subtract(double a, double b) {
double answer = a - b;
return answer;
}
double multiply(double a, double b) {
double answer = a * b;
return answer;
}
double divide(double a, double b) {
double answer = a / b;
return answer;
}
double power(double a, double b) {
double answer = a;
for (int x = 2; x <= b; x++) {
answer *= a;
}
return answer;
}
double absolute(double a) {
double answer = Math.abs(a);
return answer;
}
}
}
Output:
Please enter your equation: +4+4
8.0
Please enter your equation: 4+4
8.0
Please enter your equation: 4+3
7.0
Please enter your equation: 4-3
1.0
Please enter your equation: 4/3
1.3333333333333333
Please enter your equation: -4|
4.0
Please enter your equation: 4|
4.0
Please enter your equation: 3^2
9.0
Use a regular expression to check whether first number is actually a number. Then do what you want to do accordingly. Additionally, you can handle erroneous user inputs using regular exceptions. So you won't have java.lang.NumberFormatExceptions if you enter "3+3"
if (s.matches("^[-+]?[0-9]*\\.?[0-9]+$")) { //Check whether first number is actually a number
numA = Double.parseDouble(s);
operator = input.next().charAt(0);
numB = input.nextDouble();
} else {
operator = s.charAt(0);
numA = input.nextDouble();
numB = 0;
}

Error in simple java program

I am working on teaching myself java and while working on a code using classes I ran into this error
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at StateCalculator.getOperand(StateCalculator.java:29)
at StateCalculator.main(StateCalculator.java:77)
Below is my code:
import java.util.Scanner;
public class StateCalculator {
private double currentValue = 0;
//Initialize to 0
public StateCalculator() {
}
public static int displayMenu() {
Scanner keyboard = new Scanner(System.in);
int menuChoice = 0;
do {
System.out.print("Menu\n 1. Add\n 2. Subtract\n 3. Multiply\n 4. Divide\n 5.Clear\n 6. Quit\n What would you like to do?: ");
menuChoice = keyboard.nextInt();
} while(menuChoice < 1 || menuChoice > 6);
keyboard.close();
return menuChoice;
}
public static double getOperand(String prompt) {
Scanner input = new Scanner(System.in);
double operand = 0;
System.out.print(prompt);
operand = input.nextDouble();
input.close();
return operand;
}
public double getCurrentValue() {
return currentValue;
}
public void add(double operand) {
currentValue += operand;
}
public void subtract(double operand) {
currentValue -= operand;
}
public void multiply(double operand) {
currentValue *= operand;
}
public void divide(double operand) {
if(operand == 0) {
currentValue = Double.NaN;
}
else {
currentValue /= operand;
}
}
public void clear() {
currentValue = 0;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
StateCalculator calculator = new StateCalculator();
int option;
double operand;
do{
System.out.println("The current value is " + calculator.currentValue);
option = StateCalculator.displayMenu();
switch(option) {
case 1:
operand = getOperand("What is the second number?: ");
calculator.add(operand);
break;
case 2:
operand = getOperand("What is the second number?: ");
calculator.subtract(operand);
break;
case 3:
operand = getOperand("What is the second number?: ");
calculator.multiply(operand);
break;
case 4:
operand = getOperand("What is the second number?: ");
calculator.divide(operand);
break;
case 5:
calculator.clear();
break;
}
}while(option != 6);
keyboard.close();
}
}
I tried running the debug feature in eclipse and discovered the problem occurs on line 29 in my getOperand method when I attempt to set operand = input.nextDouble. However, I don't understand why this would be an issue.
Don't call keyboard.close(); when you close keyboard (which you defined)
Scanner keyboard = new Scanner(System.in);
it closes System.in, and then your other methods can't work (because the console will not re-open). You can have multiple scanners on System.in (as long as you don't close them), or pass one (or, but please don't, use a global).
Per the javadoc,
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

Categories