I FINALLY have the map and points(arrays) working for my app. Quick question: I have a fatal exception with substring(), a "stringIndexOutOfBoundException"
In general, what is that referring to?
An I going past the end of a string using substring()?
Thanks,
testing.substring(1,2);
(I want to parse each character to find specific characters)
I wouldn't use substring() for grabbing 1-length strings (which is just a single character), but rather charAt(int) for specific positions. If you need to go over all characters in the string, you're probably better off with by converting the whole thing to a char[] first (using toCharArray()) and iterate over that.
Yes, you're going past the end of your strings bounds generally.
The Java API even tells you so...
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
You should get used to using the API. It tells you what exceptions a method throws and why.
Try printing the Strings length and value before attempting substring. That'll help you see the problem.
For example...
String testing = "Hello StackOverflow";
System.out.println("Length of testing = " + testing.length);
System.out.println("Value of testing = " + testing);
testing.substring(1,2);
Like stated in the official doc here:
public String substring(int beginIndex)
Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
Throws: IndexOutOfBoundsException - if beginIndex is negative or
larger than the length of this String object.
Related
I have to build a calculator and i am making some validations, the code is kinda long so i will only put the part that is breaking it.
It is a validation that makes the multiplication, it breaks when trying to multiply a negative number, every other operation is done correctly but the multiplication:
else if(resulttxt.getText().toString().contains("*")){
String resultarray=resulttxt.getText().toString();
String[] split=resultarray.split("\\*");
finalresult = Double.valueOf(split[0]) * Double.valueOf(split[1]);
if (finalresult<0){
negative=true;
}else{
negative=false;
}
resulttxt.setText(String.valueOf(finalresult));
resulttxt is received from a TextView that gets it's data from cliking on the numbers or the signs which are also TextViews (not buttons but they do have the On click listener)the operation is done when ciclking on the = sign.
This throws an error if for example i try to do -6*45:
java.lang.NumberFormatException: Invalid double: "6*45"
Like i said everything works with the addition,substraction and division it is only the multiplication that breaks.
I tried executing your code in the compiler :
String resulttxt = "-6*45";
boolean negative = false;
if(resulttxt.contains("*")){
String resultarray=resulttxt;
String[] split=resultarray.split("\\*");
double finalresult = Double.valueOf(split[0]) * Double.valueOf(split[1]);
if (finalresult<0){
negative=true;
}else{
negative=false;
}
System.out.println(finalresult);
}
Every thing worked fine for, please verify datatype used in your program.
addition, multiplication and division works fine. "-6+45, -6*45 and -6/45"(any other combination. I just used the same)
However for subtraction as the pattern is "-6-45" the above logic will fail and throw number format exception. This is because if you split "\-", the "-" is first character in string and there is nothing before it.
Thus your split will fail. So to avoid this you can always take last index of character to split using substring function.
OMG dudes... this is what was the problem:
I had this validation at the end of the other operations, so BEFORE even going to the multiplication part it entered the "-" validation when it checks
if(resulttxt.contains("-")){
because it is a negative value so it does have a "-"... so it entered as a substraction instead as a multiplication because of that...
To solve it i had to put the substraction validation at the bottom of all of them.
So thank you for the guys who suggested me to check the line where the error was thrown i wouldn't have known logcat actually tells you were the mistake is and to my surprise it was on the substraction validation which to me was a "WTF" moment and then i realized what i just told you.
Try this instead :
String s1 = resultarray.substring(0,resultarray.indexOf("*"));
String s2 = resultarray.substring(resultarray.indexOf("*")+1,resultarray.length());
double d1= Double.valueOf(s1);
double d2= Double.valueOf(s2);
Hope this helps
I am creating a calculator app in android. It should calculate anonymously whatever is on textBox. For e.g. I enter 1+2.5-5*8 in textBox. But when I call addition method the app gets crashed. Because the input is in string format and answer I want is in numeric format. I used string buffer. I tried in java that when I enter (1+1+3-1) in stringBuffer and I display using println() method it give correct answer but same does not happen with string buffer when I take that value from editText.
You have to convert string into integer or float.
Use Integer.parseInt("") method to covert to integer and Float.parseFloat("") to convert to float.
First of all welcome to StackOverFlow
It might help if you add code and the error log in the question
So I am gonna cover all the possible things that might be happening wrong in your program:
NumberFormatException- you might not be converting the string "12" into int 12 to do so use Interger.parseInt(your string buffer with number only here);
Try using a stack and a queue for your solution (google it you will get details)
You might be making a mistake in getting string from edittext it sometimes give NullPointerException
if above is not enough comment and add your code asap
I write app for Android such gets data from server in JSON format. Now I get this value in string, but in my application it must look like:
Route:
1)first point
2)secon point
3).....
n) n point
I read that in Android in textView I can do it if string will be with html tags but I think it is not the best variant. After Android I must do it in iPhone now I don't know how to do that there. Send Routes as Array is not good variant too. Can you say what is the best way to decide this problem?
Have a look here you will have to find the good pattern .
Hence you have separated strings just use a list View with an ArrayAdapter.
I am not so good with regex but i think it should like : [1-9][0-9]) [[a-f][0-9]]+
I couldn't comment b/c of rep, sorry. Could you provide an example of returned JSON string. I think JSON format can be parsed with ease.
If this the case you can parse it in a loop (or another way. I'm not that good at it)
String[] parseIt (String JSON){
String[] list=JSON.split("\\d\\)");
String[] rlist=new String[list.length-1];
for(int i=0;i<list.length-1;i++){
rlist[i]=list[i+1].trim();
}
return rlist;
}
This might do trick. But you should edit result. I didn't test yet
Edit: I edited code. It simply return the address now with leading whitespace. You can get rid off them using. String trim() method like;
list[1].trim();
Do it in loop and don't care about first element (index 0).
Edit 2: Now it should work
I need calculate a thing. but my formula sentence has occur some problem.
TextView ticketP = (TextView)findViewById (R.id.ticketQ);
ticketP.setText(oneSession.getTicketOder());
String Ctotal = "";
Ctotal = jsonObject.optString("price");
String OneTotal = oneSession.getTicketOder() * Ctotal; // this part has occur the problem which is the operator * .
You'll need to convert the Strings to numeric type before performing any multiplication. Depending on the type of numeric value you are using take a look Double.parseDouble(String string) or Integer.parseInt(String string).
int oneTotal = Integer.valueOf(oneSession.getTicketOder()) * Integer.valueOf(Ctotal);
to convert it again to String use
String.valueOf(oneTotal)
Yes. Your going to have to use the parsing methods in order to convert the string to a native numerical type. You also need to be care about a few things with your code.
json.optString() can return null. opt = optional.
I would suggest using json.getInt() or json.getDouble() this will not only give you the correct type, but also throw an exception if the values aren't correct.
Secondly your going to have to convert your numerical answer back to a string if you want to display it. But this is easy enough with a .toString() or + "" if you are lazy.
Why does this code trigger a force close in Android?
`score.setText(Integer.parseInt((String) score.getText())+1);`
score is a TextView, and I am simply increasing the number by 1. I have predefined a String resource to be the initial number in the score TextView.
I am quite frustrated.
First off you should try breaking down your code so you can actually see what is going on with it.
Instead of
score.setText(Integer.parseInt((String) score.getText())+1);
try
String tmp = score.getText().toString();
int score;
score = Integer.parseInt(tmp) + 1;
score.setText(String.valueOf(score));
EDIT: Upon further reading of the documentation, setText has several overloads, one of which DOES take an int, but it takes the int of a resource ID. My guess is that your score is not a valid resource ID, thus crashing your application.
public final void setText (int resid)
Oh and as far as the frequent FC's when beginning Android Dev, it happens to the best of us. The key is to learn WHY the FC's happen, and have a LOT of patience.
mostly u need to do this
score.setText(Integer.parseInt(score.getText().toString())+1);
coz.. getText() returns a Editable Object which cannot be parsed to Integer. So it give NumberFormat Exception.
AndMake sure to set TextView,s Text to an integer initially..
try this way
score.setText(String.valueOf(Integer.parseInt(score.getText().toString())+1));
as you can pass the integer value that's why getting force the application
TextEdit.setText takes a CharSequence as input.
You are supplying an integer through Integer.parseInt((String) score.getText())+1
See, if converting it back to string and using it in setText helps.
You can convert an integer to string using Integer.toString.
PS: I am new to java myself.
The compiler should have ideally caught this error.
It's possible java uses some implicit type conversions from string to int.