Why doesn't Integer.parseInt work on a substring? - java

This conversion is not working, I am getting an exception,
not sure why
String str = "Draw: 1";
int draw = 0;
String temp;
temp = str.substring(5,7);
draw= Integer.parseInt(temp);
System.out.println(draw);

Because you're trying to parse " 1", notice the space. Adding a trim() should solve it.
temp = str.substring(5,7).trim();

Related

Number format issue, newbie project

I am trying to write a program that loads a movie data base file, and then splits up that information into the movie title, year, and all of the associated actors. I split up all of the info, but I am having issues converting the year, which is in a string, to an int. The format of the year string is (****) with the * being a year, such as 1999. When I try to use parse I get a number format exception. I have tried replacing the parentheses, but it just gave me more errors! Any ideas?
public class MovieDatabase {
ArrayList<Movie> allMovie = new ArrayList<Movie>();
//Loading the text file and breaking it apart into sections
public void loadDataFromFile( String aFileName) throws FileNotFoundException{
Scanner theScanner = new Scanner(aFileName);
theScanner = new Scanner(new FileInputStream("cast-mpaa.txt"));
while(theScanner.hasNextLine()){
String line = theScanner.nextLine();
String[] splitting = line.split("/" );
String movieTitleAndYear = splitting[0];
int movieYearIndex = movieTitleAndYear.indexOf("(");
String movieYear = movieTitleAndYear.substring(movieYearIndex);
System.out.println(movieYear);
//this is where I have issues
int theYear = Integer.parseInt(movieYear);
String movieTitle = movieTitleAndYear.substring(0, movieYearIndex);
ArrayList<Actor> allActors = new ArrayList<Actor>();
for ( int i = 1; i < splitting.length; i++){
String[] names = splitting[i].split(",");
String firstName = names[0];
Actor theActor = new Actor(firstName);
ArrayList<Actor> allActor = new ArrayList<Actor>();
allActor.add(theActor);
}
Movie theMovie = new Movie(movieTitle, theYear, allActors);
allMovie.add(theMovie);
}
theScanner.close();
}
output:
(1967)
Here is the errors I am getting:
Exception in thread "main" java.lang.NumberFormatException: For input string: "(1967)"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
at MovieDatabase.loadDataFromFile(MovieDatabase.java:27)
You have brackets around the numbers. You could either correct your file or you could remove brackets using:
String str = "(1967)";
System.out.println(str.substring(1, str.length()-1));
Output:
1967
In your code, you used:
int movieYearIndex = movieTitleAndYear.indexOf("(");
String movieYear = movieTitleAndYear.substring(movieYearIndex);
So if my movieTitleAndYear string is "hi (1947)", indexOf will give me index of "(" as 3 and substring will start reading string from index 3 which includes "(". One way you could avoid opening bracket is to change your substring line to:
String movieYear = movieTitleAndYear.substring(movieYearIndex + 1);//but still you have closing bracket.
If you are sure it's always going to be of four digit, then you could do something like:
String movieYear = movieTitleAndYear.substring(movieYearIndex + 1, movieYearIndex + 5);
You need to add indexof for ")".
Code snippet:
int movieYearOpenBracesIndex = movieTitleAndYear.indexOf("(");
int movieYearCloseBracesIndex = movieTitleAndYear.indexOf(")");
String movieYear = movieTitleAndYear.substring(movieYearOpenBracesIndex + 1, movieYearCloseBracesIndex);
System.out.println(movieYear);
This will give the exact year. e.g. 1967
Your substring call currently gets a year enclosed by brackets, e.g., (1967). You can avoid this by calling the substring variant that accepts an endIndex, and just get the year's four digits:
String movieYear =
movieTitleAndYear.substring(movieYearIndex + 1, // to get rid of "("
movieYearIndex + 5 // to get rid of ")"
);

Remove all characters except last n characters from a string

i am trying to remove all text except last 10 characters but getting error in android
09-15 16:22:58.146: E/AndroidRuntime(13630): java.lang.StringIndexOutOfBoundsException: length=228; index=263
but it is working on java when i tried it in separate class.
here is what i tried? can anybody tell me if there is any issue regarding substring in android?
String allchar =
"PJGOGROG fnkmslkjsfsdmnsgdnklnsgklsgknlgrf jkghijgdlkjkgjdfkjgf kjlgdfkjlfdgfjklklj
kljfdkjlfkjldfdkjslkljdfskjlfsjkldfsjklkljs
fdsjklsdfkljsfdkljkhgfhhgdfsgkhdfskghfdskghfdsghsfdghafevbhfsvgydcgubcdmgycdgfehkhfeghjgh68
Alias12345";
String number = "";
String reqtext = allchar.replaceAll("\\s+","");
number = reqtext.substring(reqtext.length()-10 );
System.out.println(number);
Well if substring() doesn't work, you can try doing it manually:
String allchar =
"PJGOGROG fnkmslkjsfsdmnsgdnklnsgklsgknlgrf jkghijgdlkjkgjdfkjgf kjlgdfkjlfdgfjklklj
kljfdkjlfkjldfdkjslkljdfskjlfsjkldfsjklkljs
fdsjklsdfkljsfdkljkhgfhhgdfsgkhdfskghfdskghfdsghsfdghafevbhfsvgydcgubcdmgycdgfehkhfeghjgh68
Alias12345";
StringBuilder number = new StringBuilder();
String reqtext = allchar.replaceAll("\\s+","");
for(int i = reqtext.length()-10; i < reqtext.length(); i++)
{
number.append(reqtext.charAt(i));
}
System.out.println(number.toString());
String allchar = "PJGOGROG fnkmslkjsfsdmnsgdnklnsgklsgknlgrf jkghijgdlkjkgjdfkjgf kjlgdfkjlfdgfjklkljkljfdkjlfkjldfdkjslkljdfskjlfsjkldfsjklkljsfdsjklsdfkljsfdkljkhgfhhgdfsgkhdfskghfdskghfdsghsfdghafevbhfsvgydcgubcdmgycdgfehkhfeghjgh68Alias12345";
String number = "";
String reqtext = allchar.replaceAll("\\s+","");
number = reqtext.substring(reqtext.length()-10, reqtext.length());
System.out.println(number);
This code works fine for me in android.
Avoid declaring so many variable, try using :
number = allchar.substring(allchar.length()-10, allchar.length());

How To Create Phone Number Format XXX-XXX-XXXX In Android

Can anybody help me to solve this problem ?
I want "-" between phone numbers.
I tried . It shows XXX-XXX-XXX-X Formats only . But i want XXX-XXX-XXXX Format .
Here Below I have mentioned my code.
Declare This under Oncreate
TextView TxtDocPhone=(TextView)findViewById(R.id.TxtDocPhone);
String numbersOnly = keepNumbersOnly(Phone);
String ProviderPhone = formatNumbersAsCode(numbersOnly);
Then call it
private String keepNumbersOnly(CharSequence s) {
return s.toString().replaceAll("[^0-9]", "");
}
private String formatNumbersAsCode(CharSequence s) {
int groupDigits = 0;
String tmp = "";
for (int i = 0; i < s.length(); ++i) {
tmp += s.charAt(i);
++groupDigits;
if (groupDigits == 3) {
tmp += "-";
// tmp += "";
groupDigits = 0;
}
}
return tmp;
}
Please guide me the correct way to achieve my objective.
Try this way,hope this will help you to solve your problem.
String formattedNumber = PhoneNumberUtils.formatNumber(unformattedNumber);
Take a look at PhoneNumberUtils for more options.
Finally i solve this issue . Just add below this in formatNumbersAsCode function .
return String.format("%s-%s-%s",s.subSequence(0,3),s.subSequence(3,6),s.subSequence(6,10));
You can try:
private String formatNumbersAsCode(CharSequence s) {
return String.format("%s-%s-%s",s.substring(0,3),s.substring(3,6),s.substring(6));
}
You best way to go is to use Regular Expressions.
You know your phone number should have the format XXX-XXX-XXXX, so you just write an appropriate RegEx for this, and you are fine!
Format with a space (" ") and then make a replaceall to the "-" character.

Usage of the java function 'split()

I would like to split the word in java based on the delimeter'-'when it appeared last.
I am expecting the result as "sweet_memory_in" and "everbodylife#gmail.com". Do we have any inbuilt function in java.
Complete word is sweet_memory_in_everbodylife#gmail.com
String s = "sweet_memory_in_everbodylife#gmail.com";
String first = s.substring(0,s.lastIndexOf("_"));
String second = s.substring(s.lastIndexOf("_")+1 );
try this
String s = "sweet_memory_in_everbodylife#gmail.com";
String s1 = s.substring(0,s.lastIndexOf("_"));
String s2 = s.substring(s.lastIndexOf("_")+1,s.length());
Regex may help. Other way is to get the last index of _ and use substring to split it.
Try out this code :
String data = "sweet_memory_in_everbodylife#gmail.com";
int lastIndex = data.lastIndexOf("_");
String firstSplit = data.substring(0, lastIndex);
String secondSplit = data.substring(lastIndex + 1, data.length());
System.out.println(firstSplit);
System.out.println(secondSplit);
Try this my friend (Javascript Codes):
var str = 'sweet_memory_in_everbodylife#gmail.com';
var arr1 = str.substring(str.lastIndexOf("_")).split("_");
var arr2 = str.split("_"+arr1[1]);
alert(arr2[0] +" --> "+arr1[1]);

Parse string starting from the end

I want to split string around only the last _ character , example:some_string_foo_bar into two substrings some_string_foo bar.
I tried to use Pattern and StringTokenizer, but they always start from the beginning of stirng. Any idea how to do this?
Use lastIndexOf; there's no reason to do a full split.
Sure, this might be of some use. Here's an example.
String source = "hello_world_foo";
int pos = source.lastIndexOf('_');
String before = source.substring(0, pos);
String after = source.substring(pos + 1);
You can use:
String strX = "some_string_foo";
String str1 = strX.substring(0,strX.lastIndexOf("_"));
String str2 = strX.subscting(strX.lastIndexOf("_"),strX.length());
String[] arr = str.split("_");
String lastOne = arr[arr.length-1];

Categories