So, my question is, how do I turn this make my calculator app be able to take input like this, 100 * 2 / 2 + 5 and make it return the sum of it?
or maybe even somehow make it use ( ) brackets..?
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number: ");
String input = scanner.nextLine();
System.out.println("Enter number 2: ");
String input2 = scanner.nextLine();
System.out.println("Enter operator ");
String op = scanner.nextLine();
int intEnter1 = Integer.parseInt(input.toString());
int intEnter2 = Integer.parseInt(input2.toString());
if (op.contains("+")) {
System.out.println(intEnter1 + intEnter2);
}
if (op.contains("-")) {
System.out.println(intEnter1 - intEnter2);
}
if (op.contains("*")) {
System.out.println(intEnter1 * intEnter2);
}
if (op.contains("/")) {
double intEnter1Double = (double) intEnter1;
double intEnter2Double = (double) intEnter2;
System.out.println(intEnter1Double / intEnter2Double);
}
}
}
There is also a very good library for evaluating math expressions called exp4j.
You can do something like this:
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
You have to convert your expression to Reverse Polish notation.
The idea is to transform complex expression to such form that it will be possible to calculate the result using the following algorithm:
expression is parsed from left to right
numbers are pushed to stack
if an operator occured, the correspondent amount of numbers a popped
from stack (1 for unary operator, 2 for binary) and the operation is performed on them
For example, given the input:
5 + ((1 + 2) × 4) − 3
the notation will as following:
5 1 2 + 4 × + 3 −
I found a library that makes that evaluate expressions. You can try this.
http://javaluator.sourceforge.net/en/home/
Double value = new DoubleEvaluator().evaluate(expression);
But this library make all work for you and maybe you want to do by yourself the algorithm no?
Related
Got this code here and I was wondering if it were possible to make the output that comes from either calculation systems be without a decimal/stop the value at the point before the decimal point. Or even convert a double to an int without any errors.
Please ignore the pointless do while loop at the start, I am aware.
Thank You for any help.
class Main{
public static void main(String[] args)
{
calculation(getSystemChoice());
}
public static int getSystemChoice()
{
Scanner input = new Scanner(System.in); //create scanner
int systemChoice;
do{
System.out.println("If you are using the Metric system, please enter a 1.");
System.out.println("If you are using the Imperial system, please enter a 2.");
System.out.println("To quit the program, please enter a 3.");
systemChoice = input.nextInt();
//Switch start
switch(systemChoice){
case 1:
systemChoice=1;
return systemChoice;
case 2:
systemChoice=2;
return systemChoice;
default: //Currently no working input correction system, likely due to no case for 3. !!!!
System.exit(0);
}
//Switch End
}
while(systemChoice != 1 || systemChoice != 2 || systemChoice != 3);
return systemChoice;
}
//This method takes an int as a parameter(1 or 2) and runs if statements based on the metric or imperial systems.
public static void calculation(int systemChoice)
{
double inches, centimeters, meters, feet;
Scanner input = new Scanner(System.in); //create scanner
//if the user entered one, the result will be in meters and centimeters
if(systemChoice == 1){
System.out.print("Enter amount of meters: ");
meters = input.nextDouble();
System.out.print("Enter amount of centimeters: ");
centimeters = input.nextDouble();
feet = meters * 3.28084;
inches = centimeters / 2.54;
System.out.printf("Feet: %.2f\t " , feet);
System.out.printf("Inches: %.2f\t " , inches);
rerun(systemChoice);
}
// if the user entered 2 then the result will be in feet and inches
else if(systemChoice == 2){
System.out.print("Enter amount of feet: ");
feet = input.nextDouble();
System.out.print("Enter amount of inches: ");
inches = input.nextDouble();
meters = feet / 3.28084;
centimeters = inches * 2.54;
System.out.printf("Meters: %.2f\t " , meters);
System.out.printf("Centimeters: %.2f\t\n " , centimeters);
rerun(systemChoice);
}
}
public static void rerun(int systemChoice)
{
Scanner in = new Scanner(System.in);
System.out.println("\nIf you would like to make another measurement, enter 4.");
System.out.println("Otherwise, you may quit by entering any other number.");
systemChoice = in.nextInt();
if(systemChoice == 4)
{
getSystemChoice();
calculation(systemChoice);
}
else
{
System.exit(0);
}
}
}
You can use casting just before you print it and print it as an integer.
System.out.printf("Inches: %d " , (int)inches)
I do not recommend simply casting to int. Here is an example:
double myValue = 8.65;
System.out.println((int) myValue); // will output 8 as java will always round to the next lower integer
System.out.println(Math.round(myValue)); // will output 9 which obviously is correct (mathematically speaking)
There are a number of potential solutions depending on your exact requirements. Other posters have already mentioned a couple. It's worth bearing in mind the pros and cons of each:
Simply casting to an int or long is the simplest method, but will always round down. It's probably fine for your training example. But in real-world applications, this can cause subtle bugs with values that a double can represent but an int or long can't (e.g. a double can represent the result of 1.0/0 as "infinity", but casting to an int or long will turn this into a large positive integer value-- that can lead to subtle bugs in real-world applications);
You can use Math.round() to use the convention of rounding to up or down to the 'nearest' integer; but this doesn't solve the issue of values that can't be represented;
For other rounding modes, you can use the BigDecimal class: see the BigDecimal.round() method-- many applications won't require this, but some specialist cases might;
To truncate to zero decimal places for output while also dealing with 'special' values, you can use String.format() and specify zero decimal places.
The code for the latter option would look as follows:
double val = ...
System.out.printf("Truncated value is: %.0f", val);
You've probably already seen the 'simple casting' option, but it would look like this:
double val = ...
long truncatedVal = (long) val;
System.out.println("Truncated value = " + truncatedVal);
I want to make an application that takes a sequence of 3 numbers per line to produce and stops when it reaches a sequence of zeros and then prints if it's an arithmetic progression or geometric progression and the next number in the series.
Example input:
4 7 10
2 6 18
0 0 0
should output
AP 13
GP 54
here is my code I wanna know what's wrong with it and what are the possibilities that won't work with my code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main
{
static String s="";
public static void main (String[] args) throws IOException
{
String c;
String a[];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
c= br.readLine();
a = c.split(" ");
if(c.charAt(0)!='0'){
calc(a[1], a[2]);
}
}while((c.charAt(0))!='0');
printer(s);
}
public static void calc(String a, String b){
int x = Integer.parseInt(a);
int y = Integer.parseInt(b);
if(y%x==0){
s += "GP" +" " + (y*(y/x)) + "z";
return;
}else{
s += "AP" + " " + (y + (y-x)) + "z";
return;
}
}
public static void printer(String s){
String p= "";
for(int i =0;i<=s.length()-1;i++){
if(s.charAt(i)!='z'){
p+= s.charAt(i);
}else{
System.out.println(p);
p= "";
}
}
}
}
Your problem it that you discover progression type incorrectly. For example, 0 4 8 is obviously AP, but your algorithm will say it is GP. Another example: 8 4 2 is GP, but 2%4 will return false, saying it is AP. Also, you don't proceed cases when offered sequence is not progression at all.
It is absolutely clear that all 3 numbers should be involved. Suppose that integer numbers a, b, c form AP or GP, and you need to discover which progression it is. Simple math can be used:
If they form AP, then a + c = b + b. Next element is c + c - b
If they form GP, then a * c = b * b. Next element is c * c / b
(Please notice how + is changed to *, and - to /, when you switch from AP to GP).
Your code works on the assumption that if two consecutive numbers of a 3 number series is divisible, the series is a GP and that if it's not, it has to be an AP. This assumption is wrong. There are many cases in which it will not be true, such as a series 0,3,6. It is an AP, not a GP. So instead of sending 2 parameters to the function calc(), you should send all three numbers as parameters, and check as follows:
if((a+c)==(2*b))
{//AP
}
else if((a*c)==(b*b))
{//GP
}
These above are the proper check for Arithmetic and Geometric progressions. Also while checking if the inputs are all 0, you are only checking for the first element. Instead you have to see if all three of the elements are 0. Your code might not work in the case of 0,3,6 or 0,2,4 or 0,1,2. So instead you have to check like this:
int flag=0;
for(int i=0;i<3;i++)
if(Integer.parseInt(a[i]))
flag=1;
if(flag==1)
{//continue prog
}
else
{//Terminate prog as input is 0,0,0
}
The goal is to create a program that takes a quadratic equation in quadratic form and solve it. Is there a different way to go about doing so other than StringTokenizer? Or is it possible to isolate just ^2 in StringTokenizer rather than ^ and 2 like it is doing now? I realized that using the way I wrote it, it will not allow equations to use 2 at all.
This question requires me to not take individual coefficients, but rather the entire equation itself.
Sample run: ”java SolveEquation2 1.5625x∧2+2.5x+1=0”. For this input the output should be: ”x=-0.8”
import java.util.Scanner;
import java.util.StringTokenizer;
class SolveEquation2 {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.print("Input a quadratic");
String equation = scan.nextLine();
StringTokenizer st = new StringTokenizer(equation, "x^2+-");
String a,b,c;
a = st.nextToken();
b = st.nextToken();
c = st.nextToken();
double a1 = Double.parseDouble(a);
double b1 = Double.parseDouble(b);
double c1 = Double.parseDouble(c);
double x = (b1 * b1) - (4 * a1 * c1);
double var1 = (-b1 + Math.sqrt(x)) / (2*a1);
double var2 = (-b1 - Math.sqrt(x)) / (2*a1);
if (x == 0){
System.out.println("x = " + var1);
}
if (x > 0){
System.out.println("x1 = " + var1);
System.out.println("x2 = " + var2);
}
if (x < 0){
System.out.println("No Solution");
}
}
}
You want to use regular expressions to parse the command line input.
It seems that what you're trying to do has been done many times before.
See here
Ok, I'm a beginner in java, learning on my own through websites and books. I tried a simple square root calculator with a for loop and a while loop (I've included what I tried below). Sadly, all my code does when I enter a number is terminate. Any help would be appreciated!
import java.util.Scanner;
public class The2RootProdject {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double rootIt = input.nextDouble();
double dummy = 0.0000000;
while (dummy != dummy * dummy) {
dummy += 0.0000001;
if (rootIt == dummy * dummy) {
System.out.println("the squar root of " + rootIt + " is "
+ (dummy * dummy));
}
}
}
}
You have a couple of problems here:
1) Logical bug: 0 == 0 * 0
<= This means while (dummy != dummy * dummy) {..} will never be untrue, and you'll never even enter the loop
2) Floating point numbers are inexact, so your algorithm (which relies on "==") might not work anyway
Look here for more details on floating point imprecision:
http://www.lahey.com/float.htm
This is true for ANY language - your algorithm for square root must take this into account.
Try to use this algorithm which use Newton's iteration:
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
double number, t, squareRoot;
Scanner input = new Scanner(System.in);
number = input.nextDouble();
squareRoot = number / 2;
do
{
t = squareRoot;
squareRoot = (t + (number / t)) / 2;
}
while ((t - squareRoot) != 0);
System.out.println(squareRoot);
}
}
Newton's iteration is an algorithm for computing the square root of a number via the recurrence equation:
X(n+1) = (X(n) + number/X(n))/2
I think the while condition is supposed to be =
while(rootIt != dummy * dummy) {}
Your current condition will only ever be true if you initialized dummy as 1; but I don't that would be what you want anyways.
//In the following lines of code the user is asked to enter a length to determine the volume of a regular icosahedron, however, when entered the programm always outputs 0.0 as the answer for the volume???
import java.io.*; //allows I/o statements
class VolumeIcosahedron //creating the 'volumeIcosahedron' class
{
//allows strings with exceptions to IO = input/output
public static void main (String[] args) throws IOException
{
BufferedReader myInput = new BufferedReader(
new InputStreamReader (System.in)); //system input/ output
String stringNum; // the number string
double V; // integer with decimals volume
int L; // integer required length
//System output
System.out.println("Hello, what is the required length");
stringNum = myInput.readLine();
L = Integer.parseInt(stringNum);
V = 5/12 *(3 + Math.sqrt(5))*(L*L*L);
System.out.println("The volume of the regular Icosahedron is " + V);
}
}
Because 5/12 in integer equals 0 so it always results in 0.
Try with 5.0 to force the division without involving integer division.
V = 5.0/12 *(3.0 + Math.sqrt(5))*(L*L*L);
I think this is the offending line:
V = 5/12 *(3 + Math.sqrt(5))*(L*L*L);
5/12 returns an int (whole number), which is always truncated down to 0, hence 0 * anything will return 0.
Change it to this, using the letter d to signify that these numbers are of type double:
V = 5d/12d *(3 + Math.sqrt(5))*(L*L*L);
The reason is that you are using integer inside the calculation.
With integer, you should see the division as an euclidean operation, ie a = bq + r.
So in your program, 5/12 will always return 0 (5 = 0 * 12 + 5).
If you change the line to be like this (replacing every integer by double):
V = 5.D/12.D *(3.D + Math.sqrt(5.D))*(L*L*L);
Then the result will be different.