java : convert string value to int - java

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!

Related

How to fix String index out of range: -1

I have been working on a generating password method that will change every "S" to $.
Note I take the phrase in from another class and it will always be greater than 8 characters
String key;
String store;
key = phrase.substring(0,1).toUpperCase();
phrase = key + phrase.substring(1,phrase.length());
System.out.println(phrase);
System.out.println(phrase.length());
for(int i = phrase.length(); i>0; i--) {
int sKey = phrase.indexOf('S');
store = "$" + phrase.substring(sKey+1,phrase.length());
phrase =phrase.substring(0,sKey)+store;
System.out.print(phrase);
}
}
However I always get this error afterwards
Exception in thread "main" Te$taaaajava.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at edu.ilstu.Security.generatePassword(Security.java:15)
at edu.ilstu.SecurityApp.main(SecurityApp.java:57)
Index out of range exception value of -1 means the requested symbol, in this case, S, is not found.
You take phrase.indexOf('S') on a string without checking the return value. If there is no match, the method returns -1. You then use this index as the upper bound of a substring, which crashes the program.
You would want a different algorithm even if you got it correct, if I understand correctly what you want to do. There is no reason both to search the string for each occurrence of the character you want and also to write a loop decrementing the length by 1. Also, avoid copying long arrays and strings if possible.
I am not sure if this is the correct way to do it. However, I have found adding an if statement actually fixed this code and stopped the for loop when the index becomes -1
String key;
String store;
key = phrase.substring(0,1).toUpperCase();
phrase = key + phrase.substring(1,phrase.length());
for(int i = phrase.length(); i>0; i--) {
int sKey = phrase.indexOf('S');
if(sKey >= 0) {
store = "$" + phrase.substring(sKey+1,phrase.length());
phrase =phrase.substring(0,sKey)+store;
}else {
i=0;
}
}```

java.lang.StringIndexOutOfBoundsException Error while reading Binary String

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()).

Converting EditText Value to int

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));
}

How to convert String to number in Java?

I have a parameter which is obtained as a string
String Dept_ID[] = request.getParameterValues("dept_id"))
in jsp. I have to insert the string in the db whose type is numeric
#DEPT_ID NUMERIC(10,0)).
How to perform the conversion?
Your code is receiving an array of strings. You can convert an entry from the array into a number using Integer.parseInt or Long.parseLong as appropriate.
For example:
String Dept_ID[] = request.getParameterValues("dept_id"));
int[] ids = null;
if (Dept_ID != null) {
ids = new int[Dept_ID.length];
for (int index = 0; index < Dept_ID.length; ++index) {
ids[index] = Integer.parseInt(Dept_ID[index]);
}
}
If the number uses a different radix (number base) than 10, you can supply the radix as a second arg (see the links for details).
The above answer is correct, but it doesn't take into account what happens when your getting letters as input that can't be converted. You wanna use a try and catch method for that part if you ask me.
Something like (assuming your using the code above):
String Dept_ID[] = request.getParameterValues("dept_id"));
int[] ids = null;
if (Dept_ID != null) {
ids = new int[Dept_ID.length];
for (int index = 0; index < Dept_ID.length; index++) {
try {
ids[index] = Integer.parseInt(Dept_ID[index]);
}
catch ( NumberFormatException e ) {
System.out.println("Invalid crap.");
}
}
}
Also notice that I put the ++index part the other way around to index++, if you don't do this you will keep missing the first index in the array all the time.

Error when try to parse String to Double

i have a string like this
106.826820,-6.303850,0
which i get from parsing the google Maps KML Document.
now i wanna parse its string to Double
this is my code :
public Double getLatitude(){
for(int posisi = GPS_NAME.indexOf(","); posisi > GPS_NAME.length(); posisi++){
TEMP_LAT = "" + GPS_NAME.indexOf(posisi);
}
GPS_LATITUDE = Double.valueOf(TEMP_LAT);
return GPS_LATITUDE;
}
public Double getLongitude(){
int posisiakhir = GPS_NAME.indexOf(",");
for(int i = 0; i < posisiakhir; i++){
TEMP_LON = "" + GPS_NAME.indexOf(i);
}
GPS_LONGITUDE = Double.valueOf(TEMP_LON);
return GPS_LONGITUDE;
}
but when i try to run it i got error like this
could somebody help me solving my problems >_<
and also confirm GPS_LATITUDE = Double.valueOf(TEMP_LAT); TEMP_LAT is not null there - as exception is NullPointerException not NumberFormatException.
You have null pointer exception so you should to it like this:
public Double getLatitude(){
for(int posisi = GPS_NAME.indexOf(","); posisi > GPS_NAME.length(); posisi++){
TEMP_LAT = "" + GPS_NAME.indexOf(posisi);
}
if (TEMP_LAT != null) {
GPS_LATITUDE = Double.parseDouble(TEMP_LAT);
}
return GPS_LATITUDE;
}
And for converting to double rather you should use Double.parseDouble() or also you can use new Double(TEMP_LAT).doubleValue() but first approach is cleaner.
Besides the probable causes for the NPE, I don't really get your logic; it looks completely dodgy to me.
Just some examples:
GPS_NAME.indexOf(",") will either return -1 or an index that is smaller than the length of the string in which is being searched. Then why have a condition that checks if it is larger than the length? posisi > GPS_NAME.length() will never be true, hence the for loops are useless...
Then inside the loops you do TEMP_LAT = "" + GPS_NAME.indexOf(posisi). From the earlier remark we know that posisi is either -1 or some other number that is smaller than the length of the string. So GPS_NAME.indexOf(posisi) will try to find a character repesented by the integer posisi (which will be a rather small number) in the string. How does that make sense?
I'd like to advise you to rethink your logic - perhaps String.split(",") is a good starting point.
Use Double.parseDouble(TEMP_LAT);

Categories