I have an EditText object (et_travel) on my screen that's asking for miles traveled. I grab that data like this:
float travel = Float.parseFloat(et_travel.getText().toString());
if(travel > 40000){
I just discover that if someone puts 40000 in the EditText, everything works fine, but if they put 40,000 (adding a comma to the number), I force close on the float travel = ...statement.
How can I evaluate the number without having a problem from the user adding a comma?
Is this in Java? It appears to be, but I'm wondering if I'm mistaken. Regardless, I would suggest you remove all of the characters from the string that are not of a numeric type. A way to do this may be using a regular expression.
A way to do this in Java may be the following:
String input = et_travel.getText().toString();
input = input.replaceAll("[^0-9]", "");
float travel = Float.parseFloat(input);
...
This way, you strip anything that is a non-numeric value from the string first, and then attempt to do your work. Obviously do some error checking before this (like input is not null and such). One change that is needed however is that you may need to maintain the '.' character (if you're given non-integer values). This would require changing the first regex a bit.
Check here: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)
What you need is some validation on the input. Before converting the string into a float parse the string. If there are any ','s then remove them. If there is just junk then reject the input, otherwise someone could put a word or anything else in the input and cause havoc in your program.
Check out
inputType to restrict user input
android:inputType="number"
Related
Is there a way to prevent the program from executing characters in "Menu" type program where you choose options while running console and enter numbers only to do steps and browse data.
My program is a book catalog where you can review, change, add or delete information.
Things wouldn't be as bad but the the thing is, that when you enter a letter or non-number character the program gets messy and stuck.
I am not adding my code since I think that there should be a universal command to get rid of my problem + it would take some time to translate my code into EN.
The easiest way to do it is use the getline function I think. Instead of using cin >> num; for example, you would use getline(cin,value); where "value" is a string that you first store your input in. Then you can do num = atoi(value.c_str()); to save the string input as an integer value into "num". If "num" is a float, then just use atof instead of atoi. This way if the string is not a number, it just sets the value to 0. You could then use an if statement to display an error message if the value of num == 0. Hope that helps. Good luck!
If your application runs in a console and you are worried about wrong (non-number) input, perhaps you should the input not as a number, but as a text and then parse it to see it is really a number. If not, tell the user the input is incorrect and let them enter it again.
I have a dataset with data collected from a form that contains various date and value fields. Not all fields are mandatory so blanks are possible and
in many cases expected, like a DeathDate field for a patient who is still alive.
How do I best represent these blanks in the data?
I represent DeathDate using xsd:dateTime. Blanks or empty spaces are not allowed. All of these are flagged as invalid when validating using Jena RIOT:
foo:DeathDate_1
a foo:Deathdate ;
time:inXSDDatetime " "^^xsd:dateTime .
foo:DeathDate_2
a foo:Deathdate ;
time:inXSDDatetime ""^^xsd:dateTime .
foo:DeathDate_3
a foo:Deathdate ;
time:inXSDDatetime "--"^^xsd:dateTime .
I prefer to not omit the triple because I need to know if it was blank on the source versus a conversion error during construction of my RDF.
What is the best way to code these missing values?
You should represent this by just omitting the triple. That's the meaning of a triple that's "not present": it's information that is (currently) unknown.
Alternatively, you can choose to give it the value "unknown"^^xsd:string when there's no death date. The solution in this case is to not datatype it as an xsd:dateTime, but just as a simple string. It doesn't have to be a string of course, you could use any kind of "special" value for this, e.g. a boolean false - just as long as it's a valid literal value that you can distinguish from actual death dates. This will solve the parsing problem, but IMHO if you do this, you are setting yourself up for headaches in processing the data further down the line (because you will need to ask queries over this data, and they will have to take two different types of values into account, plus the possibility that the field is missing).
I prefer to not omit the triple because I need to know if it was blank
on the source versus a conversion error during construction of my RDF.
This sounds like an XY problem. If there are conversion errors, your application should signal that in another way, e.g. by logging an error. You shouldn't try to solve this by "corrupting" your data.
I am reading a text file with my fortran code. I parse the text file (which contain a bunch of stuff such as names and numbers) and I end up with strings containing real number (they are real time measuraments) such as:
string = 1.34
I simply write this string in a real number by doing
read(levelCHAR,'(f)') level
And everything worked great for a month until today, when the number in the input file was exactly 1 and I had:
string = 1
and the read statement above gave me
level=0
Therefore to fix this I added before the read statement:
if (index(string ,'.')<=0) then
string = trim(string )//'.'
endif
And this seems to have fixed the issue. However, I wanted to know if I am missing something and there is a more elegant way to do this in one line for example by replacing the format '(f)' in the read statement with a more suitable expression.
Your program is not valid Fortran:
read(levelCHAR,'(f)') level
1
Error: Nonnegative width required in format string at (1)
form.f90:5.5:
You must indicate the input field with such as f5.0. Or you can use the list-directed input read(levelChar,*) level.
Also, be sure to use the .0 and not any other number in the fw.d descriptor for input. Otherwise strange results are to be expected for integer inputs as they will be multiplied by 10**(-d).
I have to write a MATLAB function with the following description:
function counts = letterStatistics(filename, allowedChar, N)
This function is supposed to open a text file specified by filename and read its entire contents. The contents will be parsed such that any character that isn’t in allowedChar is removed. Finally it will return a count of all N-symbol combinations in the parsed text. This function should be stored in a file name “letterStatistics.m” and I made a list of some commands and things of how the function should be organized according to my professors' lecture notes:
Begin the function by setting the default value of N to 1 in case:
a. The user specifies a 0 or negative value of N.
b. The user doesn’t pass the argument N into the function, i.e., counts = letterStatistics(filename, allowedChar)
Using the fopen function, open the file filename for reading in text mode.
Using the function fscanf, read in all the contents of the opened file into a string variable.
I know there exists a MATLAB function to turn all letters in a string to lower case. Since my analysis will disregard case, I have to use this function on the string of text.
Parse this string variable as follows (use logical indexing or regular expressions – do not use for loops):
a. We want to remove all newline characters without this occurring:
e.g.
In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
In my younger and more vulnerableyears my father gave me some advicethat I’ve been turning over in my mindever since.
Replace all newline characters (special character \n) with a single space: ' '.
b. We will treat hyphenated words as two separate words, hence do the same for hyphens '-'.
c. Remove any character that is not in allowedChar. Hint: use regexprep with an empty string '' as an argument for replace.
d. Any sequence of two or more blank spaces should be replaced by a single blank space.
Use the provided permsRep function, to create a matrix of all possible N-symbol combinations of the symbols in allowedChar.
Using the strfind function, count all the N-symbol combinations in the parsed text into an array counts. Do not loop through each character in your parsed text as you would in a C program.
Close the opened file using fclose.
HERE IS MY QUESTION: so as you can see i have made this list of what the function is, what it should do, and using which commands (fclose etc.). the trouble is that I'm aware that closing the file involves use of 'fclose' but other than that I'm not sure how to execute #8. Same goes for the whole function creation. I have a vague idea of how to create a function using what commands but I'm unable to produce the actual code.. how should I begin? Any guidance/hints would seriously be appreciated because I'm having programmers' block and am unable to start!
I think that you are new to matlab, so the documentation may be complicated. The root of the problem is the basic understanding of file I/O (input/output) I guess. So the thing is that when you open the file using fopen, matlab returns a pointer to that file, which is generally called a file ID. When you call fclose you want matlab to understand that you want to close that file. So what you have to do is to use fclose with the correct file ID.
fid = open('test.txt');
fprintf(fid,'This is a test.\n');
fclose(fid);
fid = 0; % Optional, this will make it clear that the file is not open,
% but it is not necessary since matlab will send a not open message anyway
Regarding the function creation the syntax is something like this:
function out = myFcn(x,y)
z = x*y;
fprintf('z=%.0f\n',z); % Print value of z in the command window
out = z>0;
This is a function that checks if two numbers are positive and returns true they are. If not it returns false. This may not be the best way to do this test, but it works as example I guess.
Please comment if this is not what you want to know.
String a = keyboard.nextLine().ignoreUpperCase()
is this a valid line?
It depends on your intention. The code you shared isn't clear about what you intend to do with the line you are reading from the keyboard.
Like it already has been suggested you could, in Java:
String a = keyboard.nextLine().toLowerCase();
or
String a = keyboard.nextLine().toUpperCase();
The intention here is that all lines you are getting are in upper or lower case. Ok if you want to treat all Strings you read from the keyboard as equals regardless of capitalization.
If your real intention is to match strings regardless of case, then the code reads better as:
String a = "Hello World";
a.equalsIgnoreCase("hello world");
now future maintainers of your code will understand what you're trying to do instead of trying to guess why you are converting to lower/upper case.