Newbie to Java; I've created a Command line calculator that gets a double from user and gets one operation symbol and gets another double from user and the calculates the amount.
This is my code.
import java.util.Scanner;
public class forthProblem {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double numb1, numb2, add, subtract, multiply, divide;
char operation;
while (true) {
System.out.println("Calculate: ");
numb1 = in.nextDouble();
operation = in.next().charAt(0);
numb2 = in.nextDouble();
switch (operation) {
case '+':
add = numb1 + numb2;
System.out.println(add);
break;
case '-':
subtract = numb1 - numb2;
System.out.println(subtract);
break;
case '*':
multiply = numb1 * numb2;
System.out.println(multiply);
break;
case '/':
divide = numb1 / numb2;
System.out.println(divide);
break;
}
}
}
}
What I want to figure out is how to be able to get multiple numbers from users and do multiple operations.
for example a user could type (3+4)*4/6= and get an answer.
Also I would like to implement the bedmas in the new code.
I'll appreciate your guidance.
In order to implement PEMDAS and do multiple operations, you will need to keep all input until the user sends in '='. One way to do this is reverse polish notation. Just transform the string to RPN and then run through the equation.
Related
i am new to a java program and i have a homework where when i get input from a user as an string, i have to convert it to a double and multiple it with a .11111 using a switch decision structure.
A string input from user has to be a number in roman numeral which is I, II, III, IV, and so on....
//This is my program
package practiceNum;
import java.util.Scanner;
public class practiceNum{
class stastic void main(String[] args){
String num_In_Roman; //declare a string
Scanner keyboard = new Scanner(System.in); //read input words
System.out.println("Enter a roman numerals from I to X: "); //asking user input
num_In_Roman = keyboard.nextLine();
switch(num_In_Roman){
case "I":
break;
case "II":
break;
//and so on until 10 (X) in roman numerals.
default:
System.out.println("Invalid Number!");
}
//end of body program here
}
}
Here's what i did to calculate my math but still giving me an error.
Double value = Double.parseDouble(num_In_Roman); //convert string into double
case "I":
value *= .111111;
System.out.println(value);
break;
someone help please.
This is the bad way, but this is what you can do:
case "I":
value = 1 * .111111;
System.out.println(value);
break;
case "II":
value = 2 * .111111;
System.out.println(value);
break;
After calculator() has ran, my program pauses...unless I enter an input to unpause the program. Then it continues to run and it prints out. However the input that I entered earlier to unpause the program is stored into answer. Please read my comments in the code to have a better understanding. If you still don't understand then feel free to copy the code to see what I am talking about.
public static void main(String[] args) {
boolean repeat = true;
while (repeat){
calculator(); //-Program pauses after this has ran.
System.out.println("Do you wish to repeat(y/n)?"); // This does not appear unless I enter an input.
String answer = userInput.next(); //The input that I entered earlier to unpause the program gets stored into answer.
if (answer.equalsIgnoreCase("y")){
repeat = true;
} else { repeat = false;}}} //Program terminates here because the input that I used to unpause the program isn't "y".
Full code below:
package calculatorAttempt;
import java.util.Scanner;
class CalculatorV2 {
static Scanner userInput = new Scanner(System.in);
public static void calculator(){
System.out.print(":");
if (userInput.hasNextInt()){
int num1 = userInput.nextInt();
System.out.print(":");
String inString = userInput.next();
System.out.print(":");
int num2 = userInput.nextInt();
System.out.print("=");
if (inString.equals("+")){
System.out.print(num1+num2);}
if (inString.equals("-")){
System.out.print(num1-num2);}
if (inString.equals("*")||(inString.equalsIgnoreCase("x"))){
System.out.print(num1+num2);}
if (inString.equals("/")){
float intTofloat = (float)num1/num2;
System.out.println(intTofloat);} }//If Integer
if (userInput.hasNextFloat()){
float num1 = userInput.nextFloat();
System.out.print(":");
String inString = userInput.next();
System.out.print(":");
float num2 = userInput.nextFloat();
System.out.print("=");
if (inString.equals("+")){
System.out.print(num1+num2);}
if (inString.equals("-")){
System.out.print(num1-num2);}
if (inString.equals("*")||(inString.equalsIgnoreCase("x"))){
System.out.print(num1*num2);}
if (inString.equals("/")){
System.out.print(num1/num2);} }//If Float
}//Public Void Calculator
public static void main(String[] args) {
boolean repeat = true;
while (repeat){
calculator();
System.out.println("Do you wish to repeat(y/n)?");
String answer = userInput.next();
if (answer.equalsIgnoreCase("y")){
repeat = true;
} else { repeat = false;}}
}//Main
}//Class
I am beginner so please bear with me :^) . Thanks.
This happens because of this line:
if (userInput.hasNextFloat()){
The hasNext...() methods in Scanner are blocking methods. They block if there is no input other than white space in the scanner, waiting for something to be entered. As soon as something real (not spaces or newlines) is entered, then they check whether it is a float, an int or whatever, and return a true/false reply to you.
After you finish an integer calculation, your program calls hasNextFloat(), and therefore, it blocks, waiting until you enter something. If that something is not a float, it will return false, and the if will not work.
You can experiment a little and see:
If you run your program and start with a float (say, 17.2), the program will show you the Do you wish to repeat? question after it calculates the result.
If you run your program and start with an int, and then, after you get the result, enter a float, it will print the : that is asking you for the float operator.
So basically, that should not be an if. It should be an else if structure.
Just use else if instead of if to check userInput.hasNextFloat().
Your code sample will look like.
if (userInput.hasNextInt()){
int num1 = userInput.nextInt();
....
....
....
} else if (userInput.hasNextFloat()){
float num1 = userInput.nextFloat();
....
....
...
}
You must use hasNext() instead of hasNextInt() and remove the if(hasNextFloat()) part. And use the Number class because it accepts both ints and floats:
if (userInput.hasNext()) {
Number num1 = userInput.nextByte();
System.out.print(":");
String inString = userInput.next();
System.out.print(":");
Number num2 = userInput.nextByte();
System.out.print("=");
switch (inString) {
case "+":
System.out.print(num1.doubleValue() + num2.doubleValue());
break;
case "-":
System.out.print(num1.doubleValue() - num2.doubleValue());
break;
case "*":
case "x":
case "X":
System.out.print(num1.doubleValue() * num2.doubleValue());
break;
case "/":
double intTofloat = num1.doubleValue() / num2.doubleValue();
System.out.println(intTofloat);
break;
default:
System.out.println(INVALID OPERATOR!);
break;
}
}
I am just learning how to use switch statements. I am trying to create a shopping cart of items sold at a grocery store. I have to create a program that adds the values of the items sold and then print the final value. This is what I have so far but when I terminate my program I get an error and it doesn't display the final value.
Any help is much appreciated!!
package Exercises;
import java.util.Scanner;
public class CalculatingSales {
public static void main(String[] args)
{
int total = 0;
int prod1Count = 0, prod2Count = 0, prod3Count = 0, prod4Count = 0, prod5Count = 0;
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n %s%n %s%n %s%n","Enter product number sold: " //prompt user to enter input
,"NOTE: Product number must be between 1 & 5",
"To terminate input... ",
"On UNIX/Linus?mac OS X type <Ctrl> d then press Enter",
"On Windows type <Ctrl> z then press Enter");
while(input.hasNext())
{
int item = input.nextInt();
total =+ item;
double product1;
double product2;
double product3;
double product4;
double product5;
switch (item + total)
{
case 1:
product1 = 2.98;
++prod1Count;
break;
case 2:
product2 = 4.50;
++prod2Count;
break;
case 3:
product3 = 9.98;
++prod3Count;
break;
case 4:
product4 = 4.49;
++prod4Count;
break;
case 5:
product5 = 6.87;
++prod5Count;
break;
default:
System.out.println("ERROR. You did not enter a value between 1 & 5!");
break;
}//end switch
}//end while
double shoppingCart = (double) total;
System.out.printf("%nTotal retail value of all products is: $%d", shoppingCart);
}
}
The problem is here:
System.out.printf("%nTotal retail value of all products is: $%d", shoppingCart);
The printf is expecting an int but you are passing an double as an argument.
Try this:
System.out.printf("%nTotal retail value of all products is: $%.2f", shoppingCart);
Also you should change total =+ item; to total += item;
There are a number of problems with the code. The error at the end is because you are trying to output a double and specifying an integer to print. $%d should be $%f however to make money display to two decimal places you can use $%.2f. More information on formatting can be found in this documentation
The major problems though are in your loop. The switch statement should only be passed the item number you want to compare to and do something accordingly.So the switch simply has to be switch (item) . There is a simpler way to do the total and do the switch. You can keep a running total by adding to it the value of the product the person selected each time through the loop. Upon exiting it should be the total amount for all the items selected. If you enter an item out of range it effectively adds 0.
At the end you really should close the scanner to do proper cleanup so input.close() would be a good idea as well.
The code could look something like:
package Exercises;
import java.util.Scanner;
public class CalculatingSales {
public static void main(String[] args)
{
double total = 0.0;
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n %s%n %s%n %s%n","Enter product number sold: " //prompt user to enter input
,"NOTE: Product number must be between 1 & 5",
"To terminate input... ",
"On UNIX/Linus?mac OS X type <Ctrl> d then press Enter",
"On Windows type <Ctrl> z then press Enter");
while(input.hasNext())
{
double prodvalue = 0.0;
int item = input.nextInt();
switch (item)
{
case 1:
prodvalue = 2.98;
break;
case 2:
prodvalue = 4.50;
break;
case 3:
prodvalue = 9.98;
break;
case 4:
prodvalue = 4.49;
break;
case 5:
prodvalue = 6.87;
break;
default:
System.out.println("ERROR. You did not enter a value between 1 & 5!");
break;
}//end switch
total += prodvalue;
}//end while
double shoppingCart = total;
System.out.printf("%nTotal retail value of all products is: $%.2f", shoppingCart);
input.close();
}
}
There are much better ways of doing this but as time goes on you will probably learn how this program could be simplified. I wanted to keep the code somewhat structured the way you seemed to be handling things.
If you need the counts of each individual item then you will have to modify the code above to add them back in. I realize this solution may have oversimplified what you needed but at a basic level it keeps the overall total right.
This question already has answers here:
Simple Java calculator
(10 answers)
Closed 8 years ago.
Trying to make a simple calculator in Java but I keep getting errors when I try to compile it. Not sure if it's the coding or something I am doing when I compile it. Any help would be appreciated!
import java.util.Scanner;
class simple calculator { // simple calculator
public static void main(String args[]){
System.out.println("My simple calculator\n");
Scanner bucky= new Scanner(System.in);
double fnum,snum,ans;
System.out.print("Enter the first and second " +
"number : ");
a=bucky.nextFloat(); //assign the numbers
b=bucky.nextDouble(); // to respective variable
System.out.println("What operation u want to " +
"perform");
String operation;
operation=bucky.next();
switch(operation) {
case "+":
ans=a + b;
System.out.print("Sum of the two inputs = ");
System.out.print(ans);
break;
case "-":
ans=a - b;
System.out.print("Subtraction of the two inputs = ");
System.out.print(ans);
break;
case "*":
ans=a * b;
System.out.print("Multiplication of the two inputs = ");
System.out.print(ans);
break;
case "/":
ans=a / b;
System.out.print("Division of the two inputs = ");
System.out.print(ans);
break;
default : System.out.println("Give a proper operation " +
"symbol ");
break; // not required
}
}
}
Two compilation errors:
Your class name has whitespace in it: class simple calculator isn't valid, because "calculator" isn't a recognized token. Try: class SimpleCalculator. Also make it public and change the name of the file to match. (SimpleCalculator.java).
You declare variables a and b but don't give them types. Use float a = ... and double b = .... That one is a float and the other is a double is strange, but pressing on...
Other new-to-java issues to note:
You never close bucky, the scanner. This is a resource leak, and in a bigger application could be a major bug. Add bucky.close() after you read the last line from it, which is after operation = bucky.next()
the name bucky tells me absolutely nothing about what it is or what its use is. Try to use descriptive variable names. (The only main exception being single letter names for loop indices, etc).
fnum and snum are local variables that you declare but never use. Perhaps get rid of them?
Here's your code with edits made:
import java.util.Scanner;
public class SimpleCalculator { // simple calculator
public static void main(String args[]){
System.out.println("My simple calculator\n");
Scanner bucky= new Scanner(System.in);
double ans;
System.out.print("Enter the first and second " +
"number : ");
float a=bucky.nextFloat(); //assign the numbers
double b=bucky.nextDouble(); // to respective variable
System.out.println("What operation u want to " +
"perform");
String operation;
operation=bucky.next();
bucky.close();
switch(operation) {
case "+":
ans=a + b;
System.out.print("Sum of the two inputs = ");
System.out.print(ans);
break;
case "-":
ans=a - b;
System.out.print("Subtraction of the two inputs = ");
System.out.print(ans);
break;
case "*":
ans=a * b;
System.out.print("Multiplication of the two inputs = ");
System.out.print(ans);
break;
case "/":
ans=a / b;
System.out.print("Division of the two inputs = ");
System.out.print(ans);
break;
default : System.out.println("Give a proper operation " +
"symbol ");
break; // not required
}
}
}
I was able to compile it in the terminal with no trouble.
After looking up numerous ways to restart a Java program within itself, a while loop seemed like the easiest option. Here's an example of a basic calculator program I'm trying this with:
import java.util.Scanner;
class a {
public static void main(String args[]){
boolean done = false;
int oper;
Scanner input = new Scanner(System.in);
System.out.println("McMackins Calc v2.0 (Now with fewer crashes!)");
while (!done)
{
System.out.println("What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
oper = input.nextInt();
switch (oper){
case 0:
done = true;
break;
case 1:
add addObject = new add();
addObject.getSum();
break;
case 2:
sub subObject = new sub();
subObject.getDifference();
break;
case 3:
times multObject = new times();
multObject.getProduct();
break;
case 4:
divide divObject = new divide();
divObject.getQuotient();
break;
case 5:
remain remObject = new remain();
remObject.getRemainder();
break;
case 6:
avg avgObject = new avg();
avgObject.getAvg();
break;
case 7:
interest intObject = new interest();
intObject.getInterest();
break;
default:
System.out.println("Invalid entry.");
break;
}
}
input.close();
}
}
However, this seems to throw out a NoSuchElementException at the end of the first time through the loop, and crashes the program. The function of this class is to take the initial input from the user to determine which class to use, which will determine which mathematical operation to perform. Everything works fine without the while (!done) loop.
Example usage:
McMackins Calc v2.0 (Now with fewer crashes!)
What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):
1
How many addends?
1
Enter your numbers now.
1
You have entered 1 addend.
The sum is: 1.0
What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):
Enter a valid integer.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at a.main(a.java:13)
I've also tried just having the other classes refer back to this one, but since main is a static method, I cannot access it the way I intended.
Note that I'm a bit of a beginner at Java, which is why my program is pretty simple, so try to keep it simple if it can be, or post code and then in DETAIL explain what it means so I can not only fix this problem, but future ones as well.
Thank you!
EDIT:
The code is formatted better within my editor. The braces came out in odd positions when I posted it here.
Since apparently a is written correctly, this is my add class. Hopefully this will clear something up.
import java.util.Scanner;
public class add {
public void getSum(){
Scanner input = new Scanner(System.in);
double total, addend;
int entries, count;
total = 0;
count = 0;
System.out.println("How many addends?");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
entries = input.nextInt();
System.out.println("Enter your numbers now.");
while (count < entries){
while (!input.hasNextDouble()){
System.out.println("Enter a valid number.");
input.next();
}
addend = input.nextDouble();
total = total + addend;
count++;
if (count == 1){
System.out.println("You have entered " + count + " addend.");
}else if (count > entries){
System.out.println("You have entered too many addends! Contact program developer.");
}else{
System.out.println("You have entered " + count + " addends.");
}
}
System.out.println("The sum is: " + total);
input.close();
}
}
public static void main(String args[]){
boolean done = false;
int oper;
Scanner input = new Scanner(System.in);
System.out.println("McMackins Calc v2.0 (Now with fewer crashes!)");
while (!done) {
System.out.println("What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
oper = input.nextInt();
switch (oper){
case 0:
done = true;
break;
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
break;
case 3:
System.out.println("3");
break;
case 4:
System.out.println("4");
break;
case 5:
System.out.println("5");
break;
case 6:
System.out.println("6");
break;
case 7:
System.out.println("7");
break;
default:
System.out.println("Invalid entry.");
break;
}
}
input.close();
}
This seemed to work for me so perhaps the error is something to do with your own classes (add, divide) etc.
Also, it's best to keep with convention when creating your own classes by capitalizing the first letter e.g. "add" should be "Add".
You could probably make this a little bit easier to read by building a general "Operations" class which holds an add method, a subtract method etc.
EDIT:
try this for your add method:
public static int add() {
Scanner s = new Scanner(System.in);
int counter = 0;
System.out.println("How many numbers to add?");
int numCount = s.nextInt();
for(int i = 0; i < numCount; i++) {
System.out.println("enter number");
counter += s.nextInt();
}
return counter;
}
Use bufferedreader and inputstream instead of Scanner class. This class creates a lot of bugs and errors, since sometimes it takes more arguments, that you expect it to take.
Also:
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
Your using hasNextInt method wrong, instead of it try to make simple while loop with Boolean and input.next() should be replaced with input.nextLine().
Another thing, you should check,if user typed integer instead of string or something in the while loop and it range. If everything is okay, you should change Boolean value to true and make him go out of the while loop.
For future users who are wondering how to fix this issue, through some reprogramming, I discovered that my problem was closing the input variable BEFORE the end of the loop. By having the program restart indefinitely and only close input when done, this program works fine.
Thanks to Benjamin's response, I am currently in the process of cleaning up and shortening my code by way of for loops.