I am implementing a custom input method (softkeyboard ) for android...Its a gesture detection keyboard,so I will capture the direction the users swipes and the code for that.In doing so,I have some combination of letters like "Th" and "Ch" for which I would need the int value.The char values can be easily converted ,but how to get int values for combination of characters...Please suggest.
I need getCharacter(code) to return an int.
Only by successive calls to getCharacter().. take a step back and see that this method is not the best point to be implementing what youre trying to do. The handler that returns the multiple chars (strings) should implement getCharacter() successively on every character in the string. If I am understanding the problem correctly.
Related
I'm actually using Math.sin() in my android app to calculate a sinus of a given angle (using Math.toRadians(angle_in_degrees)). For exemple when I want to get the Math.cos(90) which is 0, the result is 6.123233... E-17. Thanks you.
For floating point numbers, the system can often only approximate their values. For instance, the system would return something like 0.333333 for the expression (1.0 / 3). The number of 3s after the decimal point will be different depending on whether you're a floats or doubles, but it will still be limited to some finite length.
If you're just displaying the value, then you can limit the number of digits using something like String.format("%0.2f", value) or by rounding it using one of the rounding functions such as Math.round().
The tricky part comes when you need to compare the value to something. You can't just use if (value == some_constant) or even if (value == some_variable). At minimum, you usually have to use something like if (Math.abs(value - some_constant) < 0.001). The actual value of the '0.001' depends on the needs of your particular application and is customarily defined as a named constant.
For more complicated needs, you can implement the algorithm in the Floating-Point Guide.
You're getting back an approximation from Math.cos(Math.toRadians(90)) which is
6.123233... E-17 == 0.00000000000000006123233... which is basically 0
The following link should help clear things up as far as the precision of doubles/floats in programming.
http://www.java67.com/2015/09/float-and-double-value-comparison-in-java-use-relational.html
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!
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.
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?
I have a few questions concerning the application I'm designing. I have many different routes I could try in order to get what I wanted, but I thought I would get suggestions instead of doing trial and error.
I'm developing a simple app that has one Game screen (activity) and a main menu to start the game. The game screen will have two buttons, "Next" and "Repeat". Every time "Next" is hit, a new sentence in a different language (with the english translation below it) will appear, audio will pronounce the sentence, and hopefully I can get a highlighter to highlight the part of the sentence being spoken. You can guess what the Repeat button does.
My question is, what do you guys think would be the best way to store these sentences so they can be randomly picked out? I thought about making an array of structures or classes with the English definition, audio, and sentence in each structure. Then using a random iterator to pick one out. However, it would take a long time to do this approach and I wanted to get some ideas before I tried it.
Also, I'm not sure how I would print the sentence and definition on the screen.
Thanks!
Using an array of structs/classes seems like that would be the normal way to go.
Not really sure what you mean by a random iterator, but when picking out random sentences from the array of sentences, you might want to avoid repeats until you've gone through all the elements. To do that, you can make a second array of indices, select one at random from those, use the element that corresponds to that index, and remove that number from the array of indices.
In Java, that would look something like
ArrayList<Sentence> sentences;
ArrayList<Integer> indices;
Random rand;
private void populateIndices() {
for(int i = 0; i < sentences.size(); i++)
indices.add(i);
}
public Sentence getNextSentence() {
if(indices.isEmpty())
populateIndices();
int idx = rand.nextInt(indices.size());
int val = indices.get(idx);
indices.remove(idx);
return sentences.get(val);
}
Quite frankly I would load out of copyright books from Project Gutenberg and randomly pull sentences from them. I would then pass the sentences into Google APIs to translate and pronounce the sentences. Relying on external services is at the very heart of what a connected OS like Android is made for. It would be a much more compelling use of the platform than a canned Rosetta Stone like CD solution and your ability to tap into a broader amount of content would be increased exponentially.