How to modify the code so I can continuously count? So for example 2+3=5, and than -1 =4, until i press q to exit program ?? Please some simple solution for beginners. Thank you.
import java.util.Objects;
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do {
System.out.println("Enter first number:");
double num1 = sc.nextDouble();
System.out.println("Enter second number");
double num2 = sc.nextDouble();
System.out.println("Select operator (+,-,*,/) or enter q to exit:");
char operator = sc.next().charAt(0);
switch (operator) {
case '+':
System.out.println("Result =" + Equasion.sum(num1, num2));
break;
case '-':
System.out.println(Equasion.substract(num1, num2));
break;
case'/':
if (num2 == 0) {
System.out.println("Divide by zero problem");
} else System.out.println(Equasion.divide(num1, num2));
case '*':
System.out.println(Equasion.multiply(num1, num2));
break;
case 'q':
System.exit(0);
}
System.out.println("Press any key to continue or q to quit");
} while (!Objects.equals(ExitProg.exitProg(), 'q'));
}
}
Correct me if I'm wrong but you should move the first lines outside the while loop then overwrite the values of num1 and num2 every iteration (num2 becomes num1, then the user inputs another num2)
Related
I am new to Java, and I'm doing a calculator APP.
I'm trying to get my calculator to keep prompting the user for the correct answer (typing Y or N) after the else statement following 'Invalid Input'.
I want the program to continue with the calculations after the correct input is finally entered.
I have played around with an embedded while loop, but ended up with an infinite loop or a loop that terminates with no resolution. The code is below.
import java.util.Scanner;
class Calculate {
public static void.main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
double num1, num2;
String choice;
boolean youDecide = true;
while(youDecide == true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
char operator = userinput.next().charAt(0);
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch(operator)
{
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
if(num2 == 0)
System.out.println("Math error! A number cannot be divided by zero.");
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
return;
}
System.out.println("*************************************************************************");
System.out.println("The answer is: " + "\n" + output);
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
youDecide = true;
}
else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
}
else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
youDecide = false;
}
}
}
}
I've made some changes and comments to your code
import java.util.Scanner;
class Calculator {
public static void main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
double num1, num2;
String choice;
//the "youDecide" variable is not needed at all
while (true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
char operator = userinput.next().charAt(0);
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch (operator) {
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
if (num2 == 0) {
System.out.println("Math error! A number cannot be divided by zero.");
}
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
continue; //changed from "return" you don't want to exit, just to skip to the next execution of the loop
}
System.out.println("*************************************************************************");
System.out.println("The answer is: " + "\n" + output);
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if (choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
} else if (choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
} else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
}
}
}
}
You need a while loop to ensure the value is correct.
Due the logic into your code you need to do when the user type the char, otherwise you have to change many lines of code, or ask for all values again.
I think for a begginer the easiest way is using this loop:
char operator;
while(true) {
operator = userinput.next().charAt(0);
if(operator=='+' || operator == '-' || operator == '*' || operator == '/') {
break;
}else {
System.out.println("Please enter a valid operator: ");
}
}
Exists many ways more elegant to do this. But I think for a begginer is the easiest way to understand and implement the code.
This loop is only to ensure the user type a valid character. While the character is not one of them, the loop will be iterating.
You have to place this code just below this line where you ask for a valid operator.
After adding the edits suggested by J.F. and Javaman along with some research, I was able to solve the problem by adding the following lines to my code:
import java.util.InputMismatchException;
import java.util.Scanner;
class Calculator {
public static void main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
char operator;
double num1, num2;
String choice;
while(true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
while(true) {
operator = userinput.next().charAt(0);
if(operator == '+' || operator == '-' || operator == '*' || operator == '/') {
break;
}else {
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
}
}
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch(operator) {
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
continue;
}
System.out.println("*************************************************************************");
if(num2 == 0) {
System.out.println("Math error! A number cannot be divided by zero.");
}else {
System.out.println("The answer is: " + "\n" + output);
}
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
}else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
}else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
**while (!("Y").equalsIgnoreCase(choice) && !("N").equalsIgnoreCase(choice)) {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
}else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);**
}
}
}
}
}
}
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);
}
}
You probably understand that I am a beginner, and I know that we aren't really liked by the community.
I made a multi purpose calculator a while back and now I want to expand it. In this question I will be focusing only on one class.
import java.util.Scanner;
public class Calculator {
public static void calcMenu(Scanner input){
Scanner oper = new Scanner(System.in);
System.out.println("Please input the First number:");
double anum = input.nextDouble();
System.out.println("Please input on of the following operations:");
System.out.println("+");
System.out.println("-");
System.out.println("*");
System.out.println("/");
String equ = oper.nextLine();
System.out.println("Please input the Second number:");
double bnum = input.nextDouble();
switch (equ){
case "+":
System.out.println(anum + bnum);
break;
case "-":
System.out.println(anum - bnum);
break;
case "*":
System.out.println(anum * bnum);
break;
case "/":
System.out.println(anum / bnum);
break;
}
}
}
In this Java class, the program can solve equations only with two numbers. I would like to make it like in a standard calculator, where you can input the numbers as much as you want. I would like to do it until the user types something like "done" and the application will return to the main menu.
This is probably a very nooby question but please help. And if you want to see the whole application: here's the link
This will help you out! :)
import java.util.InputMismatchException;
import java.util.Scanner;
public class Calculator {
private static double answer;
private static boolean done = false;
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
try {
new Calculator().calcExpression();
} catch (InputMismatchException e) {
System.out.println("An error occurred. ");
}
}
private void calcExpression() throws InputMismatchException {
System.out.println("Enter Your Expression Here:");
System.out.print("Num: ");
double firstNum = in.nextDouble();
in.nextLine();
while (!done) {
System.out.print("Operator: ");
String operand = in.nextLine();
if (operand.equals("=")) {
break;
}
System.out.print("Num: ");
double secondNum = in.nextDouble();
in.nextLine();
calculate(firstNum, operand, secondNum);
firstNum = answer;
}
System.out.printf("Answer is %.2f", answer);
}
private void calculate(double num1, String equ, double num2) {
switch (equ)
{
case "/":
answer = (num1 / num2);
break;
case "*":
answer = (num1 * num2);
break;
case "+":
answer = (num1 + num2);
break;
case "-":
answer = (num1 - num2);
break;
case "=":
done = true;
break;
}
}
}
I've writter a calculator program in Java, after a user is done with work,
I want this to happen:
i'll ask if he wants to do more operations, if yes, the program should return to choice input. If no, break the program.
What lines should I add to the code? This is my calc program:
import java.util.*;
class calc
{
public static void main(String ar[])
{
char choice;
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO SHREYDAN'S CALC 1.0");
System.out.println(" ");
System.out.println("YOU CAN DO THE FOLLOWING:");
System.out.println("+: ADDITION");
System.out.println("-: SUBTRACTION");
System.out.println("*: PRODUCT");
System.out.println("/: QUOTIENT");
System.out.println("#: SQUARE ROOT");
System.out.println("^: POWER");
System.out.println("$: ROUND OFF");
System.out.println("!: FACTORIAL");
System.out.println(" ");
System.out.println("ENTER CHOICE");
choice=in.next().charAt(0);
switch(choice)
{
case '+':
System.out.println("ENTER 2 NUMBERS, USER");
double a=in.nextDouble();
double b=in.nextDouble();
System.out.println("SUM = "+(a+b));
break;
case '-':
System.out.println("ENTER 2 NUMBERS, USER");
double c=in.nextDouble();
double d=in.nextDouble();
System.out.println("SUBTRACTING "+d+" FROM "+c+" ... DIFFERENCE = "+(c-d));
break;
case '*':
System.out.println("ENTER 2 NUMBERS, USER");
double e=in.nextDouble();
double f=in.nextDouble();
System.out.println("PRODUCT = "+(e*f));
break;
case '/':
System.out.println("ENTER 2 NUMBERS, USER");
double g=in.nextDouble();
double h=in.nextDouble();
System.out.println("DIVIDING "+g+" BY "+h+" = "+(g/h));
break;
case '#':
System.out.println("ENTER NO. FOR SQAURE ROOT:");
double sqrt=in.nextDouble();
System.out.println("SQUARE ROOT OF "+sqrt+" = "+Math.sqrt(sqrt));
break;
case '^':
System.out.println("ENTER BASE, USER");
double base=in.nextDouble();
System.out.println("ENTER POWER, USER");
double power=in.nextDouble();
System.out.println(base+" RAISED TO POWER "+power+" = "+Math.pow(base,power));
break;
case '$':
System.out.println("ENTER DECIMAL VALUES TO ROUND OFF");
double deci=in.nextDouble();
System.out.println("THE NEAREST ROUND OFF = "+Math.round(deci));
break;
case '!':
System.out.println("ENTER A NO. FOR FACTORIAL:");
int fact=in.nextInt();
int factorial=1;
for(int i=fact; i>=1;i--)
factorial=factorial*i;
System.out.println(fact+"! = "+factorial);
break;
default:
System.out.println("WRONG CHOICE USER");
}
}
}
while loops are your best bet for this type of problem, just think of a condition which the user can choose to toggle the boolean condition.
for example if the user chooses no on the "continuing of operations" choice, then toggle the boolean to false and exit the while loop to end the program.
You need to wrap the program logic in a loop.
Try using a while loop
public static void main(String args[])
{
boolean doContinue = true;
while(doContinue){
char choice;
Scanner in = new Scanner(System.in);
//program logic
//when the user enters a command to end
// set continue=false
}
}
Maybe put the entire program inside a while loop with a continue to run bool condition which could be set false when they want to quit
You can try the following:
import java.util.*;
class calc {
public static void main(String ar[]) {
char choice;
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO SHREYDAN'S CALC 1.0");
System.out.println(" ");
boolean loop = true;
while (loop) {
System.out.println("YOU CAN DO THE FOLLOWING:");
System.out.println("+: ADDITION");
System.out.println("-: SUBTRACTION");
System.out.println("*: PRODUCT");
System.out.println("/: QUOTIENT");
System.out.println("#: SQUARE ROOT");
System.out.println("^: POWER");
System.out.println("$: ROUND OFF");
System.out.println("!: FACTORIAL");
System.out.println(" ");
System.out.println("ENTER CHOICE");
choice = in.next().charAt(0);
switch (choice) {
case '+':
System.out.println("ENTER 2 NUMBERS, USER");
double a = in.nextDouble();
double b = in.nextDouble();
System.out.println("SUM = " + (a + b));
break;
case '-':
System.out.println("ENTER 2 NUMBERS, USER");
double c = in.nextDouble();
double d = in.nextDouble();
System.out.println("SUBTRACTING " + d + " FROM " + c + " ... DIFFERENCE = " + (c - d));
break;
case '*':
System.out.println("ENTER 2 NUMBERS, USER");
double e = in.nextDouble();
double f = in.nextDouble();
System.out.println("PRODUCT = " + (e * f));
break;
case '/':
System.out.println("ENTER 2 NUMBERS, USER");
double g = in.nextDouble();
double h = in.nextDouble();
System.out.println("DIVIDING " + g + " BY " + h + " = " + (g / h));
break;
case '#':
System.out.println("ENTER NO. FOR SQAURE ROOT:");
double sqrt = in.nextDouble();
System.out.println("SQUARE ROOT OF " + sqrt + " = " + Math.sqrt(sqrt));
break;
case '^':
System.out.println("ENTER BASE, USER");
double base = in.nextDouble();
System.out.println("ENTER POWER, USER");
double power = in.nextDouble();
System.out.println(base + " RAISED TO POWER " + power + " = " + Math.pow(base, power));
break;
case '$':
System.out.println("ENTER DECIMAL VALUES TO ROUND OFF");
double deci = in.nextDouble();
System.out.println("THE NEAREST ROUND OFF = " + Math.round(deci));
break;
case '!':
System.out.println("ENTER A NO. FOR FACTORIAL:");
int fact = in.nextInt();
int factorial = 1;
for (int i = fact; i >= 1; i--)
factorial = factorial * i;
System.out.println(fact + "! = " + factorial);
break;
default:
System.out.println("WRONG CHOICE USER");
}
System.out.println("Want to calculate more?Y/N");
loop = in.next().charAt(0) == 'Y';
}
}
}
Hello I have tried syntax for calculator, with char for operand
but the result always error.
I'm using eclipse (Luna). there are no error or warning message on it.
Syntax
Scanner in = new Scanner(System.in);
int answer = 0;
System.out.println("Enter a number:");
int num1 = in.nextInt();
System.out.println("Enter another number:");
int num2 = in.nextInt();
System.out.println("Enter the operand:");
char input =(char) in.nextInt();
switch (input){
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;
default:
System.out.println("Invalid Command");
}
System.out.println("The result is: " + answer);
Debugging
Input number, another number and an operand:
and the error:
InputMismatchException
Just change this line: char input =(char) in.nextInt(); for this char input = in.next().charAt(0)...and you are good to go!