Android: Calculator on showing 0 immediately after the dot - android

I am now working on a calculator, and everything works fine except for decimal places.
The calculator contains 2 displays actually, one is called fakedisplay for actual operations, and one is called Display, for presenting the desired format, ie adding commas.
When pressing 12345.678, Display will follow fakedisplay and present as 12,345.678, but if i press 12345.009, the fakedisplay will work normally as 12345.009, but the Display stuck as 12,345 until 9 is pressed, and at that time it will show 12,345.009 normally.
However, it is strange that when the user presses 0, there is no response, and until pressing 9, 009 will then immediately append.
I know this arise from the parsing code, but based on this, how could I amend the following code? I really cannot think of any solution... Many thanks for all your advice!
one.setOnClickListener(new View.OnClickListener() {
if (str.length()<15) {
Fakedisplay.append("1");
}
DecimalFormat myFormatter1 = new DecimalFormat("###,###,###,###.#################");
String str1=Fakedisplay.getText().toString();
String stripped1 = Double.valueOf(str1).toString();
stripped1 = myFormatter1.format(Double.valueOf(stripped1));
if (stripped1.endsWith(".0"))
stripped1 = stripped1.substring(0, stripped1.length() - 2);
Display.setText(stripped1);
}

Probably the easiest solution is to not strip off the .0 in the code for every keystroke..
Instead, only strip off trailing zeros (assuming there's a decimal point in there of course) when the user calls for a result. Entering keys such as the digit keys 0 through 9, the decimal point ., or the sign-change key +/- (what I'll call the entry keys) are not generating a result so should not strip trailing zeros.
However, non-entry keys, such as when you press + or - or = on your calculator can freely modify the number.
That will give you a display of the digits being entered as the user enters them but will still strip off trailing zeros when necessary.
You can do that with a modification to your statement (and, as mentioned, only doing this when the user presses a non-entry key):
stripped1 = stripped1.replaceAll("(\\.[0-9]*[1-9])0+$","$1");
stripped1 = stripped1.replaceAll("\\.0$","");
The first statement removes all trailing zeros at the end of a decimal number (other than on if it's really an integer). The second takes care of that case.
No doubt I could make a single substitution if I gave it some more thought but that should be enough to get it functional.

Related

Android: regex for edit text to have only 2 values possible in decimal

In my filter used into EditText, I want to be sure the user can only set .5 or .0 for decimal values.
Valid values examples:
34.5
34.0
34
Invalid values examples:
34.2
34.8
34.6
I tried this one, but it doesn't work properly: [0-9]*[.]?[0|5]
Thank you very much guys!
You're probably looking for [0-9]*(\.([50][0]*)*)*.
[0-9]*: Any character from 0 to 9, zero or more times [so that just a "." (= 0.0) input is valid]
\.: You need to escape the '.' character, since it usually would mean "any character", and you especifically need the dot there.
[50][0]*: First, either five or zero (once). Second, the 0 character, zero or more times (since 35.50 = 35.5). This also avoids inputs like 35.59 from being valid, since 9 != 0.
([50][0]*)*: This occurrence zero or more times, so that 35., for instance, becomes a valid input (since 35. = 35.0).
(\.([50][0]*)*)*: As for this grouping, it's in order to check for the five or the zero only if there is a decimal dot. It's grouping the dot character and the 5/0 logic together with a star (zero or more times) at the end, so if it doesn't occur, it still matches.
Let me know if this was what you were looking for.
To verify the whole numbers in the examples, you can make the last part optional and use anchors.
^[0-9]+(?:[.][05])?$
^ Start of string
[0-9]+ Match 1+ digits 0-9
(?:[.][05])? Optionally match . and a digit 0 or 5
$ End of string
See a regex demo.
If you want to be able to only type a pattern like that and also accept empty strings or 34. you can repeat the digit 0 or more times, optionally match . and optionally match either 0 or 5.
^[0-9]*[.]?[05]?$
See another regex demo

Why does my looping instruction to input values for a character array of 6 elements stop after 3 inputs?

I'm new to C and programming in general. I'm stuck wondering why this thing is happening. Basically, I wrote this simple program to input a 6 character array from the user, and to print the same out. I'm using CPPDroid on my Android phone to compile and execute the code;
#include"stdio.h"
int main()
{
char c[6];
for(int i=0;i<=5;i++)
{
scanf("%c",&c[i]);
}
for(int j=0;j<=5;j++)
{
printf("%c",c[j]);
}
return 0;
}
For some reason, the first loop simply exits out before the rest of the elements are filled. I'd get an output like this (I entered a,b,s as the first 3 elements):
a
b
s
a
b
s
It just simply only takes 3 elements rather than 6, and prints them back. What's going on?
My apologies if this is a well known issue. I'm not familiar with terms used in programming much, so it's not easy for me to search for questions.
All the answers and comments mentioned it right. I will just add one more thing. Earlier the \n were also taken as input by the scanf. As a result
your loop ended and still the characters you desired were not read.
why the solution scanf("%c ",..) works?
Now, the trailing one is telling scanf() to skip any trailing
whitespace after the character input. It therefore keeps reading input
until it sees something that is not whitespace or the end of the
stream.
Also as pointed out, the leading white space would also let you achieve the same thing with the added benefit of having a smooth interactive input.
To give you an idea of what I mean I would give an excample:
int n,m;
scanf("%d ",&n);
printf("n is %d\n",n);
printf("Give 2nd number\n");
scanf("%d ",&m);
printf("m is %d\n",m);
So now you start giving input.
1
Enter
Now you expect so see the output n is 1. But it seems like it stopped.
You again type 2Enter
Now you see the output: n is 1. Then you see the output
n is 1
6<enter>
Give 2nd number
m is 2
That's what I meant when asked to avoid the trailing whitespace.
When you type in:
a
b
s
The Enter keystroke is counted as its own character (the newline character, '\n'), so you end up storing the following in c: ['a', '\n', 'b', '\n', 's', '\n'].
If you want to consume the newline, you can include it in the scanf() call; something like this:
scanf("\n%c",&c[i]);

Android Studio version of an Excel vlookup?

Ok I'm a massive noob and apart from following lots of tutorials I like to set myself a problem and then try to fix it with an app. Therefore I'm trying to make a little app that'll help me when I'm at work.
Basically it needs to breakdown a 4 character string into it's individual characters and then display them phonetically. So if I (the user) type in 5F9A then it'll display FIVE FOXTROT NINE ALPHA. At work we have an excel spreadsheet that does this all and I'm just trying to reverse engineer it. The spreadsheet itself has multiple stages, it reads the characters, converts them into ASCII and then performs a vlookup on a range of cells where each ASCII code is next to it's phonetic pronunciation. It looks for the number 53 (5 in ASCII) and then looks at the cell next to it which says FIVE.
I've managed to translate any user input into ASCII but I just don't know how to store and access this next set of data. I've been looking into SQLite but that is waaaaaay beyond me at the moment and seems far to complicated for something this simple?
Anyway, I know it's cheating asking for the answer, but maybe a push in the right direction?
The dummy way to do that would be:
Get every letter (char) of the word
Have a switch case that gives you the phonetic equivalent (you will have to do that by hand)
String word = yourWord;
String phonetic;
char currentChar;
for(i=0;i<=word.lenth();i++){
currentChar = word.substring(i, i+1);
phonetic = getPhonetic(currentChar)
}
String getPhonetic(char char){
switch char{
case a:
return alpha;
break;
case b:
....
}
}

Calculator app approach

as getting into android i decided to replace the default calculator with mine. A simple calculator with the 4 operational signs. I've been giving to all buttons the right behaviour, storing every number in a 'num' ArrayList(String) and signs in a 'sign' ArrayList(String).
What i wanted to do, was to then combine numbers and signs into a string, parse it into a float and getting a result. I thought this was one of the easy/simple ways to deal with it, since when you set a float like this:
float f = 6*4-5/2+3
it gives you the right result. but it clearly does not when starting from a String, like this:
String s = "6*4-5/2+3"
Float f = Float.valueOf(s)
Is there a way to getting a result from my 2 ArrayList(String)? In the negative case, what would be a doable approach (in the sense im not an experienced programmer)I?
I Think this approach is incorrect.
I would do the following:
You would have a Textview or Edittext as the calculator "screen" on top.
then you would have all your number and operation signs buttons.
Now, every number you press, it will append to the last one on the screen, using .append()
once you tap on an operator sign - two things will happen:
1) the number in the textView will be stored as a Float (using Float.valueOf(yourTextView); in a varibale, say firstNum.
2) you will save the operator you clicked in a second variable, say String calcOper.
Now, you enter your second number, and then you would press the Equals sign.
What will happen then is simply use a Switch of If expression.
If calcOper is "-" - then do firstNum- Current number shown on screen.
If calcOper is "+" - then do firstNum+ Current number shown on screen.
At last don't forget to set the text on the TextView the result.
Good luck!

Scan string for characters and return bounded text

I am writing a dictionary-type app. I have a list of hash-mapped terms and definitions. The basic premise is that there is a list of words that you tap on to see the definitions.
I have this functionality up and running - I am now trying to put dynamic links between the definitions.
Example: say the user taps on an item in the list, "dog". The definition might pop up, saying "A small furry [animal], commonly kept as a pet. See also [cat].". The intention is that the user can click on the word [animal] or [cat] and go to the appropriate definition. I've already gone to the trouble of making sure that any links in definitions are bounded by square brackets, so it's just a case of scanning the pop-up string for text [surrounded by brackets] and providing a link to that definition.
Note that definitions can contain multiple links, whilst some don't contain any links.
I have access to the string before it is displayed, so I guess the best way to do this is to do the scanning and ready the links before the dialog box is displayed.
The question is, how would I go about scanning for text surrounded by square brackets, and returning the text contained within those brackets?
Ideally the actual dialog box that is displayed would be devoid of the square brackets, and I need to also figure out a way of putting hyperlinks into a dialog box's text, but I'll cross that bridge when I come to it.
I'm new to Java - I've come from MATLAB and am just about staying afloat, but this is a less common task than I've had to deal with so far!
You could probably do this with a regular expression; something like this:
([^[]*)(\[[^]]+\])
which describes two "match groups"; the first of which means any string of zero or more characters that aren't "[" and the second of which means any string starting with "[", containing one or more characters that aren't "]", and ending with "]".
Then you could scan through your input for matches to this pattern. The first match group is passed through unchanged, and the second match group gets converted to a link. When the pattern stops matching your input, take whatever's left over and transmit that unchanged as well.
You'll have to experiment a little; regular expressions typically take some debugging. If your link text can only contain alphanumerics and spaces, your pattern would look more like this:
([^[]*)(\[[\s\w]+\])
Also, you may find that regular expression matching under Android is too slow to be practical, in which case you'll have to use wasyl's suggestion.
Quite simple, I think... As the text is in brackets, you need to scan every letter. So the basic recipe would be :
in a while loop scan every character (let's say, while i < len(text))
If scanned character is [:
i++;
Add letter at index i to some temporary variable
while (character # i) != ']' append it to the temporary variable
store this temporary variable in a list of results.
Some tips:
If you use solution above, use StringBuilder to append text (as regular string is immutable)
You might also want (and it's better, I think) to store starting and ending positions of all square brackets first, and then use string.substring() on each pair to get the text inside. This way you'd first iterate definition to find brackets (maybe catch unmatched ones, for early error handling), then iterate pairs of indices...
As for links, maybe this will be of use: How can I get clickable hyperlinks in AlertDialog from a string resource?

Categories

Resources