My program sets a numeric value to an editText field..I am trying to convert the edittext values to an integer..I have failed in all the attempts i have tried..Here is how the editText field receives the value:
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
DogExpenditure dogExpenditure = postSnapshot.getValue(DogExpenditure.class);
totalAmount[0] += dogExpenditure.getAmount();
textView3.setText(Integer.toString(totalAmount[0] ));
}
}
textView3.setText(Integer.toString(totalAmount[0] I am doing this because the totalAmount[0] cannot be accessed anywhere else other than inside that program so i decided to pull it from the editText(not sure about this) though i havent succeeded. i get java.lang.NumberFormatException: Invalid int: "" error:
Here is how i tried :
String diff = String.valueOf(textView3.getText());
Integer x = Integer.valueOf(diff);
String saley = String.valueOf(textView5.getText());
Integer v = Integer.valueOf(saley);
NB: the textView5 and textView5 are both EditText fields..
A NumberFormatException tell you the String is not a number.
Here, the String is empty so this can't be parse. A solution would be to check for that specific value, like Jesse Hoobergs answer.
But this will not prevent an exception if I input foobar. So the safer solution is to catch the exception. I let you find the correct solution to manager the value if this is not a numerical value.
Integer number;
try{
number = Integer.valueOf(s);
} catch(NumberFormatException nfe){
number = null; //Just an example of default value
// If you don't manage it with a default value, you need to throw an exception to stop here.
}
...
At startup, the value of the editText seems to be an empty string ("").
I think you can best check for empty strings or make sure the initial value isn't an empty string.
String diff = String.valueOf(textView3.getText());
Integer x = null;
if(!diff.trim().isEmpty())
x = Integer.valueOf(diff);
an example that may help you
boolean validInput = true;
String theString = String.valueOf(textView3.getText());
if (!theString.isEmpty()){ // if there is an input
for(int i = 0; i < theString.length(); i++){ // check for any non-digit
char c = theString.charAt(i);
if((c<48 || c>57)){ // if any non-digit found (ASCII chars values for [0-9] are [48-57]
validInput=false;
}
}
}
else {validInput=false;}
if (validInput){// if the input consists of integers only and it's not empty
int x = Integer.parseInt(theString); // it's safe, take the input
// do some work
}
Ok i found out a better way to deal with this..On startup the values are null..so i created another method that handles the edittext fields with a button click after the activity has been initialised..and it works..
private void diffe() {
String theString = String.valueOf(textView3.getText().toString().trim());
String theStringe = String.valueOf(textView5.getText().toString().trim());
int e = Integer.valueOf(theString);
int s = Integer.valueOf(theStringe);
int p = s - e ;
textView2.setText(Integer.toString(p));
}
Related
I have a long String with binary values. And i have a hash map that has the Binary digits as a key and char as a value. I have a function that supposed to read the binary string using 2 pointers and compare with hashmap and store the corresponding char in main.decodedTxt. However, im getting string out of bound exception for this. I don't know how to solve this. I'm getting exception on "String temp =" line. I have a picture link of the console output to see better picture.
public static void bitStringToText (String binText){
String bs = binText;
int from =0;
int to = 1;
while(bs != null){
String temp = bs.substring(from, to);
if (main.newMapDecoding.containsKey(temp)){
main.decodedTxt += main.newMapDecoding.get(temp);
from =to;
to = from +1;
} else {
to = to + 1;
}
}
}
Image of console exception is here
First of all there is no need to check if bs is null because no part of your code changes the value of bs. Your current code will cross the possible index of your binText at some point. It's better to loop just binText and check if you find something within it. After all you have to traverse the complete string anyways. Change your code as follows
public static void bitStringToText (String binText){
//no need to do this if you are not modifying the contents of binText
//String bs = binText;
int from =0;
int to = 1;
int size = binText.length();
String temp = "";
while(to <= size ){
temp = binText.substring(from, to);
if (main.newMapDecoding.containsKey(temp)){
main.decodedTxt += main.newMapDecoding.get(temp);
from =to;
to = from +1;
} else {
to = to + 1;
}
}
}
Hope it helps.
First, give it a try to practice debugging. It is an easy case. Either use run in debug mode (place break point on String temp = bs.substring(from, to); line) or print values of from and to before the same line. It will help to understand what is going on.
Solution:
If bs is not null you will always have StringIndexOutOfBoundsException. Because you are not checking if to is pointing to not existed index of bs String. Easiest example of the first one will be empty String: bs == "".
One of the solution could be to replace condition in while to while (to <= bs.length()).
When I choose a row on the table it prints out the selected item in a string as shown. How do I remove the square brackets from either side of the string.
Below is my code to populate TextFields with the data. You can see it populates successfully but with the [].
the table and output
tableView.getSelectionModel().selectedItemProperty().addListener((v, oldValue, newValue) -> {
String input = newValue.toString();
String[] str_array = input.split(", ");
String code = str_array[0];
String name = str_array[1];
String lecturer = str_array[2];
String year = str_array[3];
String semester = str_array[4];
codeInput.setText(code);
nameInput.setText(name);
lectureInput.setText(lecturer);
yearInput.setText(year);
semesterInput.setText(semester);
System.out.println(input);
});
You newValue should be an Object. Let's say it's an object of SchoolInfo with variables of String code, String name, String lecturer, int year, and int semester. Your Object should have Getters and Setters. You should do something like.
Warning: Some of those other answers may get the job done but are very bad ideas. The way you are trying to handle this data is a bad idea.
tableView.getSelectionModel().selectedItemProperty().addListener((v, oldValue, newValue) -> {
SchoolInfo tempSchoolInfo = (SchoolInfo)newValue;
String code = tempSchoolInfo.getCode();
String name = tempSchoolInfo .getName();
String lecturer = tempSchoolInfo.getLecturer;
int year = tempSchoolInfo.getYear();
int semester = tempSchoolInfo.getSemester();
codeInput.setText(code);
nameInput.setText(name);
lectureInput.setText(lecturer);
yearInput.setText(Integer.toString(year));
semesterInput.setText(Integer.toString(semester));
System.out.println(input);
});
You can either remove the first and last character with input.substr(1, input.length - 1) or just remove them with input.replace("[","").replace("]","") if no other occurrences are possible.
Arrays.stream(str_array).collect(Collectors.joining(","));
this produces desired result without need of 'post processing'
I am having a particular pattern of string
page0001
page0002
.
.
.
pageMN23
pageMN24
.
page0100
page0101
and so on
I have to remove "page" and zero's after that and then pick up the page number from that.
and stroe that value. Here it will return both integer and string value for example "3","4" ,"MN23", MN24".
What can be used so that correct value return and it get store in correctly.
test = test.replace("page", "");
int x = Integer.parseInt(test);
Just replace all the occurrences of "page" with an empty string, then Integer.parseInt() takes care of the rest.
Use this:
String test = "page0100";
boolean flag = false;
int pageNo;
try {
test = test.replaceAll("page0*", ""); //Note the meta character * after 0. It removes all zeros exists after `page` string and before any non zero digit.
pageNo = Integer.parseInt(test);
} catch (NumberFormatException e) {
// If NumberNumberFormatException caught here then `test` is string
// NOT valid integer
flag = true;
}
if (flag == false) {
// Page Number is string
// Use `test` variable here
} else {
// Page Number is integer
// Use `pageNo` variable here
}
from JTable, I try to get values (which are string) of each column from [row 1 to ..end of row] and calcul sum of values as follow :
final ArrayList<String>ValuesList = new ArrayList<String>();
final int nb = myTable.getRowCount();
int sum=0;
for (int i = 1; i < nb; i++)
{
String columnValue = myTable.getColumnValue(i, columnName);
sum=sum+Integer.parseInt(columnValue);
ValuesList .add(columnValue);
}
but I got :
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
You have at least one empty cell in your table.
Here's a suggestion:
try {
sum += Integer.parseInt(columnValue);
} catch (NumberFormatException nfe) {
// the cell is either empty or not an integer number
// will be treated as zero (0)
}
Note, that the method getColumnValue(int i, String name) is not defined for javax.swing.JTable. If you use a subclass of JTable then the error could be in that class/method too: it may return an empty string instead of a cell value.
I guess you will need to convert an empty String or null value to zero.
So you need to trim the whitespaces when you get the String value and then check if the string is empty.
Here is what your code should look like
final ArrayList<String>ValuesList = new ArrayList<String>();
final int nb = myTable.getRowCount();
int sum=0;
String columnValue = "";
for (int i = 1; i < nb; i++)
{
columnValue = myTable.getColumnValue(i, columnName).trim();
if (!columnValue.isEmpty()) {
sum=sum+Integer.parseInt(columnValue);
}
ValuesList.add(columnValue);
}
Put a check for null/empty string before calling the conversion with parseInst.
if (columnValue != null && !columnValue.isEmpty())
sum=sum+Integer.parseInt(columnValue);
I am not sure about exact syntax so verify before using it.
If columnValue is empty (""), you can't parse it. Just skip the that column in this case, i.e.
if( columnValue != null || columnValue.length() > 0 ) {
//parse and add here
}
Note that I added the check for null just in case, you might not need it if myTable.getColumnValue(...) is guaranteed to never return null.
Also note that you might try and handle other cases as well, depending on what values might be in your table. If blank strings like " " or general alpha-numeric values are allowed, you need to account for that as well.
Finally, why are your values stored as strings if they actually are numbers? Why don't you store them as Integer objects right away?
If the empty String means 0 in your case, you can just check this before:
if (!columnValue.equals(""))
sum=sum+Integer.parseInt(columnValue);
Or even better:
if(!columnValue.isEmpty())
sum=sum+Integer.parseInt(columnValue);
An empty string cannot be converted to an int. If you want to treat it as 0, add the appropriate if statement.
What the compiler is telling you is that you are trying to convert an empty string "" to an int . So you may want to check that you are converting strings that actually represent integers!
How do I convert a string into an integer?
I have a textbox I have the user enter a number into:
EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
And the value is assigned to the string hello.
I want to convert it to a integer so I can get the number they typed; it will be used later on in code.
Is there a way to get the EditText to a integer? That would skip the middle man. If not, string to integer will be just fine.
See the Integer class and the static parseInt() method:
http://developer.android.com/reference/java/lang/Integer.html
Integer.parseInt(et.getText().toString());
You will need to catch NumberFormatException though in case of problems whilst parsing, so:
int myNum = 0;
try {
myNum = Integer.parseInt(et.getText().toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
int in = Integer.valueOf(et.getText().toString());
//or
int in2 = new Integer(et.getText().toString());
Use regular expression:
String s="your1string2contain3with4number";
int i=Integer.parseInt(s.replaceAll("[\\D]", ""));
output:
i=1234;
If you need first number combination then you should try below code:
String s="abc123xyz456";
int i=NumberFormat.getInstance().parse(s).intValue();
output:
i=123;
Use regular expression:
int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));
output:
i=123;
j=123;
k=123;
Use regular expression is best way to doing this as already mentioned by ashish sahu
public int getInt(String s){
return Integer.parseInt(s.replaceAll("[\\D]", ""));
}
Try this code it's really working.
int number = 0;
try {
number = Integer.parseInt(YourEditTextName.getText().toString());
} catch(NumberFormatException e) {
System.out.println("parse value is not valid : " + e);
}
Best way to convert your string into int is :
EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
int converted=Integer.parseInt(hello);
You should covert String to float. It is working.
float result = 0;
if (TextUtils.isEmpty(et.getText().toString()) {
return;
}
result = Float.parseFloat(et.getText().toString());
tv.setText(result);
You can use the following to parse a string to an integer:
int value=Integer.parseInt(textView.getText().toString());
(1) input: 12 then it will work.. because textview has taken this 12 number as "12" string.
(2) input: "abdul" then it will throw an exception that is NumberFormatException.
So to solve this we need to use try catch as I have mention below:
int tax_amount=20;
EditText edit=(EditText)findViewById(R.id.editText1);
try
{
int value=Integer.parseInt(edit.getText().toString());
value=value+tax_amount;
edit.setText(String.valueOf(value));// to convert integer to string
}catch(NumberFormatException ee){
Log.e(ee.toString());
}
You may also want to refer to the following link for more information:
http://developer.android.com/reference/java/lang/Integer.html
There are five ways to convert
The First Way :
String str = " 123" ;
int i = Integer.parse(str);
output : 123
The second way :
String str = "hello123world";
int i = Integer.parse(str.replaceAll("[\\D]" , "" ) );
output : 123
The Third Way :
String str"123";
int i = new Integer(str);
output "123
The Fourth Way :
String str"123";
int i = Integer.valueOf(Str);
output "123
The Fifth Way :
String str"123";
int i = Integer.decode(str);
output "123
There could be other ways
But that's what I remember now
You can also do it one line:
int hello = Integer.parseInt(((Button)findViewById(R.id.button1)).getText().toString().replaceAll("[\\D]", ""));
Reading from order of execution
grab the view using findViewById(R.id.button1)
use ((Button)______) to cast the View as a Button
Call .GetText() to get the text entry from Button
Call .toString() to convert the Character Varying to a String
Call .ReplaceAll() with "[\\D]" to replace all Non Digit Characters with "" (nothing)
Call Integer.parseInt() grab and return an integer out of the Digit-only string.
The much simpler method is to use the decode method of Integer so for example:
int helloInt = Integer.decode(hello);
Kotlin
There are available Extension methods to parse them into other primitive types.
"10".toInt()
"10".toLong()
"true".toBoolean()
"10.0".toFloat()
"10.0".toDouble()
"10".toByte()
"10".toShort()
Java
String num = "10";
Integer.parseInt(num );
I have simply change this
int j = Integer.parseInt(user.replaceAll("[\\D]", ""));
into
int j = 1;
AND IT SOLVE MY PROBLEM