Calling variable when using Scanner Class and Multiple Classes - java

Trying to call the total value from the operatorSelection class while that class references what the user enters as the operator.
I want it to end up coming out as number1 (operator chosen) number2...= total.
Not sure how to call class so that it prints the " System.out.println(number1+" "+operator+" "+number2+" "+operator+" "+number2+ " = "+ total); " correctly.
Any knowledge would be greatly appreciated on the subject.
Thanks.
import java.util.Scanner;
class NumbersEntered
{
public void operatorSeletion(double number1, double number2, double number3, char operator)
{
double total = 0;
switch(operator)
{
case '+':
total = number1 + number2 + number3;
break;
case '-':
total = number1 - number2 - number3;
break;
case '*':
total = number1 * number2 * number3;
break;
case '/':
total = number1 / number2 / number3;
break;
default:
System.out.println("You have entered incorrectly. Please try again.");
return;
}
}
}
public class JavaPresentation_KS {
public static void main(String[] args) {
NumbersEntered nums = new NumbersEntered();
Scanner equation = new Scanner(System.in);
System.out.println("Enter first number: ");
double number1 = equation.nextDouble();
System.out.println("Enter second number: ");
double number2 = equation.nextDouble();
System.out.println("Enter third number: ");
double number3 = equation.nextDouble();
System.out.println("Enter an operator (+, -, *, /): ");
char operator = equation.next().charAt(0);
System.out.println(number1+" "+operator+" "+number2+" "+operator+" "+number2+ " = "+ total);
}
}

Your problem is that you declare the total variable within the operatorSeletion method, and you try to access it without specifying it's location. You need to declare the total variable as a field, and then access it at its location (new NumbersEntered().total). Also, you never invoke operatorSeletion, which might help ;)
class NumbersEntered {
public double total = 0; //declare as accessable field
public void operatorSeletion(double number1, double number2, double number3, char operator)
{
switch(operator)
{
case '+':
total = number1 + number2 + number3;
break;
case '-':
total = number1 - number2 - number3;
break;
case '*':
total = number1 * number2 * number3;
break;
case '/':
total = number1 / number2 / number3;
break;
default:
System.out.println("You have entered incorrectly. Please try again.");
return;
}
}
}
public class JavaPresentation_KS {
public static void main(String[] args) {
NumbersEntered nums = new NumbersEntered();
Scanner equation = new Scanner(System.in);
System.out.println("Enter first number: ");
double number1 = equation.nextDouble();
System.out.println("Enter second number: ");
double number2 = equation.nextDouble();
System.out.println("Enter third number: ");
double number3 = equation.nextDouble();
System.out.println("Enter an operator (+, -, *, /): ");
char operator = equation.next().charAt(0);
nums.operatorSeletion(number1, number2, number3, operator);
//invoke the method
System.out.println(number1 + " " + operator + " " + number2 + " " + operator + " " + number2 + " = " + nums.total);
//Access at location (nums.total)
}

Related

Java use user input from other methods

I visited other questions similar to mine but did not find the one that is applicable to me.
To lessen my line of codes instead of copy pasting that input process to my if else statement. I created a UInputs(); method that will get user inputs. So I can just call it whenever it is needed but i cant use the user inputted values inside UInputs().
import java.util.Scanner;
public class Calculator {
public static void UInputs(){
double num1, num2, num3, num4, num5;
Scanner scan = new Scanner(System.in);
System.out.print("1st Number: ");
num1 = scan.nextDouble();
System.out.print("2nd Number: ");
num2 = scan.nextDouble();
System.out.print("3rd Number: ");
num3 = scan.nextDouble();
System.out.print("4th Number: ");
num4 = scan.nextDouble();
System.out.print("5th Number: ");
num5 = scan.nextDouble();
}
public static void main (String[] args){
char Choice;
double num1, num2, num3, num4, num5;
System.out.println("\t_________________________________\n");
System.out.println("\t|\tMATH OPERATIONS\t\t|\n\t|\t[+]\tAddition\t|\n\t|\t[-]\tSubtraction\t|\n\t|\t[*]\tMultiplication\t|\n\t|\t[/]\tDivision\t|\n");
System.out.println("\t|_______________________________|\n");
System.out.print("\nEnter you Choice: ");
Scanner scan = new Scanner(System.in);
Choice = scan.nextLine().charAt(0);
if ( Choice == '+') {//ADDITION
System.out.println("================================\nAddition\n");
UInputs();
double answer = num1 + num2 + num3 + num4 + num5;
System.out.println("\nSum : " + answer );
System.out.println("================================\n");
}
else if (Choice == '-') {//SUBTRACTION
System.out.println("================================\nSubtraction\n");
System.out.print("1st Number: ");
num1 = scan.nextDouble();
System.out.print("2nd Number: ");
num2 = scan.nextDouble();
System.out.print("3rd Number: ");
num3 = scan.nextDouble();
System.out.print("4th Number: ");
num4 = scan.nextDouble();
System.out.print("5th Number: ");
num5 = scan.nextDouble();
double answer = num1 - num2 - num3 - num4 - num5;
System.out.println("\nDifference : " + answer );
System.out.println("================================\n");
}
Not the best answer I could have come up with but certainly some improvements to make the code easier to digest...
I changed UInputs to a method called calculate(). It now takes the function selected as input and then asks the user for 5 numbers. The function is then applied to the 5 numbers. Another way to perform this calculation would be to request a number from the user, return it, and sequentially apply the function to the returned number(s) to get a result... this would be nicer.
import java.util.Scanner;
public class Calculator {
private static final Scanner scan = new Scanner(System.in);
/**
* My initial thought here was that UInputs should return values
* and these should be cumulatively totalled.
* There's no need to hold the inputs in memory since
* once they're consumed, they're not longer needed.
*/
public static double calculate(char functionToApply) {
double[] inputs = new double[5];
// works for number of inputs up to 20 - could just print "number i: " here for simplicity.
for (int i=0; i<inputs.length; i++) {
String promptMessage = (i+1) + ""; // number
// postfixture (st, nd, rd, th)
switch (i+1) {
case 1: promptMessage = promptMessage+"st"; break;
case 2: promptMessage = promptMessage+"nd"; break;
case 3: promptMessage = promptMessage+"rd"; break;
default: promptMessage = promptMessage+"th"; break;
}
System.out.print(promptMessage + " Number: ");
inputs[i] = scan.nextDouble();
}
double result = 0;
for (int i=0; i<inputs.length; i++) {
switch (functionToApply) {
case '+': result = result + inputs[i]; break;
case '-': result = result - inputs[i]; break;
}
}
return result;
}
public static void main(String[] args) {
displayMenu();
char function;
System.out.print("\nEnter your Choice: ");
function = scan.nextLine().charAt(0);
String heading = "";
String lineLabel = "";
switch (function) {
case '+':
heading = "Addition";
lineLabel = "Sum";
break;
case '-':
heading = "Subtraction";
lineLabel = "Difference";
break;
}
System.out.println("================================\n" + heading + "\n");
System.out.println("\n" + lineLabel + " : " + calculate(function));
System.out.println("================================\n");
}
private static void displayMenu() {
System.out.println("\t_________________________");
System.out.println("\t|\tMATH OPERATIONS\t\t|");
System.out.println("\t|\t[+]\tAddition\t\t|");
System.out.println("\t|\t[-]\tSubtraction\t\t|");
System.out.println("\t|\t[*]\tMultiplication\t|");
System.out.println("\t|\t[/]\tDivision\t\t|");
System.out.println("\t|_______________________|\n");
}
}
This should be easier for you to extend/edit though.
Output:
_________________________
| MATH OPERATIONS |
| [+] Addition |
| [-] Subtraction |
| [*] Multiplication |
| [/] Division |
|_______________________|
Enter your Choice: +
================================
Addition
1st Number: 1
2nd Number: 2
3rd Number: 3
4th Number: 4
5th Number: 5
Sum : 15.0
================================
Process finished with exit code 0
Similarly for subtraction:
Enter your Choice: -
================================
Subtraction
1st Number: 10
2nd Number: 9
3rd Number: 1
4th Number: 0
5th Number: 0
Difference : -20.0
================================
you can create some kind of wrapper class
class MyNumberWrapper {
double num1;
double num2;
}
then UInput will look like this
public static MyNumberWrapper UInputs(){
MyNumberWrapper wrapper = new MyNumberWrapper();
Scanner scan = new Scanner(System.in);
System.out.print("1st Number: ");
wrapper.num1 = scan.nextDouble();
System.out.print("2nd Number: ");
wrapper.num2 = scan.nextDouble();
return wrapper;
}
then in your main function you can just use MyNumberWrapper wrapper = UInput() and access all variables with wrapper.num1, wrapper.num2 etc

Creating a calculator that calls the methods from a separate class using scanner

I'm creating a calculator where each of the calculator's functions have to be in a separate class and called from the main method using scanner input.
1.Add
2.Subtract
3.Multiplication
4.Division
5.Square
6.Power
7.Mod operation
8.Factorial
0.Quit
I must create each method called by an object. The calculator requires one main class (has main () method) and one user defined class which has above calculating methods. The program must let the user choose an operation (one of above calculations) and operand(s) (numbers). Some calculations require two operands. (e.g. A + B, AB) Some calculations require one operand. (e.g. A2, N!) Additional functions:
•Let the calculation function continues until user wants to exit this program.
•When one calculation is done, let user choose another operation.
•This program terminates when user selects END option.
•Implement all operations. Do not use Java library math methods.
I have the code for a program that is using switch statement and case, but our class hasn't even learned any of that. I have looked everywhere online for the past two days and just can't figure it out, so apologies if the solution is simple, and thank you to all help in advance. Here is the code to my program so far.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int choice;
do
{
System.out.println("[1] Add ");
System.out.println("[2] Subtract ");
System.out.println("[3] Multiply ");
System.out.println("[4] Division ");
System.out.println("[5] Square ");
System.out.println("[6] Power ");
System.out.println("[7] Mod Operation ");
System.out.println("[8] Factorial ");
System.out.println("[0] Quit ");
System.out.println("Please enter your choice: ");
choice = s.nextInt();
int num1, num2;
switch(choice)
{
case 1 : System.out.println("Enter two numbers to add: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The sum of " + num1 + " and " + num2 +
" is: " + add(num1, num2));
break;
case 2 : System.out.println("Enter two numbers to subtract: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The difference of " + num1 + " and " + num2 +
" is: " + diff(num1, num2));
break;
case 3 : System.out.println("Enter two numbers to multiply: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The product of " + num1 + " and " + num2 +
" is: " + prod(num1, num2));
break;
case 4 : System.out.println("Enter two numbers to divide: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The quotient of " + num1 + " and " + num2 +
" is: " + quo(num1, num2));
break;
case 5 : System.out.println("A number to square: ");
num1 = s.nextInt();
System.out.println("The square of " + num1 + " is: " + square(num1));
break;
case 6 : System.out.println("Enter the base and the exponent: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The power of " + num1 + " to the " + num2 +
"th power is: " + power(num1, num2));
break;
case 7 : System.out.println("Enter two numbers to get the interger remainder of (modulo): ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The modulo of " + num1 + " and " + num2 +
" is: " + mod(num1, num2));
break;
case 8 : System.out.println("Enter a number to get the factorial of: ");
num1 = s.nextInt();
System.out.println("The factorial of " + num1 + " is: " + factorial(num1));
break;
case 0: System.out.println("Thank you for using my program...good bye!");
System.exit(0);
}
}
while(choice != 0);
s.close();
}
public static int add(int num1, int num2)
{
return num1 + num2;
}
public static int diff(int num1, int num2)
{
return num1 - num2;
}
public static int prod(int num1, int num2)
{
return num1 * num2;
}
public static double quo(int num1, int num2)
{
return (double)num1 / num2;
}
public static int mod(int num1, int num2)
{
return num1 % num2;
}
public static long power(int base, int exp)
{
long result = 1;
while (exp != 0)
{
result *= base;
--exp;
}
return result;
}
public static int square(int num)
{
return num * num;
}
public static int factorial(int base)
{
if (base == 0)
return 1;
else
return(base * factorial(base - 1));
}
}
you can use a separate class called Functions with static methods
public class Functions{
public static int add(int num1, int num2)
{
return num1 + num2;
}
public static int diff(int num1, int num2)
{
return num1 - num2;
}
public static int prod(int num1, int num2)
{
return num1 * num2;
}
public static double quo(int num1, int num2)
{
return (double)num1 / num2;
}
public static int mod(int num1, int num2)
{
return num1 % num2;
}
public static long power(int base, int exp)
{
long result = 1;
while (exp != 0)
{
result *= base;
--exp;
}
return result;
}
public static int square(int num)
{
return num * num;
}
public static int factorial(int base)
{
if (base == 0)
return 1;
else
return(base * factorial(base - 1));
}
}
and you call these methods Functions.add(num1, num2))
I'm not sure if that what you want
Here is an approach, which may be useful to you. I have done implementation for Addition and Subtraction, you can follow the same thing for other operations as well. You may want to have abstract class for single operand operations as well.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int choice;
do {
System.out.println("[1] Add ");
System.out.println("[2] Subtract ");
System.out.println("[3] Multiply ");
System.out.println("[4] Division ");
System.out.println("[5] Square ");
System.out.println("[6] Power ");
System.out.println("[7] Mod Operation ");
System.out.println("[8] Factorial ");
System.out.println("[0] Quit ");
System.out.println("Please enter your choice: ");
choice = s.nextInt();
int num1, num2;
switch (choice) {
case 1:
Addition addition = new Addition(s);
addition.performOperation();
break;
case 2:
Subtraction subtraction = new Subtraction(s);
subtraction.performOperation();
break;
case 3:
System.out.println("Enter two numbers to multiply: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The product of " + num1 + " and " + num2 +
" is: " + prod(num1, num2));
break;
case 4:
System.out.println("Enter two numbers to divide: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The quotient of " + num1 + " and " + num2 +
" is: " + quo(num1, num2));
break;
case 5:
System.out.println("A number to square: ");
num1 = s.nextInt();
System.out.println("The square of " + num1 + " is: " + square(num1));
break;
case 6:
System.out.println("Enter the base and the exponent: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The power of " + num1 + " to the " + num2 +
"th power is: " + power(num1, num2));
break;
case 7:
System.out.println("Enter two numbers to get the interger remainder of (modulo): ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The modulo of " + num1 + " and " + num2 +
" is: " + mod(num1, num2));
break;
case 8:
System.out.println("Enter a number to get the factorial of: ");
num1 = s.nextInt();
System.out.println("The factorial of " + num1 + " is: " + factorial(num1));
break;
default:
System.out.println("Your choices should be 0 to 8!");
break;
}
}
while (choice != 0);
s.close();
System.out.println("Thank you for using my program...good bye!");
System.exit(0);
}
public static int prod(int num1, int num2) {
return num1 * num2;
}
public static double quo(int num1, int num2) {
return (double) num1 / num2;
}
public static int mod(int num1, int num2) {
return num1 % num2;
}
public static long power(int base, int exp) {
long result = 1;
while (exp != 0) {
result *= base;
--exp;
}
return result;
}
public static int square(int num) {
return num * num;
}
public static int factorial(int base) {
if (base == 0)
return 1;
else
return (base * factorial(base - 1));
}
}
abstract class OperationWithTwoOperands {
protected String prompt;
private Scanner scanner;
public OperationWithTwoOperands(Scanner scanner) {
this.scanner = scanner;
}
public void performOperation() {
System.out.println(prompt);
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
operation(num1, num2);
}
abstract protected void operation(int operand1, int operand2);
}
class Addition extends OperationWithTwoOperands {
public Addition(Scanner scanner) {
super(scanner);
prompt = "Enter two numbers to add:";
}
#Override
protected void operation(int num1, int num2) {
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + (num1 + num2));
}
}
class Subtraction extends OperationWithTwoOperands {
public Subtraction(Scanner scanner) {
super(scanner);
prompt = "Enter two numbers to subtract:";
}
#Override
protected void operation(int num1, int num2) {
System.out.println("The difference of " + num1 + " and " + num2 + " is: " + (num1 - num2));
}
}

logical bug in my code in java... in switch case

package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int operator;
double number1, number2, result;
boolean ask = true;
while (ask) {
System.out.println("please select your operator:\n"
+ "1 for +\n" +
"2 for -\n" +
"3 for *\n" +
"4 for %\n" +
"");
operator = myScanner.nextInt();
System.out.println("you chose " + operator + " operator babe");
System.out.println("please enter your first number");
Scanner numberScanner = new Scanner(System.in);
number1 = numberScanner.nextDouble();
System.out.println("please enter your second number");
Scanner numberScanner2 = new Scanner(System.in);
number2 = numberScanner2.nextDouble();
switch (operator) {
case 1:
result = number1 + number2;
System.out.println("result is:" + result);
break;
case 2:
result = number1 - number2;
System.out.println("result is:" + result);
break;
case 3:
result = number1 * number2;
System.out.println("result is:" + result);
break;
case 4:
result = number1 / number2;
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("do yo want to continue?\n" +
"y for yes\n" +
"n for no\n");
char askInput = myScanner.next().charAt(0);
if (askInput=='n') ask=false;
}
}
}
i got trouble in my switch case
if i press any number or letter somthing like 5 or 6 or... it should print you chose wrong operator.
i think problem is in my default but i don't know where is it?
Just reorder your code like this
`public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int operator;
double number1, number2, result;
boolean ask = true;
while (ask) {
System.out.println("please enter your first number");
Scanner numberScanner = new Scanner(System.in);
number1 = numberScanner.nextDouble();
System.out.println("please enter your second number");
Scanner numberScanner2 = new Scanner(System.in);
number2 = numberScanner2.nextDouble();
System.out.println("please select your operator:\n"
+ "1 for +\n"
+ "2 for -\n"
+ "3 for *\n"
+ "4 for %\n"
+ "");
operator = myScanner.nextInt();
switch (operator) {
case 1:
result = number1 + number2;
System.out.println("result is:" + result);
break;
case 2:
result = number1 - number2;
System.out.println("result is:" + result);
break;
case 3:
result = number1 * number2;
System.out.println("result is:" + result);
break;
case 4:
result = number1 / number2;
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("you chose " + operator + " operator babe");
System.out.println("do yo want to continue?\n"
+ "y for yes\n"
+ "n for no\n");
char askInput = myScanner.next().charAt(0);
if (askInput == 'n') {
ask = false;
}
}
}`
and you'll be fine
as for my comment, if you want to validate the input the user does (for the option) before having the user input another 2 numbers, than, yeah you should actually programm it that way that the validation goes RIGHT AFTER the first userinput. Here´s a slightly corrected version of your code.
public static void main(String[] args) {
int operator;
double result;
boolean ask = true;
Scanner numberScanner = new Scanner(System.in);
while (ask) {
System.out.println(
"please select your operator:\n" + "1 for +\n" + "2 for -\n" + "3 for *\n" + "4 for %\n" + "");
operator = numberScanner.nextInt();
System.out.println("you chose " + operator + " operator babe");
// Here was your "Mistake". You instantly started asking the user for another input,
// but actually wanted to ahve the switch statment here
switch (operator) {
case 1:
result = get_num1(numberScanner) + get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 2:
result = get_num1(numberScanner) - get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 3:
result = get_num1(numberScanner) * get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 4:
result = get_num1(numberScanner) % get_num2(numberScanner);
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("do yo want to continue?\n" + "y for yes\n" + "n for no\n");
char askInput = numberScanner.next().charAt(0);
if (askInput == 'n')
ask = false;
}
}
public static double get_num1(Scanner scanner) {
System.out.println("please enter your first number");
return scanner.nextDouble();
}
public static double get_num2(Scanner scanner) {
System.out.println("please enter your second number");
return scanner.nextDouble();
}
simply you could validate the operator while you assign it with the input.
for example use if condition and check whether its between 1 and 5 and if not print whatever you want
2 things:
you dont need 2 scanners using only one will be enough
the code is behaving so because you go into the switch case AFTER asking the numbers you want to operate...
some condition like:
operator = myScanner.nextInt();
if (operator < 1 || operator > 4) {
}
may help....

Calculator in Java: How to return to the main menu?

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';
}
}
}

Basic calculator in Java

I'm trying to create a basic calculator in Java. I'm quite new to programming so I'm trying to get used to it.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class javaCalculator
{
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("please enter the first number");
num1 = input.nextInt();
System.out.println("please enter the second number");
num2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation == "+");
{
System.out.println("your answer is" + (num1 + num2));
}
if (operation == "-");
{
System.out.println("your answer is" + (num1 - num2));
}
if (operation == "/");
{
System.out.println("your answer is" + (num1 / num2));
}
if (operation == "*")
{
System.out.println("your answer is" + (num1 * num2));
}
}
}
This is my code. It prompts for the numbers and operation, but displays the answers all together ?
Remove the semi-colons from your if statements, otherwise the code that follows will be free standing and will always execute:
if (operation == "+");
^
Also use .equals for Strings, == compares Object references:
if (operation.equals("+")) {
Here is simple code for calculator so you can consider this
import java.util.*;
import java.util.Scanner;
public class Hello {
public static void main(String[] args)
{
System.out.println("Enter first and second number:");
Scanner inp= new Scanner(System.in);
int num1,num2;
num1 = inp.nextInt();
num2 = inp.nextInt();
int ans;
System.out.println("Enter your selection: 1 for Addition, 2 for substraction 3 for Multiplication and 4 for division:");
int choose;
choose = inp.nextInt();
switch (choose){
case 1:
System.out.println(add( num1,num2));
break;
case 2:
System.out.println(sub( num1,num2));
break;
case 3:
System.out.println(mult( num1,num2));
break;
case 4:
System.out.println(div( num1,num2));
break;
default:
System.out.println("Illigal Operation");
}
}
public static int add(int x, int y)
{
int result = x + y;
return result;
}
public static int sub(int x, int y)
{
int result = x-y;
return result;
}
public static int mult(int x, int y)
{
int result = x*y;
return result;
}
public static int div(int x, int y)
{
int result = x/y;
return result;
}
}
CompareStrings with equals(..) not with ==
if (operation.equals("+")
{
System.out.println("your answer is" + (num1 + num2));
}
if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
if (operation .equals( "*"))
{
System.out.println("your answer is" + (num1 * num2));
}
And the ; after the conditions was an empty statement so the conditon had no effect at all.
If you use java 7 you can also replace the if statements with a switch.
In java <7 you can test, if operation has length 1 and than make a switch for the char [switch (operation.charAt(0))]
import java.util.Scanner;
public class AdditionGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("Please Enter The First Number");
num1 = input.nextInt();
System.out.println("Please Enter The Second Number");
num2 = input.nextInt();
Scanner op = new Scanner (System.in);
System.out.println("Please Enter The Operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("Your Answer is "+(num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("Your Answer is "+(num1 - num2));
}
else if (operation.equals("*"))
{
System.out.println("Your Answer is "+(num1 * num2));
}
else if (operation.equals("/"))
{
System.out.println("Your Answer is "+(num1 / num2));
}
}
}
Java program example for making a simple Calculator:
import java.util.Scanner;
public class Calculator
{
public static void main(String args[])
{
float a, b, res;
char select, ch;
Scanner scan = new Scanner(System.in);
do
{
System.out.print("(1) Addition\n");
System.out.print("(2) Subtraction\n");
System.out.print("(3) Multiplication\n");
System.out.print("(4) Division\n");
System.out.print("(5) Exit\n\n");
System.out.print("Enter Your Choice : ");
choice = scan.next().charAt(0);
switch(select)
{
case '1' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a + b;
System.out.print("Result = " + res);
break;
case '2' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a - b;
System.out.print("Result = " + res);
break;
case '3' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a * b;
System.out.print("Result = " + res);
break;
case '4' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a / b;
System.out.print("Result = " + res);
break;
case '5' : System.exit(0);
break;
default : System.out.print("Wrong Choice!!!");
}
}while(choice != 5);
}
}
maybe its better using the case instead of if dunno if this eliminates the error, but its cleaner i think.. switch (operation){case +: System.out.println("your answer is" + (num1 + num2));break;case -: System.out.println("your answer is" - (num1 - num2));break; ...
import java.util.Scanner;
import javax.swing.JOptionPane;
public class javaCalculator
{
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("please enter the first number");
num1 = input.nextInt();
System.out.println("please enter the second number");
num2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("your answer is" + (num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
else if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
else if (operation.equals("*"))
{
System.out.println("your answer is" + (num1 * num2));
}
else
{
System.out.println("Wrong selection");
}
}
}
public class SwitchExample {
public static void main(String[] args) throws Exception {
System.out.println(":::::::::::::::::::::Start:::::::::::::::::::");
System.out.println("\n\n");
System.out.println("1. Addition");
System.out.println("2. Multiplication");
System.out.println("3. Substraction");
System.out.println("4. Division");
System.out.println("0. Exit");
System.out.println("\n");
System.out.println("Enter Your Choice ::::::: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int usrChoice = Integer.parseInt(str);
switch (usrChoice) {
case 1:
doAddition();
break;
case 2:
doMultiplication();
break;
case 3:
doSubstraction();
break;
case 4:
doDivision();
break;
case 0:
System.out.println("Thank you.....");
break;
default:
System.out.println("Invalid Value");
}
System.out.println(":::::::::::::::::::::End:::::::::::::::::::");
}
public static void doAddition() throws Exception {
System.out.println("******* Enter in Addition Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Addition : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Addition : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 + no2;
System.out.println("Addition of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doSubstraction() throws Exception {
System.out.println("******* Enter in Substraction Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Substraction : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Substraction : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 - no2;
System.out.println("Substraction of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doMultiplication() throws Exception {
System.out.println("******* Enter in Multiplication Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Multiplication : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Multiplication : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 * no2;
System.out.println("Multiplication of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doDivision() throws Exception {
System.out.println("******* Enter in Dividion Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Dividion : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Dividion : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
float result = no1 / no2;
System.out.println("Division of " + no1 + " and " + no2 + " is ::::::: " + result);
}
}
we can simply use in.next().charAt(0); to assign + - * / operations as characters by initializing operation as a char.
import java.util.*;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char operation;
int num1;
int num2;
System.out.println("Enter First Number");
num1 = in.nextInt();
System.out.println("Enter Operation");
operation = in.next().charAt(0);
System.out.println("Enter Second Number");
num2 = in.nextInt();
if (operation == '+')//make sure single quotes
{
System.out.println("your answer is " + (num1 + num2));
}
if (operation == '-')
{
System.out.println("your answer is " + (num1 - num2));
}
if (operation == '/')
{
System.out.println("your answer is " + (num1 / num2));
}
if (operation == '*')
{
System.out.println("your answer is " + (num1 * num2));
}
}
}
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
int x,
int y;
Scanner input=new Scanner(System.in);
System.out.println("Enter Number 1");
x=input.nextInt();
System.out.println("Enter Number 2");
y=input.nextInt();
System.out.println("Please enter operation + - / or *");
Scanner op=new Scanner(System.in);
String operation = op.next();
if (operation.equals("+")){
System.out.println("Your Answer: " + (x+y));
}
if (operation.equals("-")){
System.out.println("Your Answer: "+ (x-y));
}
if (operation.equals("/")){
System.out.println("Your Answer: "+ (x/y));
}
if (operation.equals("*")){
System.out.println("Your Answer: "+ (x*y));
}
}
}

Categories

Resources