I made simple calculator for android for sake of learning but its buggy. All number keys just append respective number to TextView. Equals button does the job of adding/subtracting/divide/multiply. But the problem is, it can do only one at a time, if I mix plus operation with minus, it will crash. Here is code of equals button performing addition:
equals = (Button) findViewById(R.id.equals);
equals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.getText();
String expression = (result.getText()).toString();
if(expression.contains("+")){
String[] numbers = expression.split("\\+");
String no1 = numbers[0];
String no2 = numbers[1];
Double numb1 = Double.valueOf(no1);
Double numb2 = Double.valueOf(no2);
Double added = numb1+numb2;
theresult = String.valueOf(added);
result.setText(theresult);
}
}
});
as you can see above, another problem arises. It cant handle more than one + sign, how can I make it work to add x amount of numbers? Sorry I am new to programming, instead of just making it work, I want to learn how it will work so please explain too if possible. Thanks.
This is best suited as a comment, I decided to put it as an answer just to not get it lost since there are already some answers.
Have a look at this question; the accepted answer might not be what you want because you want to learn, but there is an answer by boan that is possibly what you are looking for. I am not copying it here because it is already on S.O.
If its crashes then best idea is to post logcat error too.
Now the problem; you are separating the expression based on + only. so If you add - then the second part of the array would contain - also which can't be converted into double. Here you are getting the error.
So best idea is to separate the digit only part based on all the expressions such as +, -, * and /. Once all the expression has been separated then only you can convert the remaining values to string and perform the action based on respective expression.
You will have to write some code for all this.
Now resources that could help you. (Second is shorter approach)
Evaluating a math expression given in string form
How to parse a mathematical expression given as a string and return a number?
Related
I am trying to write a piece of code to simulate text messaging on an old keypad. 2 = a,b,c 3 = def etc.
I can read the string and pull out the character but I am trying to develop an elegant way in Java of mapping the character to the number.
I could use the Character.compare. But I am going to have to compare my character with the full alphabet.
compareOneTwo = Character.compare(ch[r], 'a'); etc
I would rather use a Boolean function that compares three characters at once using an "or"
if(ch[r] = 'a'||'b'||'c') {
But I am struggling - with getting this to work.
I appreciate that this is basic and probably a silly mistake but we all have to start somewhere...
Any help will be appreciated.
You said it yourself, you are trying to find a way to map the characters to the numbers, so use a map!
Map<Character, Integer> characters = new HashMap<>();
characters.put('a', 2);
characters.put('b', 2);
characters.put('c', 2);
characters.put('d', 3);
...
characters.put('z', 0);
Integer number = characters.get('a');
System.out.println(number); // Will print '2'
The initial setup is a bit more code since you have to specify the whole alphabet, but store it in a static variable and it'll be done once for your whole application.
This will definitely yield the best performances in terms of speed, and regarding memory usage, it's only 26 characters and as many integers, so negligible :)
Another advantage is that it is easy to update, if you need to handle a new character like *, just add one row to the map and it's done!
You can't use the OR operator as you wish.
You do have other alternatives if you don't want to have many conditions connected by OR (||) operators.
You can create a Set and use contains:
if (Set.of('a','b','c').contains(ch[r])) {}
Or you can use a range of characters if you need to check for a consecutive range:
if (ch[r] >= 'a' && ch[r] <= 'c') {}
Currently trying to do a reverse polish calculator for one of my Uni homework tasks.
I have the program working fine when using a bunch of if/else statements to work out which operator was typed in and do the mathematical operation normally like num1+num2.
This is beyond the homework task we were set but what I'm trying to do now is replace the operator with a variable for example: "num1 + num2" would become "num1 variable num2" where variable equals "+" etc.
Is there a way to do this in Java?
Thanks in advance
Since you are interested in going beyond the scope of the training material, and assuming you've learned about interfaces already, I believe what you are looking for is a binary expression tree (that wikipedia article actually explains it good).
Basically, you create an interface Expression with a double compute() method. There will be two types of implementing classes:
Operand: Constant and Variable.
Operator: Plus, Minus, Multiply, Divide. Each will have two Expression fields: left and right.
Your text expression is then parsed into the expression tree:
// input: "num1 + num2 * 3"
// result expression tree will be built by parser using:
Expression a = new Variable("num1");
Expression b = new Variable("num2");
Expression c = new Constant(3);
Expression d = new Multiply(b, c);
Expression e = new Plus(a, d);
Map<String, Double> variables = /*defined elsewhere*/;
double result = e.compute(variables);
Your new assignment, should you choose to accept it, will be to write the expression classes and a parser to build the expression tree from a text expression.
Hope this will encourage you to go way beyond the training material, having some fun while playing.
First you can use a switch on String rather than if-then-else chain. Another way is to build a static final Map (E.g. HashMap) from String to Function. The strings are the operators. The Functions do the operation. In Java 8 you can give the functions as lambdas. I only have access through a phone right now so can't show code. Your question will be much better received if you add code showing what you mean.
I'm learning Java, and I'm completing some problems tasked to me.
I've come across a specific problem and I feel like the answer is so simple, but I just can't find it.
I need to check if given string ends with the first two characters it begins with. For example, "edited" (begins and ends with "ed")
I've tried using the java endsWith and startsWith, but I keep getting an error
start = text.startsWith(text.substring(0,2));
Yeilds
Error: incompatible types
required: java.lang.String
found: boolean
Any help would be appreciated.
Thankyou.
You're calling startsWith when you don't need to - you know it starts with the first two characters, by definition :)
You could have:
String start = text.substring(0, 2);
boolean valid = text.endsWith(start);
Or just collapse the two:
boolean valid = text.endsWith(text.substring(0, 2));
I'm assuming you already know the string is of length 2 or more... if not, you should check that first. (And change the variable valid to whatever makes sense in your context.)
This is a dynamic code for what you need to do
let's say we have
String testak = "tesHJKLtes"
//index you need to check here 2
int ind = 2;
ind is the index you need to check
if ( testak.substring(0,ind).equals(testak.substring(testak.length()
-ind-1,testak.length()-1))){
System.out.println("yeeaaahhh");
}
and consider that this you are not limited to 2 anymore you can give ind any number you like
and it will work
For a programming project in Calculus we were instructed to code a program that models the Simpson's 1/3 and 3/8 rule.
We are supposed to take in a polynomial(i.e. 5x^2+7x+10) but I am struggling conceptualizing this. I have began by using scanner but is there a better way to correctly read the polynomial?
Any examples or reference materials will be greatly appreciated.
I'd suggest that you start with a Function interface that takes in a number of input values and returns an output value:
public interface Function {
double evaluate(double x);
}
Write a polynomial implementation:
public class Poly {
public static double evaluate(double x, double [] coeffs) {
double value = 0.0;
if (coeffs != null) {
// Use Horner's method to evaluate.
for (int i = coeffs.length-1; i >= 0; --i) {
value = coeffs[i] + (x*value);
}
}
return value;
}
}
Pass that to your integrator and let it do its thing.
A simple way (to get you started) is to use an array.
In your example: 5x^2 + 7x + 10 would be:
{10,7,5}
I.e. at index 0 is the factor 10 for x^0 at index 1 is 7 for x^1 at index 2 is 10 for x^2.
Of course this not the best approach. To figure out way figure out how you would represent x^20
In java it would be easiest to pre-format your input and just ask for constants--as in, "Please enter the X^2 term" (and then the X term, and then the constant).
If that's not acceptable, you are going to be quite vulnerable to input style differences. You can separate the terms by String.split[ting] on + and -, that will leave you something like:
[5x^2], [7x], [10]
You could then search for strings containing "x^2" and "x" to differentiate your terms
Remove spaces and .toLowerCase() first to counter user variances, of course.
When you split your string you will need to identify the - cases so you can negate those constants.
You could do two splits, one on + the other on -. You could also use StringTokenizer with the option to keep the "Tokens" which might be more straight-forward but StringTokenizer makes some people a little uncomfortable, so go with whatever works for you.
Note that this will succeed even if the user types "5x^2 + 10 + 7 x", which can be handy.
I believe parsing is my problem. I am somewhat new to java so this is troubling me.
You should use a parser generator.
A parser generator is a tool that reads a grammar specification and converts it to a Java program that can recognize matches to the grammar. In addition to the parser generator itself, JavaCC provides other standard capabilities related to parser generation such as tree building (via a tool called JJTree included with JavaCC), actions, debugging, etc.
JavaCC's FAQ answers How do I parse arithmetic expressions?
See the examples that come with JavaCC.
See any text on compiling.
See Parsing Epressions by Recursive Descent and a tutorial by Theodore Norvell.
Also, see JavaCC - Parse math expressions into a class structure
I am working on a project that requires some simple math to be performed on currency, however it arrives in the form of a String. I am new to Java/Android so I am looking for help in converting from a String to a data type appropriate to this operation. At first I thought Float was right but after reading elsewhere and introducing myself to the numbers class, it appears BigDecimal is correct. Am I on the right track? At this point I simply want to subtract the sum of payments from an initial invoice amount. I get the feeling this code is simple but clumsy and I suspect I am missing a great deal about the nuances of working with currency. How would you do it? All advice warmly appreciated!
// capture variables from sending activity
String invoiceAmt = getIntent().getStringExtra("invoiceAmt");
String paymentsSum = getIntent().getStringExtra("paymentsSum");
// convert strings to BigD's
BigDecimal amt = new BigDecimal(invoiceAmt);
BigDecimal sum = new BigDecimal(paymentsSum);
// Do the math
BigDecimal invDue = amt.subtract(sum);
// insert the value (back to string) into textView
TextView tvInvoiceDue = (TextView)findViewById(R.id.InvoiceDue);
tvInvoiceDue.setText(invDue.toString());
BigDecimal is a fine approach. So is using an int or a long to store cents. I've heard some people like Joda-Money but I've never used it myself.
See this question.
In the code you posted, make sure the Strings you are receiving don't have currency symbols in them.