Showing posts with label operators. Show all posts
Showing posts with label operators. Show all posts

Tuesday, November 12, 2013

DozCalc: A More Polished Android Application in Java

Since my post on my first Android app, I've done a lot. I went on from that first app to learn how to access a lot more of the device, deal with a wider range of circumstances, and generally get to know Android and the tools for developing for it better.

Specifically, I have posted an app for Android called DozCalc.

DozCalc is a dozenal (base 12) calculator. It doesn't convert back and forth between dozenal and decimal, so be warned. Just like your normal four function calculator that works in base 10 and nothing else, DozCalc works in base 12 and nothing else.

Java

The "programming", like development in many modern GUI environments, was less about the functional code (in this case in Java) and more about the user interface. While Android allows for UI programming in Java, it's typically simpler to implement it in XML. And this is what I did.

The only problem I had was dealing with loss of precision in some calculations. At first, I was going to be very clever and write a proper function using numerical analysis to get the value right to some specified number of fractional digits (note: it's not proper to call them 'decimal digits' when you're working strictly in base 12). However, it was simpler and easier to just add a small value to certain calculations (division, for example) to make all the fractional values come out correct. Far simpler to program, just as effective for this use, and every bit as accurate as the average four function calculator.

Sometimes programming is less about the language, or the algorithm, than about just getting a solution that's accurate enough for the need, then moving forward.

Thanks to object-oriented design, I was able to re-use the code from DozCalc in another graphical calculator. Unfortunately, I got bogged down in the graphical design, so the steampunk styled version of DozCalc (named Mr Wells' Calculator) has yet to be released, and may not be depending on how my schedule of current projects goes.
StumbleUpon

Wednesday, June 27, 2012

Java's Assignment Operators

An assignment operator is a way of putting a new value into a variable.

I covered these briefly in Doing Math in Java, Part 1. Now I'll go into a bit more detail.

The Simple Assignment Operator

The simple assignment operator is =.

It places the value from the expression on its right side into the variable on its left.
This is covered in detail in Left Becomes Right.

Also see the Java Language Specification: The Simple Assignment Operator.

The Compound Assignment Operators

The compound assignment operators are:
+=, "plus-equals",
-=, "minus-equals",
*=, "times-equals" or "star-equals",
/=, "divided by-equals" or "slash-equals",
%=, "remainder-equals" or "percent-equals",
&=, "and-equals",
|=, "or-equals",
^=, "exor-equals" or "caret-equals",
>>=, "signed-shift-right-equals",
<<=, "shift-left-equals",
>>>=, "unsigned-shift-right-equals".

Commonality
Each of these operators has a variable to assign a value to before it, and an expression that results in a value after it:
variable operator expression

The expression has to result in a value that is compatible with variable's type.

Java will calculate the value of expression,

perform the calculation variable optype expression, where optype is the assignment operator without the equals sign.

Then it will place the result of that calculation into variable.

+=, "Plus-Equals"
Plus-equals adds the value after += to the original value of the variable, then puts the result into the variable.

-=, "Minus-Equals"
This subtracts the value after the operator from the original value in the variable, then stores the result in the variable.

*=, "Times-Equals"
Multiply the variable by the value on the right of the operator, put the result in variable.

/=, "Divided by-Equals"
Same as the above, but for division.

%=, "Remainder-Equals"
This finds the remainder of the variable's initial value divided by the value after the operator. That remainder is then put into the variable.

See Java's Modulo Operator--Wrapping Around for more information on how the remainder (or modulo) operator % works.

&=, "And-Equals"
And-equals does a bit-wise AND of the value after the assignment operator with the original value of the variable, then puts the results in the variable.

|=, "Or-Equals"
Or-equals does a bit-wise OR of the variable and the value after the operator. The result is placed in the variable.

^=, "Exor-Equals"
Exor-equals is short of Exclusive-Or Equals (and it is often written xor-equals). It does a bitwise exclusive-or of the variable and the value after the assignment operator, then puts the result into the variable.

>>=, "Signed-Shift-Right-Equals"
This does a signed right shift of the variable a number of times equal to the expression after the assignment operator. The result is placed in variable.

<<=, "Shift-Left-Equals"
This does the same thing as signed-shift-right-equals, except it does a signed left shift (each bit in the variable gets moved to the left expression times.

>>>=, "Unsigned-Shift-Right-Equals"
This one moves all the bits, unlike the signed shifts which leave the sign bit (highest order bit) alone.

Not Quite the Whole Story
That covers how these operators behave with numerical and other simple values. These operators have other behaviors when used with Strings, Arrays, and other complex value types. That goes beyond the scope of this article, however, more on that can be found at the links given under "Additional Information".

Additional Information
See the Java Language Specification: Compound Assignment Operators, Multiplicative Operators, Additive Operators, Bit-wise and Logical Operators.

StumbleUpon

Friday, June 24, 2011

Java Variable Value Assignment: Left Equals Right, Left Becomes Right

One of those things that vexes beginning programmers is assigning values to a variable in Java. Part of what makes it so vexing is that the problem is practically invisible to an experienced programmer. Another part of it is that we use the equals sign (=) to do the assignment.

Take a look at these statements:

int i = 1;
j=7;
7+count=c;
b+14=a+9;

The first two are fine (assuming that 7 is a valid value for whatever type of variable j is), but the last two are wrong.

Remember All That Algebra We Taught You? Well, We Broke It.

After you've gone to all the trouble to learn how to deal with things like 7+count=c and b+14=a+9 in algebra class, now we take what you know and turn it on its ear in programming class. Sweet, eh?

The problem is that the = we use in programming has pretty much nothing to do with the = that you use in math. It's just close enough to be confusing. In Java, the equals sign is an assignment operator, not an indicator of equality between values as it is in math. There is a comparison operator for equality in Java, it's ==, and we'll talk about it shortly. First, let's talk assignment.

Assignment

In computers, we use the term assignment to describe sticking a value into the computer's memory so that we can get it back later. It's like using the memory in a programmable calculator. We put some number into our calculator's memory so that we can get it back later for another part of our calculation. It's pretty much the same thing with computers.

With Java, we can store all kinds of values, not just numbers. We can store sections of text, called strings in a String variable, for example. (Java prefers the term "member" over variable, in general. For what we're talking about now, the two terms are interchangeable.) We can also store more than one thing at a time, like all the information about a bicycle in a Bicycle object that keeps track of a bicycle's color, frame size, tire size, gear ratios, etc., all together in one object.

But we're here to just look at assignment today, not the wide variety of things we can assign as values.

To store a value on a calculator, you use some key sequence like M+ or STO 00 to store the value in the calculator's display to memory. With Java, we use the equals sign to store some value on the right into whatever is on the left side of the equals sign. We read from left to right like this:

count = a;
"count equals a"

This means we take the value of a and place it in count. But a better way to read that equals sign is to use the word "becomes" instead of "equals":

count = 9;
"count becomes nine"

This makes it more obvious that we're putting in a new value that changes the value of count. In this case, we're putting in a value of 9. The statement up above would be "count becomes a" or, better yet, "count becomes a's value." Because what we're doing in count= a; is taking the value in variable a and copying it into count. If we then print the value in count, it will be the same as whatever is in a at that time.

We can also compute a value to put into our variable.

count = a + 1;
"count becomes a plus one"

This makes the value in count be one more than the current value of a.

What we can't do is change sides around the equals sign. In algebra, c = a + 1 is the same as a + 1 = c. But in Java that doesn't work:

a + 1 = count
This is wrong in Java. Does not compute. Norman, Norman, help me Norman!

We would be trying to make a+1 become the value in count. The problem is, you can't have a storage location named "a+1". Java doesn't see this the way your algebra trained eyes do.

Comparisons

In normal math, when we use the equals sign we are making a comparison. We are stating that what's on one side of the equals sign is the same as what's on the other side. For most algebra problems, we assume that the statement is true and try to find values for the variables that result in that.

Another use of equals in some math problems is to state that two things are equal when they may or may not be, then determine whether that statement is true or not. You remember those problems, they looked something like this:

State whether each of the following is true or false.
1. 11 = 6 + 5
2. 14 = 3 x 7
3 65 - 14 = 17 x 3


In Java, the equals sign is already used for assigning values to variables. How do we do a comparison to see whether it's true or not?

The == Operator

In some languages, = does both jobs. But in Java, there's a second operator for doing equality comparisons, ==, "equals equals". When we want to see if two values are the same, we compare them using a statement something like this:

if (count == 100) then stop();

This compares count to the value 100, and executes the method stop() if the result of the comparison is true.


The Dangers of the = Operator

Something to look out for is using = by accident in such a situation. Like this:

if (count = 100) then stop();
Don't do this if you want to compare count to 100!

What this does is assign the value 100 to count. If the assignment is successful (which it almost certainly will be, if the program compiles), the program will then do stop() every time it hits this statement! Because the assignment was successful, so the result is considered to be true.

Summary

The equals sign makes the variable on the left equal the computed value from the right side of the equals sign:

name = "Mergatroyd";
"name becomes Mergatroyd"

It doesn't work the other way around (putting something from the left into the variable on the right.)

If you want to compare to values to see if they're equal, use "equals equals":
if (state == "done") then exit();
"if state equals equals done then exit" or
"if state is equal to done then exit"
StumbleUpon

Friday, May 27, 2011

Doing Math in Java part 1: Operators

One of the most valuable uses of a computer is...computing. That is, acting as a mathematical calculator. Java has a plethora of tools for doing computation.

Operators

The standard math functions that are built into the Java language are called operators. These are the sort of math functions you would expect to find on a simple calculator, plus some extras:

+ - * / % ++ --


There are other operators used for comparisons, these are the math operators. You can learn more about them in the Java Language Specification, specifically in Integer Operations, Floating-Point Operations, and more extensively through Chapter 15, Expressions.

+ and - do what you would expect, they add and subtract one value from another. * is the symbol used for multiplication, instead of the × used in math class. * is used because it's easier for the computer to recognize it as a math operator, × just looks like a letter 'x' to the computer. Similarly, / is used for division. The ÷ sign isn't on most keyboards, but / has been common on keyboards even before they were attached to computers.

The % sign doesn't do what you might, at first, expect. It doesn't calculate a percentage, as it does on most calculators. It returns the remainder of a division. For example, if you do 10/3 (ten divided by three), the result will be 3. But what if you want to get the remainder? That's what % does. 10%3 will return a value of 1. '%' is sometimes called "modulo". It's a bit of a misnomer, mathematically, but the use of the term is common and well understood, so it's not unusual to pronounce 10%3 as "ten modulo three". This is a very valuable function for keeping a value within a certain range, such as keeping an object located onscreen in graphics by having it "wrap" from one side of the screen to the other when it reaches an edge.

++ and -- are the "increment" and "decrement" operators. Increment means "go up by one unit", and decrement "go down by one unit". So if you've got a variable like:

int i = 5;

And you do i++, the value of i will become 6. Doing i-- will take away 1. ++ and -- can be placed either before or after the value they act on, for example:

number = i++;
count = --j;


There will be different effects on your program depending on whether they come before or after the value. You can find information on that in the Java Language Specification as well, in sections 15.14 and 15.15 which cover the two ways of using these operators. In general, it's best to stick to using them after your value until you understand the differences.

Assignment Operators

You can also do math as part of assigning a value. For example, let's say we want to add three to a value in our program. The obvious way to do this would be:

i = i + 3;

This takes the prior value of i, adds 3 to it, then puts the result back into variable i. With an assignment operator we can do the same thing more tersely:

i += 3;

We've combined the + with = to create an operator. This does the same thing as i = i + 3;. Your program doesn't care which way you type it. The same thing can be done with the other operators that take two values:

i *= 4; // Multiply i by four, store result back in i.
i /= 2; // Divide i in half.
i %= 3; // Put the remainder of i/3 in i.
i -= 7; //Subtract seven from i.


More Complex Math

This is what we can do with the basic math operators built into the language. To get more operations, like those found on a scientific or programmer's calculator, we use methods of some of the standard packages of Java. Which I'll cover in a future article.

Until then, have a look at java.lang.Math.
StumbleUpon