How to add clear option to my command line calculator [duplicate] - java

This question already has answers here:
How to clear the console?
(14 answers)
Closed last year.
I am making a CLI calculator and I am trying to add a clear button but cannot figure out how to clear all the user input and start the display from the beginning. I tried using the reset method and that didn't seem to do the trick.
System.out.println("Enter any of the following:");
System.out.println(" 1 2 3 4 5 6 7 8 9 ");
System.out.println(" + - * / = ");
System.out.println("Enter AC to reset ");
double firstNum = input.nextDouble();
input.nextLine();
if (input.equals(clear)) {
input.reset();
}
System.out.println("Display 1: " + firstNum);
System.out.println("Display 2: " + firstNum);
System.out.println("Operator: ");
String operand = input.nextLine();
System.out.println("Display 1: " + firstNum + " " + operand);
System.out.println("Display 2: " + firstNum );
if (operand.equals("=")) {
break;
}
System.out.println("Enter your next number: ");
double secondNum = input.nextDouble();
input.nextLine();
calculate(firstNum, operand, secondNum);
System.out.println("Display 1: " + firstNum + " " + operand + " " + secondNum );
firstNum = answer;
System.out.println("Display 2: " + answer);
}
System.out.println("Answer: " + answer);
}

I suppose it can't be done. I tried to solve the problem and this is a waste of time. If it helps, you can use special characters like "\b" to delete the previous character or "\r" to write from the beginning of the string. But when you press Enter, you can't change the previous line.

Related

Scanner bug in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
I'm italian (the writings in the prints are in italian). After do the addition, the program ask me an input, and from this input (and another that it ask after) it made an subtraction. I don't know if this is a bug. Can somone help me?
import java.util.Scanner;
public class calcolatrice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numero1;
int numero2;
int numero3;
System.out.println("Menu: "
+ "addition (1), "
+ "subtraction (2), "
+ "multiplication (3), "
+ "division (4), "
+ "exponential (5), "
+ "square root (6)");
System.out.println("\nEnter the number corresponding to the option you want: ");
int opzione = input.nextInt();
if (opzione == 1) {
System.out.print("Enter the first number: ");
numero1 = input.nextInt();
System.out.print("Enter the second number: ");
numero2 = input.nextInt();
numero3 = numero1 + numero2;
System.out.print("The sum between " + numero1 + " and " + numero2 + " is: " + numero3);
} else if (opzione == 2)
System.out.print("\nEnter the first number: ");
numero1 = input.nextInt();
System.out.print("Enter the second number: ");
numero2 = input.nextInt();
numero3 = numero1 - numero2;
System.out.print("The difference between " + numero1 + " and " + numero2 + " is: " + numero3);
}
}
In your original code, you have this logic:
if (opzione == 1) {
// do things
} else if (opzione == 2)
// do other things
That code has a subtle bug present: in the second branch of the if statement, there are no braces; that is, there is not {...}.
Here is the entire block, where I applied code formatting (indendation) as well as line numbers:
1 if (opzione == 1) {
2 System.out.print("Enter the first number: ");
3 numero1 = input.nextInt();
4
5 System.out.print("Enter the second number: ");
6 numero2 = input.nextInt();
7
8 numero3 = numero1 + numero2;
9 System.out.print("The sum between " + numero1 + " and " + numero2 + " is: " + numero3);
10
11 } else if (opzione == 2)
12 System.out.print("\nEnter the first number: ");
13
14 numero1 = input.nextInt();
15
16 System.out.print("Enter the second number: ");
17 numero2 = input.nextInt();
18
19 numero3 = numero1 - numero2;
20 System.out.print("The difference between " + numero1 + " and " + numero2 + " is: " + numero3);
A few comments:
Line 12: This is indented once, which corresponds to the if statement – that is, if opzione has a value of 2, it will then proceed to run line 12.
Line 14: This is not indented. Note that the code formatter did this automatically (I'm using IntelliJ, though there are many other options). The formatter understood that line 14 is not part of the if statement from line 11.
Lines 16-20: Just like with line 14, these are lines of that code that run independently of the if statements on line 1 or line 11. This is why you observed that it prompts you for additional things after choosing the "addition" path.
To fix your code:
Line 11: Add an open brace ({) at the end of the line, changing this:
} else if (opzione == 2)
to this:
} else if (opzione == 2) {
Line 21: Add a new line at the end (after the call to System.out.print), with a single closing brace (}) – this is the other end of { from Line 11

How can I find the multiple of two numbers using Java Modulus

This is the code that I have so far. I just want to know if I'm correct. I am very new to this and most likely I'm correct but I still wanted to know. thanks
Scanner input = new Scanner(System.in);
//variables
int number1;
int number2;
System.out.println("enter first number: ");
number1 = input.nextInt();
System.out.println("enter first number: ");
number2 = input.nextInt();
int multiple = number1 % number2;
if((number1 % number2) == 0) {
System.out.println("Yes, " + number1 + " is a multiple of " + number2);
}
else {
System.out.println("No, " + number1 + " is not a multiple of " + number2);
}
System.out.println("The multiple is: " + multiple);
}
I guess you want if a number is divisible by other or not and want to get multiplier if so.
Scanner input = new Scanner(System.in);
//variables
int number1;
int number2;
System.out.println("enter first number: ");
number1 = input.nextInt();
System.out.println("enter second number: ");
number2 = input.nextInt();
if((number1 % number2) == 0) {
System.out.println("Yes, " + number1 + " is a multiple of " + number2);
System.out.println("The multiple is: " + (number1 / number2));
}
else {
System.out.println("No, " + number1 + " is not a multiple of " + number2);
}
Your code works fine. But if you consider couple of things here it would be good.
Change your second prompt to "enter second number"
Currently you are printing message "The multiple is: " every time whether you find multiple or not.
So print this message only when you found a multiple. Move this line to if block to achieve this.

Making a calculator using switch case

The result i get :
Enter a number :
5
Enter another number :
4
What do you want to perform on these numbers?
You have entered a wrong action, please try again
Where did i go wrong in my code?
import java.util.Scanner;
public class App {
public static void main(String[] args) {
double num1, num2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number : ");
num1 = sc.nextDouble();
System.out.println("Enter another number : ");
num2 = sc.nextDouble();
System.out.println("What do you want to perform on these numbers? ");
String word = sc.nextLine();
sc.close();
double result = 0;
switch (word) {
case "Addition":
result = num1 + num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Subtraction":
result = num1 - num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Multiplication":
result = num1 * num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Division":
result = num1 / num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
default:
System.out.println("You have entered a wrong action, please try again ");
break;
}
}
}
Instead of using sc.nextline() on line 15 use sc.next(). The program will now wait for your input before continuing.
Can you change your code like below:
System.out.println("What do you want to perform on these numbers? ");
sc.nextLine(); // ADD THIS LINE
String word = sc.nextLine();
The problem here is with the num2 = sc.nextDouble(); the newline char is not consumed.
Below is the code I use:
public static void main(String args[]) throws Exception {
// A1Pattern.printPattern(26);
double num1, num2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number : ");
num1 = sc.nextDouble();
System.out.println("Enter another number : ");
num2 = sc.nextDouble();
System.out.println("What do you want to perform on these numbers? ");
sc.nextLine();
String word = sc.nextLine();
sc.close();
double result = 0;
switch (word) {
case "Addition":
result = num1 + num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Subtraction":
result = num1 - num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Multiplication":
result = num1 * num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Division":
result = num1 / num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
default:
System.out.println("You have entered a wrong action, please try again ");
break;
}
}
OUTPUT:
Enter a number :
1
Enter another number :
2
What do you want to perform on these numbers?
Subtraction
1.0 Subtraction 2.0 : -1.0
The java.util.Scanner.next() method finds and returns the next complete token from this scanner.
Use scanner.next() instead of scanner.nextLine().

Simple Calculator Operation

I am attempting to simplify my long code of a calculator program, but I have a road block. I have a new else if statement for each calculator operator, but what I want to do is allow the user to manually type in, on one line, the entire operation they would like to perform and have the code compute it.
Here's what I have:
do {
System.out.println("What function would you like to perform?");
System.out.print("Exit Calculator (Q), Add (+), Subtract (-), Multiply (x), Divide (/): ");
maininput = in.next();
if (maininput.equals("+")) {
System.out.print("Enter the first number to add: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to add: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + answer);
System.out.println();
}
else if (maininput.equals("-")) {
System.out.print("Enter the first number to subtract: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to subtract: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("x")) {
System.out.print("Enter the first number to multiply: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to multiply: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 * num2;
System.out.println(num1 + " x " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("/")) {
System.out.print("Enter the first number to divide: ");
num1 = in.nextDouble();
do {
System.out.print("Enter the second number to divide: ");
num2 = in.nextDouble();
System.out.println();
if (num2 == 0) {
System.out.println("Cannot divide by 0! Please enter a different number.");
}
} while (num2 == 0);
answer = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("Q") || maininput.equals("q") || maininput.equals("EXIT") || maininput.equals("exit")) {
in.close();
System.exit(0);
}
else {
System.out.println(maininput + " is not a valid operand. Please try again.");
System.out.println();
}
} while (maininput != "Q" && maininput != "q");
This is what I want the output to be:
Enter operation:
4 * 6
4 * 6 = 24
Should be able to enter any operation here on one line. I am not asking you to write my calculator for me, I am asking how to allow the computer to read in the entire operation off one line and compute it, then print it.
If you use scanner readLine then you can read a whole line
e.g.
4 * 6
This line can then be split to get three tokens
String tokens [] = line.split (" ");
then you can see what operation to do based upon token[1]
if (token[1].equals ("-") {
//lets minus token[2] from token[0]
// need to convert String to Number
}
You can use String.split and store it in an array. Then it will return an array of string, parse those back to integers. the do the operation you want. The x variable will be the result.
if(maininput.contains("+")) {
String[] stringarr = string.split("\\+");
int x = Integer.parseInt(stringarr[0]) + Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " + " + stringarr[1] + " = " + x);
} else if(maininput.contains("-")) {
String[] stringarr = string.split("\\-");
int x = Integer.parseInt(stringarr[0]) - Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " - " + stringarr[1] + " = " x);
}
... And so on.
You could try parsing the line using a Pattern object, something like this:
Pattern opPattern = Pattern.compile("(\\d+) *([+-*/]) *(\\d+)");
Matcher matcher = opPattern.matcher(userLine);
if(matcher.find()) {
int op1 = Integer.toValue(matcher.group(1));
int op2 = Integer.toValue(matcher.group(3));
String op = matcher.group(2);
if(op.equals("+")) {
// do + op ...
} else ... {
// etc...
}
} else {
// error in line, not the form of an operation
}
Have a look at the javadoc, as I'm not sure if I used the correct method names and the like, just tried to illustrate the idea...

Java calculator not executing if-statement [duplicate]

This question already has answers here:
Using scanner.nextLine() [duplicate]
(5 answers)
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I'm relatively new to programming and have recently started learning Java in order to move into Android programming. I thought I would create a very simple calculator to practice, but it seems that my if statement doesn't work.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
//Create new scanner object
Scanner numInput = new Scanner( System.in );
//Enter first number
System.out.println("Please enter the first number: ");
int num1 = numInput.nextInt();
//Enter the second number
System.out.println("Please enter the second number: ");
int num2 = numInput.nextInt();
//Choose the operation to perform (+,-,*,/)
System.out.println("What operation would you like to do?");
System.out.println("Type \"+\" to add.");
System.out.println("Type \"-\" to subtract.");
System.out.println("Type \"*\" to multiply.");
System.out.println("Type \"/\" to divide.");
String opChoice = numInput.nextLine();
//Add
if (opChoice.equals("+")) {
int ans = num1 + num2;
System.out.println("Adding " + num2 + " to " + num1 + " equals " + ans + ".");
}
//Subtract
else if (opChoice.equals("-")) {
int ans = num1 - num2;
System.out.println("Subtracting " + num2 + " from " + num1 + " equals " + ans + ".");
}
//Multiply
else if (opChoice.equals("*")) {
int ans = num1 + num2;
System.out.println("Multiplying " + num2 + " with " + num1 + " equals " + ans + ".");
}
//Divide
else if (opChoice.equals("/")) {
int ans = num1 + num2;
System.out.println("Dividing " + num1 + " by " + num2 + " equals " + ans + ".");
}
}
}
I am using the Eclipse IDE, and it runs fine until it asks for which operation to do. It will display the options but won't let me enter anything (I've been testing it with multiplying 5 by 2).
I searched for similar questions and tried what they suggested, but it still doesn't seem to work. I would appreciate any help, I assume this is probably just some simple error I am making, so I apologize if this seems like a silly question!
EDIT: Thanks for the quick responses, guys! I appreciate it. And yes, I fixed the multiply and division. :)
The problem is that nextInt() doesn't consume (doesn't read) the new-line character (that you input when you press [Enter]). One way to solve this is calling nextLine() after each nextInt():
//Enter first number
System.out.println("Please enter the first number: ");
int num1 = numInput.nextInt();
numInput.nextLine(); // Add this
//Enter the second number
System.out.println("Please enter the second number: ");
int num2 = numInput.nextInt();
numInput.nextLine(); // Add this
Another way to solve this, would be reading the numbers with nextLine() (which returns a String) and then parsing it to a int:
int num1 = Integer.parseInt(numInput.nextLine());
You won't need to add an extra nextLine() because the new-line character is being consumed by the nextLine() already called.
Also, as #sotondolphin suggested, you may want to check your * and / operations.
The issue is that when numInput.nextInt(); is called, you get the number entered ... but it leaves the newline (\n). Your call to numInput.nextLine(); then gets an empty string.
Replacing that call with numInput.next() will solve the problem as it has a slightly different behavior:
public String next()
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
The default delimiter pattern is whitespace, which includes \n and what's in the input stream after you enter the operation (using * as example) is now \n*\n
The code below does addition but not expected multiplication and division. Could you please check the source?
//Multiply
else if (opChoice.equals("*")) {
int ans = num1 + num2;
System.out.println("Multiplying " + num2 + " with " + num1 + " equals " + ans + ".");
}
//Divide
else if (opChoice.equals("/")) {
int ans = num1 + num2;
System.out.println("Dividing " + num1 + " by " + num2 + " equals " + ans + ".");
}
}

Categories