I try to calculate digits (in my calculator) in args from commandline. Example:
args[0] = 2*3;
String result = method(args[0]);
System.out.println(result) // should be 6
I don't know how to use my char between two digits example "+", "-". I can't use loops. My method idea is use charAt like:
char a = arg.charAt(0);
char b = arg.charAt(1);
char c = arg.charAt(2);
But I don't know to change my b char (*) to do calculation.
You are not passing the value correctly. Your input is a String, right? Your code shows an integer expression.
args[0] = "2*3"; //note that this changed to a string
double result = parse(args[0]);
System.out.println(result) // should be 6
Then you can parse your string in your method:
double parse(String str){
int num1 = Integer.valueOf(str.substring(0,1));
char operator = str.charAt(1);
int num2 = Integer.valueOf(str.substring(2,3));
switch(operator){
case '+': return num1+num2;
case '-': return num1-num2;
case '*': return num1*num2;
case '/': return num1/num2;
default: throw new IllegalArgumentException();
}
}
Running System.out.println(parse("2*3")); prints 6.0 with my code.
Of course this only works with operands that have exactly one digit. But that's a restriction that comes from your charAt idea.
I'm not normally using JAVA, but..
You will get the input as a string, if you run a process like this:
> MyCalculator 2*3
now, you want to separate this string into three parts:
Number1, Operation, Number2
for this you can do something like:
String[] parts = args[0].split("\\*");
Double Number1 = Double.parseDouble( parts[0])
Double Number2 = Double.parseDouble( parts[1])
now, you may notice that you'll be missing the operator..
so you want locate it and fetch it, or you can do something like this:
if( args[0].indexOf("*") > -1)
{
System.out.println(Number1 * Number2);
}
edit:
for more flexibillity, you may want to do it the opposite way around:
if( args[0].indexOf("*") > -1)
{
String[] parts = args[0].split("\\*");
Double Number1 = Double.parseDouble( parts[0])
Double Number2 = Double.parseDouble( parts[1])
System.out.println(Number1 * Number2);
}
if( args[0].indexOf("/") > -1)
{
String[] parts = args[0].split("/");
Double Number1 = Double.parseDouble( parts[0])
Double Number2 = Double.parseDouble( parts[1])
System.out.println(Number1 / Number2);
}
etc...
notice that "-" will be especially annoying
Its not the best solution but it works, you can enter numbers of any length.
String[] number = args[0].split("[*]|[/]|[+]|[-]");
int stringLength = args[0].length();
int operatorBeginning = number[0].length();
int operatorEnd = stringLength - number[1].length();
String operator = args[0].substring(operatorBeginning,operatorEnd);
double answer = 0;
switch(operator) {
case "*":
answer = Integer.valueOf(number[0]) * Integer.valueOf(number[1]);
break;
case "/":
answer = Integer.valueOf(number[0]) / Integer.valueOf(number[1]);
break;
case "+":
answer = Integer.valueOf(number[0]) + Integer.valueOf(number[1]);
break;
case "-":
answer = Integer.valueOf(number[0]) - Integer.valueOf(number[1]);
break;
default:
System.out.println("Wrong operator");
break;
}
System.out.println(answer);
Related
My calculator, that I needed to make for my test task to apply for a Java course, is working great. But there's an issue I would like to resolve. If you type in, for example, "5+3" as opposed to "5 + 3", it doesn't work. Can my calculator be smart enough to delimit input without explicit delimiters (like spaces)?
In other words, how do I make my scanner split, for example, an input of 5+32 *2 into five tokens: 5, +, 32, *, and 2? If I don't have to overhaul my entire code, that would be even better!
import java.util.Scanner;
import java.io.IOException;
import java.text.DecimalFormat;
public class Introduction {
private static double firstNum;
private static double secondNum;
private static double result;
private static boolean dontKnow;
private static String firstNumS;
private static String secondNumS;
private static String operationS;
private static final DecimalFormat df = new DecimalFormat("#.##");
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
firstNumS = scanner.next();
operationS = scanner.next();
secondNumS = scanner.next();
if(firstNumS.compareTo(operationS) > 15){
switch(firstNumS){
case "I":
firstNum = 1;
break;
case "II":
firstNum = 2;
break;
case "III":
firstNum = 3;
break;
case "IV":
firstNum = 4;
break;
case "V":
firstNum = 5;
break;
case "VI":
firstNum = 6;
break;
case "VII":
firstNum = 7;
break;
case "VIII":
firstNum = 8;
break;
case "IX":
firstNum = 9;
break;
case "X":
firstNum = 10;
break;
default:
System.out.println("I don't know the first number!");
dontKnow = true; }}
else {
firstNum = Integer.decode(firstNumS);
if(firstNum > 10){
System.out.println("It appears, the first number is too big for me!");
dontKnow = true;
}
}
if(secondNumS.compareTo(operationS) > 15) {
switch(secondNumS){
case "I":
secondNum = 1;
break;
case "II":
secondNum = 2;
break;
case "III":
secondNum = 3;
break;
case "IV":
secondNum = 4;
break;
case "V":
secondNum = 5;
break;
case "VI":
secondNum = 6;
break;
case "VII":
secondNum = 7;
break;
case "VIII":
secondNum = 8;
break;
case "IX":
secondNum = 9;
break;
case "X":
secondNum = 10;
break;
default:
System.out.println("I don't know the second number!");
dontKnow = true; }}
else {
secondNum = Integer.decode(secondNumS);
if(secondNum > 10) {
System.out.println("It appears, the second number is too big for me!");
dontKnow = true; }}
if(operationS.equals("+")) {
result = firstNum + secondNum; }
else if(operationS.equals("-")) {
result = firstNum - secondNum; }
else if(operationS.equals("*")){
result = firstNum * secondNum; }
else if(operationS.equals("/")){
result = firstNum / secondNum; }
else {
System.out.println("I don't know such an operation!");
dontKnow = true; }
if(!(operationS.equals("/") && secondNum == 0)) {
if(!dontKnow) {
if(result / (int)result != 1) {
if(String.valueOf(result).equals(df.format(result))) {
System.out.println("It's " + result + "!"); }
else {
System.out.println("It's approximately " + df.format(result) + "!"); }}
else {
System.out.println("It's " + (int)result + "!"); }}}
else {
if(!dontKnow) {
System.out.println("Gosh! I tried to divide it by zero, as you requested, but my virtual head nearly exploded! I need to recover..."); }
else {
System.out.println("Besides, you can't even divide by zero, I'm so told!"); }}
}
}
Assuming you're using scanner, yes, it could. The scanner operates on the notion that a regexp serves as delimiter: Each match of the regex delimits, and whatever the regexp matches is tossed out (because nobody 'cares' about reading the spaces or the commas or whatever). The scanner then gives you stuff in between the delimiters.
Thus, for you to end up with scanner stream '5', '+', and '3', you want a delimiter that delimits on the space between '5' / '+' and '+' / '3', whilst matching 0 characters otherwise those would be thrown out.
You can do that, using regexp lookahead/lookbehind. You want a digit to the left and an operator to the right, or vice versa:
String test = "53 + 2*35- 8";
Scanner s = new Scanner(test);
s.useDelimiter("\\s+|(?:(?<=\\d)(?=[-+/*]))|(?:(?=\\d)(?<=[-+/*]))");
while (s.hasNext()) {
System.out.println("NEXT: '" + s.next() + "'");
}
To break that convoluted regex open:
A|B|C means: A or B or C. That's the 'outermost' part of this regexp, we're looking for one of 3 distinct things to split on.
\\s+ means: 1 or more whitespace characters. Thus, input "5 20" would be split into 5 and 20. The whitespace is consumed (i.e. tossed out and not part of your tokens).
OR, positive lookbehind ((?<=X) means: Match if, looking backwards, you would see X), and X is \\d here - a digit. We then also have a positive lookahead: (?=X) means: Check for X being here, but don't consume it (or it would be thrown out, remember, the regex describes the delimiter, and the delimiter is thrown out). We look ahead for one of the symbols.
OR, that, but flipped about (first an operator, then a digit).
NB: If you want to avoid the complexity of a regexp, you could just loop through each character, but you'd be building a little state machine, and have to take care of consecutive, non-space separated digits: You need to combine those (10 + 20 is not 1, 0, +, 2, 0 - it's 10 + 20).
NB2: If you also want to support ( and ) you can edit the regex appropriately (They are, essentially, 'operators' and go in the list of operators), however, at some point you're essentially descriving a grammar for a formal language and should start looking into a parser generator. But that's all vastly more complicated than any of this.
I need help with my coding. I am practicing again with my java programming and today I am creating a calculator that has the same function as the real calculator but again I run into errors and unable to figure out again.
Okay, the way I wanted my calculator to works is instead of getting line by line input from the user like this:-
In code output
Enter Number: 1
Enter Operator (+,-, /, *, ^ (Power) or s (Square): +
Enter Number: 2
Ans: 3
I wanted it to calculate when the user press enter like this:-
The Output that I want
enter number: 1+2*4
Ans: 12
So they can add as many long numbers as they want before they hit enter calculate. The users are supposed to be able to reset the number to when using the calculator while in the loop of the calculation.
at the beginning of the code, it will ask the user for an input to continue or exit the calculator. Then if continue it will run the calculation. The calculator will be looping until the users press E to exit the calculator and if exit it will exit the code.
This is where I have errors. First, I can't figure out how to break from the loop inside the looping calculator and second at the beginning of the code when the user press E it was supposed to exit the calculator but it didn't. The third error is when the user using the square to calculate I want it to get straight to show the answer instead of asking another number.
and I want to simplify the code in public static void main(String[] args)for the calculation part. Is it possible to put the switch case in method and call it inside the main? or do you have a suggestion on how to simplify the calculation part?
Please help me:(
public class TestingCalculator {
public static void main(String[] args){
double answer = 0;
double numA, numB;
char operator;
char activateCalc;
boolean calculator = false;
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
Scanner ans = new Scanner(System.in);
String a = ans.next();
activateCalc = a.charAt(0);
while (activateCalc != 'E' || activateCalc != 'e') {
Scanner input = new Scanner(System.in);
System.out.print("Enter number: ");
String n =input.next();
numA = Double.parseDouble(n);
while (calculator = true) {
//User enter their operator.
System.out.print("Enter Operator (+,-, /, *, ^ (Power) or s (Square): ");
operator = input.next().charAt(0);
System.out.print("Enter number: "); //User enter the continues number
numB = input.nextDouble();
switch (operator) {
case '=':
System.out.print(answer);
break;
case '+':
answer = add(numA,numB);
break;
case '-':
answer =subtract(numA,numB);
break;
case '*':
answer = multiply(numA,numB);
break;
case '/':
answer = divide(numA,numB);
break;
case '^':
answer = power(numA, numB);
break;
case 's':
case 'S':
answer = Math.pow(numA, 2);
break;
}
//The calculation answer of the user input
System.out.println("Answer: " + answer);
numA = answer;
// to exit calculator.
System.out.println("Press E to Exit the calculator: ");
if (activateCalc = 'E' || activateCalc = 'e') {
break;
}
}
}
ans.close();
}
//Method for the operators.
static double add(double numA, double numB) {
double answer = numA + numB;
return answer;
}
static double subtract(double numA, double numB) {
double answer = numA - numB;
return answer;
}
static double multiply(double numA, double numB) {
double answer = numA * numB;
return answer;
}
static double divide(double numA, double numB) {
double answer = numA / numB;
return answer;
}
static double power(double numA, double numB) {
int answer = (int) Math.pow(numA, numB);
return answer;
}
static double Square(double numA, double numB) {
int answer = (int) Math.pow(numA, 2);
return answer;
}
}
Instead of trying to identify the problems with your application, I decided to focus on producing a program that works the way you want (with the input you specified). The code was a little big, but I tried to leave it well commented for you to understand what I did. I know that some things may still be a little confusing, so I will simulate running the program to try to make it clearer how it works.
Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestingCalculator
{
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Evaluates a mathematical expression.
*
* #param line Mathematical expression. This line cannot have blank
* spaces
* #return Result of this mathematical expression
*/
public static String calc(String line)
{
while (!hasOnlyNumbers(line)) {
// Checks if line has parentheses
if (line.contains("(")) {
// Get index of the most nested parentheses
int parentheses_begin = line.lastIndexOf("(");
int parentheses_end = line.substring(parentheses_begin).indexOf(")");
String ans = calc(line.substring(parentheses_begin+1, parentheses_end));
// Replaces content of parentheses with the result obtained
if (line.length()-1 >= parentheses_end+1)
line = line.substring(0,parentheses_begin)+ans+line.substring(parentheses_end+1);
else
line = line.substring(0,parentheses_begin)+ans;
}
// Checks if line has potentiation operator
else if (line.contains("^")) {
int opIndex = line.indexOf("^");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = power(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has square operator
else if (line.contains("s")) {
int opIndex = line.indexOf("s");
String n1 = extractFirstNumber(line, opIndex);
double ans = square(Double.valueOf(n1));
line = calc(parseLine(line, n1, opIndex, ans));
}
// Checks if line has multiplication operator
else if (line.contains("*")) {
int opIndex = line.indexOf("*");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = multiply(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has division operator
else if (line.contains("/")) {
int opIndex = line.indexOf("/");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = divide(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has sum operator
else if (line.contains("+")) {
int opIndex = line.indexOf("+");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = add(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has subtraction operator
else if (line.contains("-")) {
int opIndex = line.indexOf("-");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = subtract(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
}
// Returns line only when it has only numbers
return line;
}
/**
* Checks if a line contains only numbers.
*
* #param line Line to be analyzed
* #return If a line contains only numbers
*/
private static boolean hasOnlyNumbers(String line)
{
return line.matches("^[0-9.]+$");
}
/**
* Given a mathematical expression, replaces a subexpression for a value.
*
* #param line Mathematical expression
* #param n1 Number to the left of the subexpression operator
* #param n2 Number to the right of the subexpression operator
* #param opIndex Operator index of the subexpression
* #param ans Value that will replace the subexpression
* #return New mathematical expression with the subexpression replaced
* by the value
*/
private static String parseLine(String line, String n1, String n2, int opIndex, double ans)
{
int lenFirstNumber = n1.length();
int lenSecondNumber = n2.length();
if (line.length()-1 >= opIndex+lenSecondNumber+1)
return line.substring(0, opIndex-lenFirstNumber)+ans+line.substring(opIndex+lenSecondNumber+1);
return line.substring(0, opIndex-lenFirstNumber)+ans;
}
/**
* Given a mathematical expression, replaces a subexpression for a value.
*
* #param line Mathematical expression
* #param n1 Number to the left of the subexpression operator
* #param opIndex Operator index of the subexpression
* #param ans Value that will replace the subexpression
* #return New mathematical expression with the subexpression replaced
* by the value
*/
private static String parseLine(String line, String n1, int opIndex, double ans)
{
int lenFirstNumber = n1.length();
if (line.length()-1 >= opIndex+2)
return line.substring(0, opIndex-lenFirstNumber)+ans+line.substring(opIndex+2);
return line.substring(0, opIndex-lenFirstNumber)+ans;
}
/**
* Extracts the first number from an operation. <br />
* <h1>Example:<h1> <br />
* <b>Line:</b> 1+2*3 <br />
* <b>opIndex:</b> 3 <br />
* <b>Return:</b> 2 <br />
*
* #param line Mathematical expression
* #param opIndex Index of the operator to which the number to be
* extracted belongs to
* #return Number to the left of the operator
*/
private static String extractFirstNumber(String line, int opIndex)
{
StringBuilder num = new StringBuilder();
int i = opIndex-1;
while (i>=0 && (Character.isDigit(line.charAt(i)) || line.charAt(i) == '.')) {
num.append(line.charAt(i));
i--;
}
// Reverses the result, since the number is taken from the end to the
// beginning
num = num.reverse();
return num.toString();
}
/**
* Extracts the second number from a math operation. <br />
* <h1>Example:<h1> <br />
* <b>Line:</b> 1+2*3 <br />
* <b>opIndex:</b> 3 <br />
* <b>Return:</b> 3 <br />
*
* #param line Mathematical expression
* #param opIndex Index of the operator to which the number to be
* extracted belongs to
* #return Number to the right of the operator
*/
private static String extractSecondNumber(String line, int opIndex)
{
StringBuilder num = new StringBuilder();
int i = opIndex+1;
while (i<line.length() && (Character.isDigit(line.charAt(i)) || line.charAt(i) == '.')) {
num.append(line.charAt(i));
i++;
}
return num.toString();
}
// Method for the operators.
private static double add(double numA, double numB)
{
double answer = numA + numB;
return answer;
}
private static double subtract(double numA, double numB)
{
double answer = numA - numB;
return answer;
}
private static double multiply(double numA, double numB)
{
double answer = numA * numB;
return answer;
}
private static double divide(double numA, double numB)
{
double answer = numA / numB;
return answer;
}
private static double power(double numA, double numB)
{
int answer = (int) Math.pow(numA, numB);
return answer;
}
private static double square(double num)
{
int answer = (int) Math.pow(num, 2);
return answer;
}
//-------------------------------------------------------------------------
// Main
//-------------------------------------------------------------------------
public static void main(String[] args) throws IOException
{
char option;
String inputLine = "";
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
option = input.readLine().charAt(0);
while (option != 'E' && option != 'e') {
// Gets user input
System.out.print("Enter mathematical expression: ");
inputLine += input.readLine();
// Processes input
inputLine = inputLine.replaceAll(" ", "");
inputLine = inputLine.replaceAll("S", "s");
// Evaluates input
System.out.println("Evaluating...");
String ans = TestingCalculator.calc(inputLine);
// Displays answer
System.out.println("Ans: "+ans);
// Checks if the user wants to continue running the program
System.out.print("Press E to Exit the calculator: ");
inputLine = input.readLine();
if (inputLine.length() > 0)
option = inputLine.charAt(0);
}
input.close();
}
}
Output
Enter mathematical expression: (1+2*4)/3
Evaluating...
Ans: 3.0
Output 2
Enter mathematical expression: 1+2*9/3
Evaluating...
Ans: 7.0
Desk checking
Input: (1+2*4)/3
calc( (1+2*4)/3 )
not hasOnlyNumbers( (1+2*4)/3) ) ? true
( (1+2*4)/3) ) contains '(' ? true
int parentheses_begin = 0
int parentheses_end = 6
String ans = calc( 1+2*4 )
calc( 1+2*4 )
not hasOnlyNumbers( 1+2*4 ) ? true
( 1+2*4 ) contains '(' ? false
( 1+2*4 ) contains '^' ? false
( 1+2*4 ) contains 's' ? false
( 1+2*4 ) contains '*' ? true
int opIndex = 3
int n1 = 2
int n2 = 4
String ans = n1 * n2 = 2 * 4 = 8
line = calc( 1+8 )
calc( 1+8 )
not hasOnlyNumbers( 1+8 ) ? true
( 1+8 ) contains '(' ? false
( 1+8 ) contains '^' ? false
( 1+8 ) contains 's' ? false
( 1+8 ) contains '*' ? false
( 1+8 ) contains '/' ? false
( 1+8 ) contains '+' ? true
int opIndex = 1
int n1 = 1
int n2 = 8
String ans = n1 + n2 = 1 + 8 = 9
line = calc( 9 )
calc( 9 )
not hasOnlyNumbers( 9 ) ? false
return 9
line = 9
not hasOnlyNumbers( 9 ) ? false
return 9
line = 9
not hasOnlyNumbers( 9 ) ? false
return 9
ans = 9
(9-1 >= 6+1) ? true
line = 9/3
not hasOnlyNumbers( 9/3 ) ? true
( 9/3 ) contains '(' ? false
( 9/3 ) contains '^' ? false
( 9/3 ) contains 's' ? false
( 9/3 ) contains '*' ? false
( 9/3 ) contains '/' ? true
int opIndex = 1
String n1 = 9
String n2 = 3
double ans = 9 / 3 = 3
line = calc( 3 )
calc( 3 )
not hasOnlyNumbers( 3 ) ? false
return 3
line = 3
not hasOnlyNumbers( 3 ) ? false
return 3
Some observations
No checks are made to see if the user-provided input is valid
It is important to maintain the order of operations that are verified in the calc method, in order to maintain precedence between operators (exponentiation / radication must be done first, followed by multiplication / division and finally addition / subtraction operations)
I had problems with the Scanner class, so I used BufferedReader to read the input
Square operation must be done as follows: <num>s or <num>S
Hope this helps. If you don't understand something, tell me I can explain it to you.
try below code and one suggestion try to handle the negative scenarios as well.
public static void main(String[] args) {
double answer = 0;
double numA, numB;
char operator;
char activateCalc;
boolean calculator = false;
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
Scanner ans = new Scanner(System.in);
Scanner input = new Scanner(System.in);
activateCalc = input.next().charAt(0);
while (true) {
if (activateCalc != 'E' && activateCalc != 'e') {
System.out.print("Enter number: ");
String n = input.next();
numA = Double.parseDouble(n);
// User enter their operator.
System.out.print("Enter Operator (+,-, /, *, ^ (Power) or s (Square): ");
operator = input.next().charAt(0);
System.out.print("Enter number: "); // User enter the continues number
numB = input.nextDouble();
switch (operator) {
case '=':
System.out.print(answer);
break;
case '+':
answer = add(numA, numB);
break;
case '-':
answer = subtract(numA, numB);
break;
case '*':
answer = multiply(numA, numB);
break;
case '/':
answer = divide(numA, numB);
break;
case '^':
answer = power(numA, numB);
break;
case 'S':
case 's':
answer = Math.pow(numA, 2);
break;
default:
answer = 0;
}
// The calculation answer of the user input
System.out.println("Answer: " + answer);
numA = answer;
// to exit calculator.
System.out.println("Press E to Exit the calculator or Y to continue : ");
activateCalc = input.next().charAt(0);
if(activateCalc != 'E' && activateCalc != 'e')continue;
}
System.out.println("Thank you for using the calculator. By :) ");
ans.close();
break;
}
}
// Method for the operators.
static double add(double numA, double numB) {
double answer = numA + numB;
return answer;
}
static double subtract(double numA, double numB) {
double answer = numA - numB;
return answer;
}
static double multiply(double numA, double numB) {
double answer = numA * numB;
return answer;
}
static double divide(double numA, double numB) {
double answer = numA / numB;
return answer;
}
static double power(double numA, double numB) {
int answer = (int) Math.pow(numA, numB);
return answer;
}
static double Square(double numA, double numB) {
int answer = (int) Math.pow(numA, 2);
return answer;
}
This question requires debugging details so here we go:
Your code does not seem to compile because of the error:
if (activateCalc = 'E' || activateCalc = 'e') {
break;
}
where you had to use comparison == operator instead of assignment =.
Similar issue is in your inner loop while (calculator = true) - and there's a warning that this value is never used - but this does not affect much.
You cannot exit the loop because you never check the input for exit, it should be:
System.out.println("Press E to Exit the calculator: ");
activateCalc = input.next().charAt(0);
But even if you updated activateCalc, you'd get into endless loop anyway because of the error in this condition while (activateCalc != 'E' || activateCalc != 'e') -- even if user presses 'e', or 'E' this condition is always true.
I have a problem. In class we have to do a simple calculator, and my problem is that I wanna write a number, then the operator, then again a number. Somehow my code doesn't work. I can enter the first number but then my program closes :/ Why is that? Is it because I used the data type string?
Thanks to everyone in advance!!
Here is my code:
import java.util.Scanner;
import java.math.*;
public class Calculatrice
{
public static void main(String args[])
{
double num1;
Scanner keyb = new Scanner(System.in);
System.out.println("Calculette Simple");
System.out.print("Valeur actuelle: ");
num1 = keyb.nextDouble();
System.out.print("Entrez un operateur: ");
String i;
i = keyb.nextLine();
double result = 0;
switch (i)
{
case "+":
result = result + num1;
break;
case "-":
result = result - num1;
break;
case "*":
result = result * num1;
break;
case "/":
result = result / num1;
break;
case "sqrt":
result = Math.sqrt(result);
break;
case "c":
result = 0;
break;
case "x":
System.exit(0);
break;
case "^":
result = Math.pow(result,num1);
break;
default:
System.out.println("Valeurs acceptees: +, -, *, /, ^, sqrt, c, x");
break;
}
keyb.close();
}
}
You need a loop: you need to read data from command line until a condition is verified, in order to read more then one string (number, operator or whatever you want). Then try something like this :
// your initialization of scanner
i = keyb.nextLine();
double result = 0;
while (!i.equals("end")) { // I use this as exit condition, but you can use whatever you want
switch (i) {
case "+":
result = result + num1;
break;
case "-":
result = result - num1;
break;
case "*":
result = result * num1;
break;
case "/":
result = result / num1;
break;
case "sqrt":
result = Math.sqrt(result);
break;
case "c":
result = 0;
break;
case "x":
System.exit(0);
break;
case "^":
result = Math.pow(result, num1);
default:
System.out.println("Valeurs acceptees: +, -, *, /, ^, sqrt, c, x");
}
}
// close scanner
you need some loop with exit condition (I belive it's 'x' in input)
something like
while (!"x".equals(i)) {
switch (i)
...
}
The program takes the value of both the numbers (entered by user) and then user is asked to enter the operation (+, -, * and /), based on the input program performs the selected operation on the entered numbers using switch case.
import java.util.Scanner;
public class JavaExample {
public static void main(String[] args) {
double num1, num2;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number:");
/* We are using data type double so that user
* can enter integer as well as floating point
* value
*/
num1 = scanner.nextDouble();
System.out.print("Enter second number:");
num2 = scanner.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
scanner.close();
double output;
switch(operator)
{
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
break;
/* If user enters any other operator or char apart from
* +, -, * and /, then display an error message to user
*
*/
default:
System.out.printf("You have entered wrong operator");
return;
}
System.out.println(num1+" "+operator+" "+num2+": "+output);
}
}
How do I check if a variable is equal or not equal to a contains? I want to make it so if someone where to put in an invalid operator it would say try again.
String operator = "+, -, *,/, %";
double num1, num2, sum=0;
System.out.println("First number: ");
num1 = input.nextDouble();
System.out.println("Second number: ");
num2 = input.nextDouble();
if (operator.contains("+")){
sum = num1 + num2;
} else if (operator != operator.contains("+,-,*,/,%"){
System.out.println("Error");
}
If you want to check what operator should be used based on the user entry, you could use switch statement as below
String operator = "";
while (operator.isEmpty()) {
System.out.println("Enter Operator: ");
operator = input.next();
switch (operator) {
case "+" : result = num1 + num2; break;
case "-" : result = num1 - num2; break;
case "*" : result = num1 * num2; break;
case "/" : result = num1 / num2; break;
default : System.out.println("Invalid operator: " + operator);
operator = "";
}
System.out.println("Result is " + result);
}
DEMO
If you only want to check if the operator is valid, you can use List contains() method:
String[] operators = { "+", "-", "*", "/" , "%" };
List<String> ops = Arrays.asList(operators);
:
System.out.println("Enter Operator: ");
String operator = input.next();
if (ops.contains(operator)) {
// do some calculation here
}
I am having trouble figuring out the logic for an infix calculator that is dynamic. I am able to accommodate string values with 5 elements, such as "1 + 1", but I cannot compute strings with more than 5 elements (ie: "1 + 2 + 3 + 4").
This is my process
import java.util.StringTokenizer;
public static int calculate(String input)
{
int lhs = 0;
int rhs = 0;
int total = 0;
char operation = ' ';
int intOne, intTwo;
StringTokenizer st = new StringTokenizer(input);
/*
* this block is chosen if there are no operations
*/
// block of if statement code for inputs less than or equal to
// 5 characters.
/*
* this block generates the correct number if there is more than
* one operator in the equation.
*/
}else if(input.length() > 5){
int firstValue = 0;
int latterValue = 0;
while(st.hasMoreTokens()){
/*
* method that assigns the left and right sides
*/
//assigns values to the first equation
int firstToken = Integer.parseInt(st.nextToken());
String opToken = st.nextToken();
int latterToken = Integer.parseInt(st.nextToken());
//returns a value for the first equation
firstValue = assignSides(firstToken, opToken, latterToken);
// takes in the next operator
if(st.nextToken().equals("+")){
operation = '+';
}else if(st.nextToken().equals("-")){
operation = '-';
}else if(st.nextToken().equals("*")){
operation = '*';
}else if(st.nextToken().equals("/")){
operation = '/';
}
// assigns values to the latter equation
firstToken = Integer.parseInt(st.nextToken());
opToken = st.nextToken();
latterToken = Integer.parseInt(st.nextToken());
//returns a value for the latter equation
latterValue = assignSides(firstToken, opToken, latterToken);
/*
* decides how to add the two equations
*/
switch(operation){
case '+': total = firstValue + latterValue;
break;
case '-': total = firstValue - latterValue;
break;
case '*': total = firstValue * latterValue;
break;
case '/': total = firstValue / latterValue;
break;
default: System.out.println("cannot compute");
break;
}
if(st.hasMoreTokens()){
//makes the total the first value
total = firstValue;
if(st.nextToken().equals("+")){
operation = '+';
}else if(st.nextToken().equals("-")){
operation = '-';
}else if(st.nextToken().equals("*")){
operation = '*';
}else if(st.nextToken().equals("/")){
operation = '/';
}
}
}
}
return total;
}
public static int assignSides(int firstToken, String opToken, int latterToken)
{
int lhs=0;
int rhs = 0;
int sum = 0;
char operation = ' ';
/*
* converts the string into a character
*/
if(opToken.equals("+")){
operation = '+';
}else if(opToken.equals("-")){
operation = '-';
}else if(opToken.equals("*")){
operation = '*';
}else if(opToken.equals("/")){
operation = '/';
}
rhs = latterToken;
/*
* interprates the character as a function
*/
switch(operation){
case '+': sum = lhs + rhs;
break;
case '-': sum = lhs - rhs;
break;
case '*': sum = lhs * rhs;
break;
case '/': sum = lhs / rhs;
break;
default: System.out.println("cannot compute");
break;
}
return sum;
}
Can I get help me with the error in my logic?
When calculating for more than 3 symbols (not counting spaces), as in "1 + 2 + 3",
you have to calculate in this order: 1 + (2 + 3).
You have to split up the first 1 and the remainig part "2 + 3", and pass the remaining part to the calculate method again. Something like:
int firstPart = ...; // evaluation of "1"
int secondPart = calculate("2 + 3");
int total = firstPart + secondPart;