I am having trouble casting from a string to a char then to a double. I'm trying to calculate a simple expression 1+2 but when I pop it from a stack its 50.0 and 49.0 respectively. Then adds to 99.0. My code is below.
The expression is '1+2'
public static double calculate (String expression){
Stack<Character> calc = new Stack();
expression.replaceAll("\\s+","") ;
double result = 0;
for(int i = 0; i < expression.length(); i++){
calc.push((char) expression.charAt(i));
}
double one = (double) calc.pop();
char expr = calc.pop();
double two = (double) calc.pop();
if(expr == '-'){
result = one - (1*two);
} else if (expr == '+'){
result = one + (1*two);
}
System.out.println(result);
return result;
}
The problem is that when you do a direct cast to a number like this
(double) calc.pop();
...you are actually getting the ascii values of the characters '1' (ascii 49) and '2' (ascii 50).
You need to parse the character. Something like this will work:
Double.parseDouble(calc.pop().toString());
Related
I have to make this subroutine able to work with doubles, not just ints. I'm new to coding and really dont get this.
Here is the subroutine:
public static int readNumber() throws Exception
{
int number = 0;
char characterAsciiCode = '0';
int numberValue = 0;
characterAsciiCode = (char)System.in.read();
while ( characterAsciiCode != '\n')
{
//convert the character code to an actual numeric value
numberValue = characterAsciiCode - '0';
//integrate the numeric digit into the total number
number = number * 10 + numberValue;
//get the next character from the keyboard buffer
characterAsciiCode = (char)System.in.read();
}
return number;
}
Your help would be greatly appreciated.
So assuming the idea was that you were supposed to be constructing the number yourself without nextInt() or nextDouble(), you could extend the logic you already have as follows:
1) if you encounter the new line before a ., just return the double of the number you found so far.
2) if you encounter the . (I am being Americentric here, if where yuou live the comma is used, adapt accordingly) first, save the number, accumulate the decimal part as an integer using the same routine as before (terminated by new line), but track the length of the decimal part.
3) return the number part plus the decimal part divided by 10^decimalLength.
Here's the code. It may have an unnecessary cast or two. I was being cautious.
public static double readNumber() throws Exception {
int number = 0;
char characterAsciiCode = '0';
int numberValue = 0;
characterAsciiCode = (char) System.in.read();
while ((characterAsciiCode != '\n') && (characterAsciiCode != '.')) {
//convert the character code to an actual numeric value
numberValue = characterAsciiCode - '0';
//integrate the numeric digit into the total number
number = number * 10 + numberValue;
//get the next character from the keyboard buffer
characterAsciiCode = (char) System.in.read();
}
if (characterAsciiCode == '\n') {
return (double) number;
}
int decimal = 0;
int decimalLen = 0;
characterAsciiCode = (char) System.in.read();
while (characterAsciiCode != '\n') {
//convert the character code to an actual numeric value
numberValue = characterAsciiCode - '0';
//integrate the numeric digit into the total number
decimal = decimal * 10 + numberValue;
decimalLen++;
//get the next character from the keyboard buffer
characterAsciiCode = (char) System.in.read();
}
return (double) number + (double) decimal / Math.pow(10, decimalLen);
}
I need to convert a float to an int, as if the comma was removed.
Example:
23.2343f -> 232343
private static int removeComma(float value)
{
for (int i = 0; ; i++) {
if((value * (float)Math.pow(10, i)) % 1.0f == 0.0f)
return (int)(value * Math.pow(10, i));
}
}
The problem is with rounding up of the number. For example if I pass 23000.2359f it becomes 23000236, because it rounded up the input to 23000.236.
Java float doesn't have that much precision, which you can see with
float f = 23000.2359f;
System.out.println(f);
which outputs
23000.236
To get the output you want, you could use a double like
double d = 23000.2359;
String v = String.valueOf(d).replace(".", "");
int val = Integer.parseInt(v);
System.out.println(val);
Output is (the requested)
230002359
you must find a way to get the number of digit after decimal place 1st. Suppose it is n. then multiply the number with 10 times n
double d= 234.12413;
String text = Double.toString(Math.abs(d));
int integerPlaces = text.indexOf('.');
int decimalPlaces = text.length() - integerPlaces - 1;
How to get the value which is after the point.
Example:
If 5.4 is the value and I want to get the value 4 not 0.4, how can I do this?
You can use String functions for that :
public static void main(String args[]){
Double d = 5.14;
String afterD = String.valueOf(d);
afterD =afterD.substring(afterD.indexOf(".") + 1);
System.out.println(afterD);
}
first of all convert number to String,
Then using Substring get indexof(".") + 1 then print it.
& see it ll work.
OR You can try :
double d = 4.24;
BigDecimal bd = new BigDecimal(( d - Math.floor( d )) * 100 );
bd = bd.setScale(4,RoundingMode.HALF_DOWN);
System.out.println( bd.intValue() );
will print : 24
suppose your input is 4.241 then you have to add 1 extra 0 in BigDecimal bd formula i.e. instead of 100 it ll be 1000.
Code:
double i = 5.4;
String[] s = Double.toString(i).split("\\.");
System.out.println(s[1]);
output:
4
Explantion:
you can convert the double to String type and after that use split function which split the converted double to String in two pieces because of using \\. delimiter. At the end, type out the second portion that you want.
you can try this
code:
double i = 4.4;
String s = Double.toString(i);
boolean seenFloatingPoint = false;
for (int j = 0; j < s.length(); j++) {
if(s.charAt(j)== '.' && !seenFloatingPoint){
seenFloatingPoint = true;
} else if (seenFloatingPoint)
System.out.print(s.charAt(j));
}
System.out.println("");
output:
4
the one line answer is
int floatingpoint(float floating){
return Integer.valueOf((Float.toString(floating).split(".")[1]));
}
which will do as follows:
convert the number e.g 56.45 to string
then split the string in string array where [0]="56" and [1]="45"
then it will convert the the second string into integer.
Thanks.
Try this way
Double d = 5.14;
String afterD = String.valueOf(d);
String fractionPart = afterD.split("\\.")[1];
Try this way
double d = 5.24;
int i = Integer.parseInt(Double.toString(d).split("\\.")[1]);
int i=(int)yourvalue;
float/double afterDecimal= yourvalue - i;
int finalValue = afterDecimal * precision;//define precision as power of 10
EX. yourvalue = 2.345;
int i=(int)yourvalue;//i=2
float/double afterDecimal= yourvalue - i;//afterDecimal=0.345
int finalValue = afterDecimal * precision;
//finalValue=0.345*10 or
//finalValue=0.345*100 or
// finalValue=0.345*1000
...
System.out.println((int)(5.4%((int)5.4)*10));
Basically 5.4 mod 5 gets you .4 * 10 gets you 4.
CS Student here. I want to be able to take a string such as '2+2*3/2-2' and evaluate it (= 3). But I'm not sure how to structure the code to follow the proper order of operations. Here's code for multiplication and division:
int r = 1;
int n = 0;
char op = '*';
for (int i = 0; i < E.length(); i++)
if (E.charAt(i)=='*'||E.charAt(i)=='/')
{
if (op == '*')
r *= n;
else
r /= n;
n = 0;
op = E.charAt(i);
}
else
n = n*10 + (E.charAt(i)-'0');
if (op == '*')
r *= n;
else
r /= n;
return r;
Thanks for reading!
Use a binary tree where each node is an arithmetic operator and the leaves are the values.
This is exactly what the Interpreter pattern is meant to do. Your mathematical operations are basically a grammar - all you need to do is represent that grammar. Use the Interpreter pattern to parse your mathematical statement, and then use what it spits out to perform the necessary operations.
Use Reverse Polish Notation to represent your formula in a "computation friendly" form.
You can read about RPN here: http://en.wikipedia.org/wiki/Reverse_Polish_notation
RPN version of your 2+2*3/2-2 would be 2 2 3 * 2 / 2 - +
Then the algorithm is like that:
Assume each sign from RPN version is an element from the array of symbols.
You take element from the array and if this is a number put it on a stack if this is an operator take two elements from the stack and perform operation. The result should land on the stack again. Repeat until you reach the last element of the array. At the end there will be only one element on your stack which is your answer.
Let's visualize:
iteration# symbol stack content
1# 2 -> 2
2# 2 -> 2,2
3# 3 -> 3,2,2
4# * -> 6,2
5# 2 -> 2,6,2
6# / -> 3,2
7# 2 -> 2,3,2
8# - -> 1,2
9# + -> 3
You need to parse the expression. A simple recursive descent parser can do that:
double expression(const char **p) {
double rv = term(p);
while (**p) {
if (**p = '+') {
++*p;
rv += term(p)
} else if (**p = '-') {
++*p;
rv -= term(p);
} else
break; }
return rv; }
double term(const char **p) {
double rv = factor(p);
while (**p) {
if (**p = '*') {
++*p;
rv *= factor(p)
} else if (**p = '/') {
++*p;
rv /= factor(p);
} else
break; }
return rv; }
double factor(const char **p) {
return strtod(p, (char **)&p);
}
Of course, the above won't deal with spaces in the strings, or parenthesis, or other things you might care about, but they can be added relatively easily.
I need to create a program that converts a string to double.
public class Convert{
public static void main(String args[]){
String num="124023211.123";
int d=0,g=0,c=0,fnl=0,h=0,v=0;
double fnl2=0;
int exp=(num.indexOf(".")-1);
while(num.charAt(d)!='.'){
g=num.charAt(d)-48;
int k = 1;
for(int f=0;f<exp;f++){
k=(k*10);
}
fnl+=(k*g);
d++;
exp--;
}
num=(num.substring(d+1) );
//System.out.println(fnl);
//System.out.println(num);
while(h!=num.length()){
v=num.charAt(h)-48;
double j=1;
int exp1=num.length();
for(int f1=0;f1<exp1;f1++){
j*=.10;
}
fnl2+=(h*j);
j++;
h++;
}
System.out.println(fnl2);
}
}
The first while loop converts the int part of the string and it works right. But the second while loop should result to the decimal portion of the string. I am having a hard time because double results to huge decimal numbers and it ruins the conversion, and also the second while loop prints the wrong answer.
int exp1=num.length();
This line is part of your problem. Your loop will always loops num.length() times, but num isn't changing in length (so always 3, in your case). This is causing all three numbers to be treated as thousandths.
Also, remember that decimal values can't be represented exactly in the IEEE-754 format. By doing all these multiplications and additions, you're introducing error into your result. Double.Parse is going to give you the best approximation possible for your number.
You can do the following
String s="124023211.123";
int i;
double result = 0.0f, result2 = 0.0f;
for (i = 0; i < s.length(); i++)
if (s.charAt(i) == '.')
break;
else
result = result * 10 + (s.charAt(i) - '0');
for (i = s.length()-1 ; i>=0 ; i--)
if (s.charAt(i) == '.')
break;
else
result2 = result2 / 10 + (s.charAt(i) - '0');
if (i>=0)
result += result2/10;
Tested for: 11, 3.0, 6.00000, 0005.000, .12, and 124023211.123
Of course, you will not get always the exact value, because sometimes it will be written as an expression as double, like the number you provided. And there are some numbers that have no representation in the binary system.
Try this one it is working fine tested for valid data
public class Sample1 {
public static void main(String args[]){
String num="122312312.2331231";
String s1 = num.substring(0,num.indexOf("."));
String s2 = num.substring(num.indexOf(".") + 1,num.length());
System.out.println(s1);
System.out.println(s2);
double n1 = 0;
double n2 = 0;
for(int i=0;i<s1.length();i++){
double d = s1.charAt(i) - '0';
n1 = n1*10;
n1 += d;
}
System.out.println(n1);
for(int i=0;i<s2.length();i++){
double d = s2.charAt(i) - '0';
//n2 = n2/;
n2 += d/number(i+1);
}
System.out.println(n1+n2);
}
public static long number(int n2){
long d = 10l;
if(n2>1)
d = 10 * number(n2-1);
return d;
}
}
Gautam Sonar