Ambiguousness in Android Java source - java

EditText ed1 = (EditText)findViewById( R.id.editText1 );
int a = Integer.parseInt( ed1.getText().toString() );
Does the above code get the input as numeric from the user and show it as a string?
My requirement is to get the input as integer and return as Strings. How do I do that?

Is the above code referencing that get the input as numeric from the user and show it as string?
The other way round - it's going through these steps:
Find the EditBox
Get the text from the edit box
Parse the text as a number
My requirement is to get the input as integer and return as Strings
Get the input from where? If you're getting the input from a user then it's probably already in a string form. If you're trying to convert an integer from somewhere else in the code, then you could use
String text = Integer.toString(number);
... or you could use a NumberFormat object, which would take different cultural information into account, allowing for grouping of digits etc.

EditText ed1=(EditText)findViewById(R.id.editText1);
String ed1Str = ed1.getText().toString().trim();
int a = Integer.parseInt(ed1Str);
Will make it available as an integer (int a) and as a string (String ed1Str)

The EditText.getText() returns Editable object and you have to convert it to string. You cannot get the number directly from edit text. You can access the text returned from EditText, convert it to String and then covert it into number as you have implemented.

do little modification in above code ed1.setInputType(InputType.TYPE_CLASS_NUMBER);
that will make your edittext only to accept integer values..

Related

How to display Interger in jTextField?

How can I have an interger display in jTextField? I have made a scoring using if statement, but then the int cannot be display in the jTextField.
I would suggest you to use Integer Class for your purpose as it will give you lot more other functionality apart from this. If you are using Integer class, you can use Integer.toString() to easily convert any integer value directly to the string or it may implicitly type convert it to String. Then the statement would look like as
JTextField_variblename.setText() = integer_variablename.toString();
For more information on the Integer Class and toString() function, visit Class Integer- Oracle Java Docs
You can concatenate it with a string by using :
int valueToBeSet = 100;
jTextFieldName.setText("" + valueToBeSet);
The JTextField wants a string parameter and not an integer parameter so you must convert your integer to a string. The easiest way to do this is by:
int intScore = 1;
String stringScore = "" + intScore;
You can now use stringScore in your JTextField.
You can use String.valueOf in String class to convert to String type.
int i =1;
jTextField1.setText(String.valueOf(i));
I hope this may provide answer to your question.Happy coding.

Parse double from JFormattedTextField

I've got a bug or something. I have a method that saves an article, like this:
class SaveArticleListener implements ActionListener {
//....
String s = textArticlePrice.getText().replace(',','.').replaceAll("\\s","");
double price = Double.parseDouble(s);
//....
}
Where textArticlePrice is a JFormattedTextField which configured like:
NumberFormat priceFormat = NumberFormat.getNumberInstance();
priceFormat.setMaximumFractionDigits(2);
priceFormat.setMinimumFractionDigits(2);
textArticlePrice = new JFormattedTextField(priceFormat);
textArticlePrice.setColumns(10);
And in the parseDouble method I'm getting every time:
java.lang.NumberFormatException: For input string: "123 456 789.00"
So replace works with a dot, but not with whitespace... Why?
You'd be better off using your NumberFormat to parse the String. Keep a reference to priceFormat, and then use
double price = priceFormat.parse(textArticlePrice.getText()).doubleValue();
The formatter that's being used to display the number is the same one then used to turn it back into a double so you know it's going to be parsing it in a compatible way.
Best of all is
double price = ((Number) textArticlePrice.getValue()).doubleValue();
which should work without any need for conversion if you've set your JFormattedTextField up properly. (The getValue() call returns an Object, so you need to cast it. It might return a Double or a Long, depending on what's in the text field, so the safe way to get a double out of it is to treat it as a Number, which is the supertype of both, and invoke its .doubleValue() method.)
Writing something that converts it into something that can be parsed by Double.parseDouble() is really not the right way to go because it's too fragile if the formatting of your text field changes later on.
Regarding your question" why doesn't it work with white spaces". White spaces are chars just like a,l,#,?,¡, but it only recognises ,12345, numbers together as a number, you cant make an int variable 'int number = 1 234; Its the same with parsing. Rather try,
s = s.replace(',','.');
s = s.replace(" ","");
Price = Double.parseDouble(s);
Assuming that '123 456 789.00' is one number.
please comment if this helped.
I did this now, it worked fine
String strNumber = "1 2 3 4 5 6.789";
double DblNumber = Double.parseDouble(strNumber);
System.out.Println(DblNumber);// this displays the number if your IDE has an output window

java convert from string to int

I need to parse the value of a label so that it can be stored as an Integer
JLabel lblSeatNo;
int seatNo;
seatNo = Integer.parseInt(lblSeatNo.getText());
It has worked other times I have used with method, however now I am getting a Number Format Exception and I don't understand why.
If it helps with value of the label can vary, it's general format is something like: "A131" or "B504"
Thankyou.
Assuming you want this as a hex number (that is base 16), you must supply the radix to your parseInt call -
seatNo = Integer.parseInt(lblSeatNo.getText(), 16);
if you want the decimal value (e.g. base 10) and to skip the letter, you could do
seatNo = Integer.parseInt(lblSeatNo.getText().substring(1));
Try int value = Integer.parseInt(hexString, 16); if you know that the string representation will always be hexadecimal. You might also want to check the documentation of the method in question.
Depends on what you are wanting:
If you want to just parse the numbers (not including a, b, etc) then you have to call substring to remove the letter.
if the letter is meant to be there as a hex number then you can call
Integer.parseInt(hexNo, 16)
follow this link
How to parse hex color String to Integer
eg. Integer.parseInt(myHexValue,16)
From your comments it seems like you want to extract just the number from the Seat label. But since you say that you also need to recreate the seat label then in your object you may also want to add a String for the row which will contain the Letter
So you could do something like this (assuming only ever a single letter)
int seatNo = Integer.parseInt(lblSeatNo.getText().substring(1));
String row = lblSeatNo.getText().subString(0,1);
Then to get the label again
String label = row + seatNo;

Java: NumberFormatException in converting string to integer

I want to retrieve value from textbox and convert it to integer. I wrote the following code but it throws a NumberFormatException.
String nop = no_of_people.getText().toString();
System.out.println(nop);
int nop1 = Integer.parseInt(nop);
System.out.println(nop1);
The first call to System.out.println prints me the number but converting to integer gives an exception. What am I doing wrong?
Note that the parsing will fail if there are any white spaces in your string. You could either trim the string first by using the .trim method or else, do a replace all using the .replaceAll("\\s+", "").
If you want to avoid such issues, I would recommend you use a Formatted Text Field or a Spinner.
The latter options will guarantee that you have numeric values and should avoid you the need of using try catch blocks.
Your TextBox may contain number with a white space. Try following edited code. You need to trim the TextBox Value before converting it to Integer. Also make sure that value is not exceeding to integer range.
String nop=(no_of_people.getText().toString().trim());
System.out.println(nop);
int nop1 = Integer.parseInt(nop);
System.out.println(nop1);
Try this:
int nop1 = Integer.parseInt(no_of_people.getText().toString().trim());
System.out.println(nop1);
I would suggest replacing all non-digit characters from String first converting to int:
replaceAll("\\D+", "");
You can use this code:
String nop=(no_of_people.getText().toString().replaceAll("\\D+", ""));
System.out.printf("nop=[%s]%n", nop);
int nop1 = Integer.parseInt(nop);
System.out.printf("nop1=[%d]%n", nop1);

Java Double to String conversion without formatting

I have the number 654987. Its an ID in a database. I want to convert it to a string.
The regular Double.ToString(value) makes it into scientific form, 6.54987E5. Something I dont want.
Other formatting functions Ive found checks the current locale and adds appropriate thousand separators and such. Since its an ID, I cant accept any formatting at all.
How to do it?
[Edit] To clarify: Im working on a special database that treats all numeric columns as doubles. Double is the only (numeric) type I can retrieve from the database.
Use a fixed NumberFormat (specifically a DecimalFormat):
double value = getValue();
String str = new DecimalFormat("#").format(value);
alternatively simply cast to int (or long if the range of values it too big):
String str = String.valueOf((long) value);
But then again: why do you have an integer value (i.e. a "whole" number) in a double variable in the first place?
Use Long:
long id = 654987;
String str = Long.toString(id);
If it's an integer id in the database, use an Integer instead. Then it will format as an integer.
How about String.valueOf((long)value);
What about:
Long.toString(value)
or
new String(value)
Also you can use
double value = getValue();
NumberFormat f = NumberFormat.getInstance();
f.setGroupingUsed(false);
String strVal = f.format(value);
If what you are storing is an ID (i.e. something used only to identify another entity, whose actual numeric value has no significance) then you shouldn't be using Double to store it. Precision will almost certainly screw you.
If your database doesn't allow integer values then you should stored IDs as strings. If necessary make the string the string representation of the integer you want to use. With appropriate use of leading zeros you can make the alphabetic order of the string the same as the numeric order of the ints.
That should get you round the issue.
What about Long.toString((long)value) ?
double d = 56789;
String s = d+"";

Categories