This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
The "switch case" witch I have write for sin,cos,tan,cot doesn't work when I enter them in operator and it goes to entering second number.
Where is my fault?
Here is my code:
import java.util.Scanner;
public class MainClass {
public static void main(String args[]){
Scanner NumInput = new Scanner(System.in);
double firstNum = 0;
double secondNum = 0;
double result = 0;
System.out.println("Enter first number: ");
firstNum = NumInput.nextDouble() ;
System.out.println("Enter operator: ");
String amalgar = NumInput.next();
if (amalgar == "sin" || amalgar == "cos" || amalgar == "tan" || amalgar == "cot"){
switch(amalgar){
case "sin":
result = Math.toRadians(Math.sin(firstNum));
break;
case "cos":
result = Math.toRadians(Math.cos(firstNum));
break;
case "tan":
result = Math.toRadians(Math.tan(firstNum));
break;
case "cot":
result = (Math.toRadians(Math.cos(firstNum))/Math.toRadians(Math.sin(firstNum)));
break;
default :
break;
}
System.out.println(Math.toRadians(result));
}
else
System.out.println("Enter second number: ");
secondNum = NumInput.nextDouble();
switch (amalgar){
case "+":
result = firstNum + secondNum;
break;
case "-":
result = firstNum - secondNum;
break;
case "*":
result = firstNum * secondNum;
break;
case "/":
result = firstNum / secondNum;
break;
default:
System.out.println("nemifahmam chi neveeshti");
}
System.out.println(result);
}
}
The problem lies with this if condition:
if (amalgar == "sin" || amalgar == "cos" || amalgar == "tan" || amalgar == "cot"){
Using == only evaluates to true if you have the same object (i.e. two identical references) but "sin"(or "cos",etc) and amalgar are always two different objects. You should use equals() instead to compare the value. (see How do I compare strings in Java?)
Better yet, don't use the if-else block at all. Use switch, because if you don't match one of those four you won't evaluate anything but your default case, which is empty.
Related
I created simple calculator using switch case. When I enter the invalid operators, but it takes that value .And at last it gives the default switch case .How can I restrict it.
package calculator;
import java.util.*;
public class Calculator {
public static void main(String[] args) {
char operator;
Double num1, num2, result;
Scanner input = new Scanner(System.in);
System.out.println("Enter the operator: +,-,*,/,% ");
operator = input.next().charAt(0);
//user input
System.out.println("Enter the First Number:");
num1 = input.nextDouble();
System.out.println("Enter the Second Number:");
num2 = input.nextDouble();
switch (operator) {
case '+':
result = num1+num2;
System.out.println(num1+" + "+num1+" = " + result);
break;
case '-':
result = num1-num2;
System.out.println(num1+" - "+num1+" = " + result);
break;
case '*':
result = num1*num2;
System.out.println(num1+" * "+num1+" = " + result);
break;
case '/':
result = num1/num2;
System.out.println(num1+" / "+num1+" = " + result);
break;
case '%':
result = num1%num2;
System.out.println(num1+" % "+num1+" = " + result);
break;
default:
System.out.println("Invalid operator");
break;
}
input.close();
}
}
console output
Enter the operator: +,-,*,/,%
7
Enter the First Number:
5
Enter the Second Number:
5
Invalid operator
if(Character.isDigit(c)){
// what you want for true
}
else{
// what you want for false
}
This may help you.
Java or any other programming languages run code sequentially.
Here once the operator is entered you can check to proceed further for other statements.
The logic of code how you write, that way it is executed.
So in this case, once you take value for operator check whether that operator is allowed in your case or not.
If allowed then run the further code else not run that.
I am new at coding and now I am learning Java. I tryed to write something like calculator. I wrote it with switch case but then I realized I must take all inputs in single line. For example in this code I took 3 inputs but in 3 different lines. But I must take 2 input and 1 char in single line. First first number second char and then third number. Can you help me ?
Public static void main(String[] args) {
int opr1,opr2,answer;
char opr;
Scanner sc =new Scanner(System.in);
System.out.println("Enter first number");
opr1=sc.nextInt();
System.out.println("Enter operation for");
opr=sc.next().charAt(0);
System.out.println("Enter second number");
opr2=sc.nextInt();
switch (opr){
case '+':
answer=opr1+opr2;
System.out.println("The answer is: " +answer);
break;
case '-':
answer=opr1-opr2;
System.out.println("The answer is: " +answer);
break;
case '*':
answer=opr1*opr2;
System.out.println("The answer is: " +answer);
break;
case '/':
if(opr2>0) {
answer = opr1 / opr2;
System.out.println("The answer is: " + answer);
}
else {
System.out.println("You can't divide to zero");
}
break;
default:
System.out.println("Unknown command");
break;
}
Try following way
System.out.print("Enter a number then operator then another number : ");
String input = scanner.nextLine(); // get the entire line after the prompt
String[] sum = input.split(" ");
Here numbers and operator separated by "space". Now, you can call them by sum array.
int num1 = Integer.parseInt(sum[0]);
String operator = sum[1]; //They are already string value
int num2 = Integer.parseInt(sum[2]);
Then, you can do as you did than.
You can try something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter number, operation and number. For example: 2+2");
String value = scanner.next();
Character operation = null;
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
Character c = value.charAt(i);
// If operation is null, the digits belongs to the first number.
if (operation == null && Character.isDigit(c)) {
a.append(c);
}
// If operation is not null, the digits belongs to the second number.
else if (operation != null && Character.isDigit(c)) {
b.append(c);
}
// It's not a digit, therefore it's the operation itself.
else {
operation = c;
}
}
Integer aNumber = Integer.valueOf(a.toString());
Integer bNumber = Integer.valueOf(b.toString());
// Switch goes here...
}
Note: didn't validate input here.
I'm writing a simple program with a do while loop and switch, which cna accept a mathematical operation and execute it for given 2 numbers.
The problem I have is, why should I initialize the result produced by the operation to zero at the beginning.
If I don't make ans=0, it gives me errors. If the given conditions are not met, some code parts are not executed and I don't need "ans".
package q3;
import java.util.Scanner;
public class Q3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char operator;
float no1, no2, ans=0; // <-------------- Why should I initialize ans
do {
System.out.println(" Mathematical Operations to be performed :");
System.out.println("\t * Multiplication\n\t / Division\n\t + Addition\n\t - Subtraction");
System.out.println("Press any other character to exit");
System.out.print("Mathematical Operator : ");
operator = input.next().charAt(0);
if (operator == '*' || operator == '/' || operator == '+' || operator == '-') {
System.out.print("Number 1: ");
no1 = input.nextFloat();
System.out.print("Number 2: ");
no2 = input.nextFloat();
switch (operator) {
case '*':
ans = no1 * no2;
break;
case '/':
ans = no1 / no2;
break;
case '+':
ans = no1 + no2;
break;
case '-':
ans = no1 - no2;
break;
}
System.out.println("The answer of " + no1 + operator + no2 + " = " + ans);
}
} while (operator == '*' || operator == '/' || operator == '+' || operator == '-');
}
}
Java requires that all local variables are initialised before they are used.
In your print line, you read the value of abs, but not all control paths set a value to it. (Even though you think you've covered all possibilities of your switch given the outer if, the compiler will not see things that way: some other thread could modify operator).
So your IDE / compiler is suggesting that you initialise it at the point of declaration.
This is because if no case evaluates to true, the value of ans will not be set. So you cannot use it.
You can overcome this by adding a default case, and setting the value of ans as 0 in that.
You should initialize ans=0; because you didn't have a default value for ans, for this you need to initialized it.
But if you add the defualt value you don't need to initialize it like this:
...
case '-':
ans = no1 - no2;
break;
default :
ans = someValue;
break;
Well, it could be that none of the case statements apply and as a result ans would still be un-initialized. And since local variables have to be initialised before they are being used, you get this error.
If you didnt initialize it, you ans will have a garbage value at first.
It is not compulsory to initialize it.
But your program will be a better program if you initialize it.
I am experiencing trouble in the creation of my reverse polish notation calculator with my validation code. I need the calculator to accept the two shift operators (<< and >>) as part of the calculations. The following snippets of code is the validation part and also the calculation.
public static boolean isInt(String userinput) {
try {
Integer.parseInt(userinput); // Try to parse. Makes sure that the values entered are actual numbers
return true; // Boolean value to show if the equation entered is valid or not
} catch (NumberFormatException e) {
System.out.println("Please enter a valid expression!");
invalidlines++;
return false;
}
}
public static boolean isValidLine(String line) {
line = line.trim();
if (line.length() <= 4) { // Trims the lines down to 4 and ensures there is no spaces being included
return false;
} else {
String[] calcarray = new String[3];
calcarray = line.split(" ");
String operators = new String("[+\\-\\*\\/\\<<\\>>\\%\\&\\|]"); // Validator using regular expressions to check the operator used
if (isInt(calcarray[0].toString()) && isInt(calcarray[1].toString()) && calcarray[2].matches(operators)) { // Checks that the operator in the string matches the ones in the regular expression
return true;
} else {
return false;
}
}
}
below is the calculator part:
String keyboardInput = new String();
Scanner kbScan = new Scanner(System.in);
int answer = 0;
while (true) {
display("Please enter an equation");
keyboardInput = kbScan.nextLine();
if (isValidLine(keyboardInput)) {
String[] equation = new String[3]; // We know that this is only going to contain 3 to be valid
equation = keyboardInput.split(" "); // split this up, as it's stored with the spaces.
int num1 = Integer.parseInt(equation[0]);
int num2 = Integer.parseInt(equation[1]);
switch (equation[2]) { // This case switch checks the third position of the
// string to decide which operator is being used. It then works out the
// answer and breaks to the next instruction
case ("+"):
answer = num1 + num2;
break;
case ("-"):
answer = num1 - num2;
break;
case ("/"):
answer = num1 / num2;
break;
case ("*"):
answer = num1 * num2;
break;
case ("<<"):
answer = num1 << num2;
break;
case (">>"):
answer = num1 >> num2;
break;
case ("%"):
answer = num1 % num2;
break;
case ("|"):
answer = num1 | num2;
break;
case ("&"):
answer = num1 & num2;
break;
}
display("Your post fix expression: " + equation[0] + " " + equation[1] + " " + equation[2]);
display("Your calculation: " + equation[0] + " " + equation[2] + " " + equation[1] + " = " + answer);
} else {
display("The equation you entered is invalid");
}
}
Whenever a valid expression is entered the following error is shown in the console:
Enter F for file calculator or K for keyboard input
k
Please enter an equation
10 2 <<
The equation you entered is invalid
Please enter an equation
And I cannot figure out which part of my validation is wrong for these expressions.
Problem is with your operators regex.
User rather something like:
("\\+|\\-|\\*|\\/|<<|>>|\\%|\\&|\\|")
//Loop that isn't working. I keep pressing a number that is 1,2,3,4, or 5 but it won't exit the loop. The operator seems to be assigned the value that I input but it still will not exit the while loop. I'm trying to write a basic calculator with simple math operations but this turned into a very annoying problem.
import java.util.Scanner;
public class BasicCalculatorTwo {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int operator;
double fnum, snum, answer;
operator = 0;
System.out.println("Enter first number : ");
fnum = scanner.nextDouble();
System.out.println("Enter second number : ");
snum = scanner.nextDouble();
while(operator != 1 || operator != 2 || operator != 3 || operator != 4 || operator != 5 ){
System.out.println();
System.out.println(fnum + " ? " + snum + " = ");
System.out.println("1 : Add");
System.out.println("2 : Subtract");
System.out.println("3 : Multiply");
System.out.println("4 : Divide");
System.out.println("5 : Modularize");
operator = scanner.nextInt();
}
switch(operator){
case 1:
answer = fnum + snum;
break;
case 2:
answer = fnum - snum;
break;
case 3:
answer = fnum * snum;
break;
case 4:
answer = fnum / snum;
break;
case 5:
answer = fnum % snum;
break;
default:
break;
System.out.println(fnum + " ? " + snum + " = " + answer);
scanner.close();
}
}
}
You loop conditional is the problem.
while (operator != 1 || operator != 2 || operator != 3 || operator != 4 || operator != 5)
It should be
while (operator != 1 && operator != 2 && operator != 3 && operator != 4 && operator != 5)
Basically, you're saying that if the operator is != 1, then do the loop. Likewise each of the others. If you were to utilize && operators instead of || it would work much better.
Really, what you want to say is that operator is > 1 && < 5, then loop, otherwise break.
while(operator < 1 || operator > 5)
{
DoPrintStuffHere();
}
Think about it logically, you want any number less than 1 OR greater than 5 to loop again.