A simple console calculator - java

I have designed a simple console calculator as follows but i need to create a loop where I can re run the program:
So that I won't need to run the program again and again and it can take the input from the user and run by itself.
private static Scanner op;
private static Scanner input;
private static Scanner cont;
public static void main(String args[]) {
double num1;
double num2;
double ans = 0;
double l1;
double l2;
String operation;
input = new Scanner(System.in);
System.out.println("Please input your first number:");
num1= input.nextDouble();
System.out.println("Please input the second numer:");
num2= input.nextDouble();
op = new Scanner(System.in);
System.out.println("Select your operation:");
operation = op.next();
if (operation.equals("+")){
System.out.println("Your Result is :" + (num1+num2));
}
if (operation.equals("-")){
System.out.println("Your Result is:" + (num1-num2));
}
if (operation.equals("/")){
if (num2 == 0){
System.out.println("Your Input is Invalid");}
else {
System.out.println("Your result is :" + (num1/num2));
}
}
if (operation.equals("*")){
System.out.println("Your result is:" + (num1*num2));
}
if (operation.equals("%")){
System.out.println("Your result is:" + (num1*100/num2));
}
if (operation.equals("^")){
ans= Math.pow(num1, num2);
System.out.println("Your result is:"+ans);
}
if (operation.equals("log")){
l1=Math.log(num1);
l2=Math.log(num2);
System.out.println("Your result is:"+l1/l2);
}
operation = cont.next();
System.out.println("Do you wish to perform any other operation?");
if (operation.equals("Yes")){
else{
System.out.println("Thank You");
}
}
}

you can create a function and call it with a loop like this:
private static void myfunction(){
//put your code here
}
public static void main(String[] args) {
//call your function until your condition is false
while(myconditionistrue){
myfunction();
}
}
if you want to ask your user if continue or not use this way:
private static void myfunction() {
//put your code here
}
public static void main(String[] args) {
String exit;
Scanner scan = new Scanner(System.in);
do {
//call your function or you can put all your code here
myfunction();
System.out.println("You want to continue? y : n :");
exit = scan.next();
} while (exit.equals("y"));
}

You can use a while(true) and then just exit at command:
import java.util.Scanner;
class Main {
private static Scanner op;
private static Scanner input;
private static Scanner cont;
public static void main(String args[]) {
double num1;
double num2;
double ans = 0;
double l1;
double l2;
String operation;
while (true) {
input = new Scanner(System.in);
System.out.println("Please input your first number:");
num1 = input.nextDouble();
System.out.println("Please input the second numer:");
num2 = input.nextDouble();
op = new Scanner(System.in);
System.out.println("Select your operation:");
operation = op.next();
if (operation.equals("+")) {
System.out.println("Your Result is :" + (num1 + num2));
}
if (operation.equals("-")) {
System.out.println("Your Result is:" + (num1 - num2));
}
if (operation.equals("/")) {
if (num2 == 0) {
System.out.println("Your Input is Invalid");
} else {
System.out.println("Your result is :" + (num1 / num2));
}
;
}
if (operation.equals("*")) {
System.out.println("Your result is:" + (num1 * num2));
}
if (operation.equals("%")) {
System.out.println("Your result is:" + (num1 * 100 / num2));
}
if (operation.equals("^")) {
ans = Math.pow(num1, num2);
System.out.println("Your result is:" + ans);
}
if (operation.equals("log")) {
l1 = Math.log(num1);
l2 = Math.log(num2);
System.out.println("Your result is:" + l1 / l2);
}
//cont = new Scanner(System.in);
//operation = cont.next();
System.out.println("Do you wish to perform any other operation?");
cont = new Scanner(System.in);
operation = cont.next();
if (operation.equals("Yes")) {
} else {
System.out.println("Thank You");
System.exit(0);
}
}
}
}
Test
Please input your first number:
5
Please input the second numer:
5
Select your operation:
*
Your result is:25.0
Do you wish to perform any other operation?
Yes
Please input your first number:
20
Please input the second numer:
10
Select your operation:
+
Your Result is :30.0
Do you wish to perform any other operation?
No
Thank You

As RealSkeptic stated in his comment, what you need is a loop. You can learn about loops, for example, here. The best choice for this situation is do-while loop.
I have a few more advices to your code:
You don't need to create many scanners to get more inputs than just one. One instance suffices.
When you use many if statements whose conditions are disjoint (by that I mean that if a single condition is true then the rest of the conditions is false), use else-if statements. It is more efficient. See this for more information.
Don't use empty branches in if statement. In this particular example, you can use if (!operation.equals("Yes")). The exclamation mark means negation. So if operation equals "Yes", the whole condition is evaluated as false.
Learn how to divide a complex code into functions (or methods). Generally, one function should provide one simple functionality.

Related

NoSuchElementException error for ATM Machine app (Modified)

I am currently learning Java and I am trying to retain the information I learned by building a ATM machine app (I plan on adding more to it in the future).
My current issue is I would like to ask a user 'What would you like to do' repeatedly until a valid input is provided(current valid inputs are 'Withdraw' and 'Deposit').
I have a loop that will repeatedly ask the user 'Please select a valid choice' if the input is not valid. If the input is valid it will execute only once, ask 'What would you like to do', and then display a NoSuchElementException. Not sure how to fix this.
Here is my code:
App.java
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("What woul you like to do?");
String response = scanner.next().toLowerCase();
Transactions newTransaction = new Transactions();
if (response.equals("withdraw")) {
newTransaction.Withdrawal();
} else if (response.equals("deposit")) {
newTransaction.Deposit();
} else {
System.out.println("Please select a valid choice");
}
}
scanner.close();
}
}
Transactions.java
import java.util.Scanner;
public class Transactions {
private int currentBalance = 100;
public void Withdrawal() {
Scanner scanner = new Scanner(System.in);
System.out.println("How much would you like to withdraw?");
int withdrawAmount = scanner.nextInt();
if (withdrawAmount > 0) {
if (currentBalance > 0) {
currentBalance -= withdrawAmount;
System.out.println("Amount withdrawn: $" + withdrawAmount);
System.out.println("Current Balance: $" + Balance());
if (currentBalance < 0) {
System.out.println(
"You have withdrawn more than you have in current balance.\nYou will be charged a overdraft fee");
}
} else {
System.out.println(
"You have withdrawn more than you have in current balance.\nYou will be charged a overdraft fee");
}
} else {
System.out.println("Can't remove 0 from account");
}
scanner.close();
}
public void Deposit() {
Scanner scanner = new Scanner(System.in);
System.out.println("How much would you like to deposit?");
int depositAmount = scanner.nextInt();
if (depositAmount > 0) {
currentBalance += depositAmount;
Balance();
}
System.out.println("Amount deposited: $" + depositAmount);
System.out.println("Current Balance: $" + Balance());
scanner.close();
}
public int Balance() {
return currentBalance;
}
}
Error Message
NoSuchElementException
You can use a sentinel. A sentinel is a value entered that will end the iteration.
//incomplete code showing logic
int choice;
Scanner input = new Scanner(System.in);
System.out.println("Enter Choice");
choice = input.nextInt();
while(choice != -1){ //-1 is the sentinel, can be value you choose
//Some logic you want to do
System.out.println("Enter choice or -1 to end");
choice = input.NextInt(); //notice we input choice again here
}
Like has been said you should learn about loops. There are two types while-loop and for-loop. In this case you should youse the while-loop.
The implementation of your problem could be this.
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("What woul you like to do?");
String response;
Transactions newTransaction = new Transactions();
while (true) {
response = scanner.next().toLowerCase();
if (response.equals("withdraw")) {
newTransaction.Withdrawal();
break;
} else if (response.equals("deposit")) {
newTransaction.Deposit();
break;
} else {
System.out.println("Please select a valid choice");
}
}
scanner.close();
}
}

Java program skips an input?

Hello,
I was trying to build a simple calculator using basic Java code and understand OOP better, so, I wrote this:
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num1 = input.nextInt();
System.out.println("Enter an operation: ");
String opr;
opr = input.nextLine();
if(opr == "+") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.addition();
} else if (opr == "-") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.subtraction();
} else if (opr == "*") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.multiplication();
} else if (opr == "/") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.division();
} else {
System.out.println("Please, Enter a valid operation!");
}
}
}
and another Class for math operations:
import java.util.Scanner;
public class Operation {
static int Num1;
static int Num2;
Scanner input = new Scanner(System.in);
public Operation(int x, int y) {
x = Num1;
y = Num2;
}
public void addition() {
System.out.println(Num1 + Num2);
}
public void subtraction() {
System.out.println(Num1 - Num2);
}
public void multiplication() {
System.out.println(Num1 * Num2);
}
public void division() {
System.out.println(Num1 / Num2);
}
}
but it doesn't take input for the operation, and it goes straight to the next line of code, like so:
Enter a number:
4
Enter an operation:
Please, Enter a valid operation!
Could anyone, please point my mistake?
Note: I'm a newbie in Java and programming in general. so, please don't mind me if my code isn't the best, I'm still learning.
Hello you had a couple of problems. The nextLine() will return an empty line the first time since nextInt consumes the integer only after receiving a new line char but leaves the new line char in the buffer. Additionally the equals comparison needs to be using opr.equals("+") or a switch statement. And finally your Operation class constructor had the variable assignment backwards. I have also modified the Operation private member variables to follow standard naming conventions and scoping practices. You generally want to make member variables private since if not explicitly defined they will be protected. I would recommend using a good IDE since it can catch a lot of those errors for you, try using the free IntelliJ. Here is an updated version of your code.
public class Operation {
private final int num1;
private final int num2;
public Operation(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
public void addition() {
System.out.println(num1 + num2);
}
public void subtraction() {
System.out.println(num1 - num2);
}
public void multiplication() {
System.out.println(num1 * num2);
}
public void division() {
System.out.println(num1 / num2);
}
}
And your main class
public class Calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num1 = input.nextInt();
System.out.println("Enter an operation: ");
String opr = null;
while(opr == null || opr.length() == 0){
opr = input.nextLine();
}
switch (opr) {
case "+": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.addition();
break;
}
case "-": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.subtraction();
break;
}
case "*": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.multiplication();
break;
}
case "/": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.division();
break;
}
default:
System.out.println("Please, Enter a valid operation!");
break;
}
}
}
Use
input.next
rather than
input.nextLine
as nextInt accepts a number and the new line character \n.
In the switch ts checking for the new line character.

Simple Java Guessing program. Continuing

I am just playing around with java and wanted to make a simple program where the user; me has to guess/type in the correct number until it's correct. What can I do so the program can keep running, printing out "Make another guess" until the user/me puts in the correct number. Maybe a boolean? I'm not sure. This is what I have so far.
import java.util.Scanner;
public class iftothemax {
public static void main(String[] args) {
int myInt = 2;
// Create Scanner object
Scanner input = new Scanner(System.in);
//Output the prompt
System.out.println("Enter a number:");
//Wait for the user to enter a number
int value = input.nextInt();
if(value == myInt) {
System.out.println("You discover me!");
}
else {
//Tell them to keep guessing
System.out.println("Not yet! You entered:" + value + " Make another guess");
input.nextInt();
}
}
You might want to use a while loop to repeat some code:
while (value != myInt) {
System.out.println("Not yet! You entered: " + value + ". Make another guess");
value = input.nextInt();
}
System.out.println("You discovered me!");
This program would do the trick:
public static void main(String [] args){
int myInt = 2;
int value = 0;
Scanner input = new Scanner(System.in);
boolean guessCorrect = false;
while(!guessCorrect){
System.out.println("Not yet! You entered:" + value + " Make another guess");
value = input.nextInt();
if(value == myInt){
guessCorrect = true
}
}
System.out.println("You discover me!");
}
Simply introduce a loop.
import java.util.Scanner;
public class iftothemax {
public static void main(String[] args) {
int myInt = 2;
// Create Scanner object
Scanner input = new Scanner(System.in);
for(;;) {
//Output the prompt
System.out.println("Enter a number:");
//Wait for the user to enter a number
int value = input.nextInt();
if(value == myInt) {
System.out.println("You discover me!");
break;
}
else {
//Tell them to keep guessing
System.out.println("Not yet! You entered:" + value + " Make another guess");
}
}
}
}

Exiting a program with System.exit(0) in java

I am a little confused about how to implement System.exit(0); in my program. What I want to have happen is for the user to type the word "exit" and for the program to terminate. I would also like the program to return "0.0" when "clear" is entered, but I think I am having trouble working with my variables because num1 and num2 are doubles but I want "exit" and "clear" to be acceptable inputs, as well.
If anyone has any insight, that would be greatly appreciated. Here is my code:
package projectapcs;
/**
*
* #author Apple
*/
import java.util.Scanner;
public class ProjectAPCS {
public static void exit(int x){
}
public static void clear(int y){
}
public static void main(String[] args) {
double num1;
double num2;
char char1;
String operation;
Scanner input = new Scanner(System.in);
System.out.println
("Enter 'exit' to quit the calculator, 'help' for more options or 'continue' to use the calculator");
System.out.println
("\nEnter the first number:");
num1 = input.nextInt();
System.out.println
("Display:" + num1);
System.out.println("Please enter operation:");
operation = input.next();
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
if ("+".equals(operation)){
System.out.println((num1 + num2));
}
else if ("-".equals(operation)){
System.out.println((num1 - num2));
}
else if ("/".equals(operation)){
System.out.println((num1 / num2));
}
else if ("*".equals(operation)){
System.out.println((num1 * num2));
}
else if ("-x".equals(operation)){
System.out.println (-num1);
}
else if ("x^2".equals(operation)){
System.out.println (num1 * num1);
}
else if ("sqrt".equals(operation)){
System.out.println (Math.sqrt(num1));
}
else if ("H".equals(num1)){
System.out.println("Type + for the addition of values");
System.out.println("Type - for the substraction of values");
System.out.println("Type * for the multiplcation of values");
System.out.println("Type / for the division of values");
System.out.println("Type negate for the negation of values");
System.out.println("Type ^2 for squaring of values");
}
else if("E".equals(num1)){
System.out.println ("Calculator program terminated...");
System.exit(0);
}
}
}
If you want to allow arbitrary inputs, read input as a String, then convert to double as needed:
String input = scanner.next();
if (input.equals("exit")) {
exit();
else if (input.equals("clear")) {
clear();
} else {
try {
double number = Double.parseDouble(input);
/* do something with `number` */
} catch (NumberFormatException e) {
System.err.println("Not a double.");
}
}

Basic Java Calcualtor: Only addition working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am trying to build a simple calculator that operates on Double values and performs:
+
-
*
/
negation
^2
for some reason, whichever operation i specify when running the program executes the addition function. So when I try to do
5
7
*
I get 12.0 and not 35.
Any suggestions?
I would also really like some help implementing a way to quit this program when the word "exit" is entered. I was thinking something like System.exit(0);
but Im not sure how to implement. this is my code so far:
import java.util.Scanner;
public class Calc {
public static void main(String[] args)
{
double num1;
double num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println ("Enter 'exit' to quit the calculator or 'help' for more options");
System.out.println("Enter the first number:");
num1 = input.nextInt();
System.out.println ("Display:" + num1);
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation:");
operation = op.next();
if (operation == "+");
{
System.out.println((num1 + num2));
}
if (operation == "-"){
{
System.out.println((num1 - num2));
}
if (operation == "/"){
{
System.out.println((num1 / num2));
}
if (operation == "*"){
{
System.out.println((num1 * num2));
}
}
}
there is a semicolon at if (operation.equals("+"));
so, System.out.println((num1 + num2)); will always work
And also replace, == with .equals("+")
as == checks for reference, while equals checks for the value of the variable.
please change operation == to operation.equals("your value")
There are at least three main issues with your code...
Firstly, String comparison in Java is done using .equals not ==
Secondly...
if (operation == "+");
Has a semi-colon at the end, which basically means that even if the condition is meet, it will not run anything, but will skip to the next execution block, which is ...
{
System.out.println((num1 + num2));
}
Thirdly, you have an extra open brace ({) here...
if (operation == "-"){
{
Here...
if (operation == "/"){
{
And here...
if (operation == "*"){
{
Which is going to completely screw up your logic
You should also make use of else-if blocks as well...
Instead, try something like...
if ("+".equals(operation))//;
{
System.out.println((num1 + num2));
}
else if ("-".equals(operation)) //{
{
System.out.println((num1 - num2));
}
else if ("/".equals(operation)) //{
{
System.out.println((num1 / num2));
}
else if ("*".equals(operation)) //{
{
System.out.println((num1 * num2));
}
I've commented out the problem areas so you can see where they exists before hand
try this way
Instead of using == use .equals()
import java.util.Scanner;
public class Calc {
public static void main(String[] args)
{
double num1;
double num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println ("Enter 'exit' to quit the calculator or 'help' for more options");
System.out.println("Enter the first number:");
num1 = input.nextInt();
System.out.println ("Display:" + num1);
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation:");
operation = op.next();
if (operation.equals("+"))
{
System.out.println((num1 + num2));
}
if (operation.equals("-"))
{
System.out.println((num1 - num2));
}
if (operation.equals("/")){
{
System.out.println((num1 / num2));
}
if (operation.equals( "*")){
{
System.out.println((num1 * num2));
}
}
}

Categories