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.
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 was just trying to code a simple calculator and it works fine...
What I want to do now is include a 'do while' or 'while' loop to repeat a statement till a user enters one of the four basic operator signs. I have achieved it using other methods (if and switch) but I want to simplify it.
Also I faced a lot of problems learning how to parse a character in scanner and JPane methods. I could achieve using various resources on the internet but a simple method that would help me understand the logic more clearly and not just achieve will be highly appreciated...
public class MyCalculator{
public static void main (String [] args){
// Let us code a simple calculator
char OP;
System.out.println("This is a simple calculator that will do basic calculations such as :\nAddition, Multiplication, Substraction and Division.");
// Create a scanner object to Read user Input.
Scanner input = new Scanner(System.in);
System.out.println("Enter Any positive number followed by pressing ENTER.");
int firstNum = input.nextInt();
// Need to Loop the below statement till one of the four (+,-,*,/) operator is entered.
System.out.println("Enter your choice of OPERATOR sign followed by pressing ENTER.");
OP = input.next().charAt(0);
System.out.println("Enter your Second number followed by an ENTER stroke.");
int secNum = input.nextInt();
// Various possible Resolution
int RSum = firstNum+secNum;
int RSubs= firstNum-secNum;
int RPro = firstNum*secNum;
double DPro = firstNum/secNum;
// Conditional statements for Processing
Switch (OP){
case '+': System.out.println("The Resulting sum is "+ RSum);
break;
case '-': System.out.println("The Resulting sum is "+ RSubs);
break;
case '*': System.out.println("The Resulting Product is "+ RPro);
break;
case '/': System.out.println("The Resulting Divisional product is "+ DPro);
break;
default : System.out.println("Try Again");
}
}
}
You can use something like this:
while(scanner.hasNext()) {
//some code
int number = scanner.NextInt();
}
But I would implement a calculator as follow:
int num1 = scanner.NextInt();
String op = scanner.Next();
int num2 = scanner.NextInt();
You can loop through a String as follow and do your checks:
for (char ch : exampleString.toCharArray()){
System.out.println(ch);
}
You can also loop through a String as follow:
for (int i=0; i<examplestring.length(); i++) {
char c = examplestring.charAt(i);
}
You can loop until you get a + or a - as follow:
char operator;
do {
char operator = scanner.next().get(0);
}while(operator != '+' || operator != '-')
You can loop and print error messages as follow:
char operator;
do {
char operator = scanner.next().get(0);
if(!isValidOperator(operator)) {
System.out.println("invalid operator");
}
}while(!isValidOperator(operator))
public boolean isValidOperator(char operator) {
if(operator == '+') {
return true;
} else if (operator == '-') {
return true;
}
return false;
}
This is my first try on Java. The project is a calculator that takes a number, an operator signal (+,-,*,/), and another number to create an equation and give the final value of it, asking after that if the user wants to restart the program for another equation or not. I would like to know if there is anything that I can do to improve my code.
Thanks!
/*
Name: Felipe de Araujo
Project #: 1
*/
import java.util.Scanner; //Importing API.
public class Calculator {
public static void main(String[] args){
int a = 1; //Creating variable for the first while loop.
System.out.println("Welcome to the calculator!"); //Program introduction.
while (a == 1){
Scanner input = new Scanner(System.in); //Creating the input.
double firstNumber, secondNumber, result; char operator; //Creating all variables.
//Program asking for the first number.
System.out.print("First Number: ");
firstNumber = input.nextDouble();
//Program asking for the operator
System.out.print(firstNumber + " (+,-,*,/): ");
operator = input.next(".").charAt(0);
int repeat = 1; //Creating variable for the next while loop.
//Evaluating the operator to determine if it is inside the criteria (+,-,*,/).
if (operator == '+' || operator == '-' || operator == '*' || operator == '/'){
System.out.print(firstNumber + " " + operator + " Second Number: "); //If the operator is inside the criteria than start
//asking for the second number.
}
else { //If the operator is not inside the criteria run the loop until the user type something that is.
while (repeat == 1){
System.out.print(operator + " not recognized, please select between (+,-,*,/): ");
operator = input.next(".").charAt(0);
if (operator == '+' || operator == '-' || operator == '*' || operator == '/') {
System.out.print(firstNumber + " " + operator + " Second Number: ");
repeat++;
}
}
}
secondNumber = input.nextDouble(); //Initialize the secondNumber variable to the number typed.
//Equalling the variable result to the return given by the method calculatorMethod, with the variables given.
result = calculatorMethod(firstNumber, secondNumber, operator);
System.out.println(firstNumber + " " + operator + " " + secondNumber + " = " + result);//Printing the equation.
System.out.println(" ");
// Asking the user to continue the program for another operation.
char out;//Creating the variable out.
System.out.print("[y/Y] - continue | [n/N] or any other to end program: ");
out = input.next(".").charAt(0);//Initializing the variable out to what was typed.
//Verifying if the user wants to continue the program.
if (out == 'y' || out == 'Y'){
System.out.println(" ");
}
else {//If the users type anything besides y/Y the program will exit the main loop, ending the program.
System.out.println("Bye!");
a++;
}
}
}
//Declaring the calculatorMethod and all its behaviors.
private static double calculatorMethod(double a, double b, char c){
if (c == '+'){
return a + b;
}
else if (c == '-'){
return a - b;
}
else if (c == '*'){
return a * b;
}
else {
return a / b;
}
}
}
hello and welcome to the Java world :) . Some tips :
Try to give clear name to your variables. 'a', 'b', 'c' could be complicated to understand.
Favor short methods to improve the readability of your code. For example you can create an other method which return an object of : separator + the two numbers and an other one which print the result.
You can use switch(variable) in your calculatorMethod method. For example :
switch (c) { // you have to change the name of all the variables 'c', 'a' and 'b'
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
default:
return a / b;
}
}
You can create an enum or a list with the different operators.
When you check the input operator, you can use a while() loop and delete the if...else loop. The condition of the while loop could be "while the operator is not the correct one (and so, not contained in the list of correct operators), loop again and again".
The scanner initialization Scanner input = new Scanner(System.in); should be out the while() loop because you need to initialize only one time the scanner and in this case, you initialize X times (X refers to the numbers of loops).
Good luck :)
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.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I am working on a VERY simple calculator with Java and it does not seem to output an answer after selecting the operation. The code is as follows:
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
Double fnum;
Double snum;
Double answer;
String operation;
System.out.println("Enter a number.");
fnum = keyboard.nextDouble();
System.out.println("Enter another number.");
snum = keyboard.nextDouble();
System.out.println("What operation do you wish for? [Multiplication, Addition, Subtraction, Division]");
operation = keyboard.next();
if (operation == "Multiplication" || operation == "multiplication" || operation == "*") {
answer = fnum * snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Division" || operation == "division" || operation == "/") {
answer = fnum / snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Addition" || operation == "addition" || operation == "+" || operation == "add") {
answer = fnum + snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Subtraction" || operation == "subraction" || operation == "-" || operation == "subtract"){
answer = fnum - snum;
System.out.print("Your answer is: " + answer);
}
else {
System.out.println("This is not valid.");
}
}
}
and this is the output:
Enter a number.
6
Enter another number.
6
What operation do you wish for? [Multiplication, Addition, Subtraction, Division]
Multiplication
This is not valid.
Any help would be very appreciated.
P.S. there are no errors.
Thanks!
There are 2 problems. A problem with Scanner and with the condition
keyboard.nextDouble(), keyboard.next() etc... (all except .nextLine() ) leave the newline ( \n or Enter ) in the buffer. This can cause problems etc..
I suggest adding a delimiter using keyboard.useDelimiter("\n");. This only needs to be done once and can be done right after initialization of keyboard.
That way, it will only see the Enter as a signal to end that current input.
Also, the conditions must all be using the .equals() method or .equalsIgnoreCase() which is written as:
operation.equals("Multiplication");
or
operation.equalsIgnoreCase("multiplication");
Strings should be compared via .eqauals() method. So put in the if clause operation.equals("Multiplication")...and so on...
You are comparing strings by reference, not by their values. Use .equals() instead!
As #Sebastian said you should use equals instead of ==
You can improve it a little bit to avoid the spaces mistakes or case (upper case or lower case) issues by doing it the following way:
if (operation.trim().toUpperCase().equals("MULTIPLICATION") || operation.trim().equals("*"))
That way it will work for Multiplication multiplication but also MulTIpliCation, etc.
You can get the same result using equalsIgnoreCase also