android String numberformatexception - java

i try to split String array and show rundom values in this array.i wrote function witch can split String
public int Cal(String ab) {
String[] arr=ab.split(":");
int av=(Integer.parseInt(arr[0])*60 + Integer.parseInt(arr[1]))*1000;
return av;
}
and i call this function like this
String[] st = {"00:49 ","00:49","02:17","03:26","03:55", "04:26", "05:25" };
Random random = new Random();
String index = st[random.nextInt(st.length)];
Log.e("randommmmmmmmmmmm", String.valueOf(Cal(index)));
i have numberformatexception exception. i have not idea what i am doing wrong

Use Trim() method like below,
public int Cal(String ab)
{
String[] arr=ab.split(":");
int av = ( Integer.parseInt(arr[0].trim())*60 + Integer.parseInt(arr[1].trim()))*1000;
return av;
}
trim() will remove spaces. Whenever you are trying to convert numeric string to number ( i.e. "11 " ), you should always remember to use trim() to avoid NumberFormatException

It means you are passing invalid number to parseInt method. The parseInt method of Integer class expects a valid string representation of a number

Your String array first element is having the space at the last --->> "00:49 "
String[] arr=ab.split(":");
Integer.parseInt(arr[1]) --------->>> This Leads to NumberFormatException
So Try Trimming the data before use..
int av=(Integer.parseInt(arr[0].trim())*60 + Integer.parseInt(arr[1]).trim())*1000;

Use the code as below.
public int Cal(String ab) {
String[] arr=ab.split(":");
int av=(Integer.parseInt(Integer.parseInt(arr[0]))*60 + Integer.parseInt(arr[1]))*1000;
return av;
}

Related

String builder initialized length,index out of bounds error

In the below code, I am getting the StringIndexOutOfBoundsException in sBuilder.insert(pos,words[i]); line,
I have initialized the length here new StringBuilder(s.length()) for the below input,
System.out.println(sortSentence("is2 sentence4 This1 a3"));
public static String sortSentence(String s) {
StringBuilder sBuilder=new StringBuilder(s.length());
String words[]= s.split(" ");
for(int i=0;i<words.length;i++)
{
int pos= Integer.parseInt(words[i].replaceAll("\\D+",""));
// this is the line of error
sBuilder.insert(pos,words[i]);
}
return sBuilder.toString();
}
This is the error I am getting,
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: offset 2, length 0
The length of the input String is 22 how can I get this error despite of this ?
If you check the code where the exception is raised it becomes clearer. StringBuilder's content has no such index, and the capacity from the constructor doesn't fill it by default.
static void checkOffset(int offset, int length) {
if (offset < 0 || offset > length) {
throw new StringIndexOutOfBoundsException("offset " + offset +
", length " + length);
}
}
Also the javadoc says it:
Inserts the string representation of the Object argument into this
character sequence. The offset argument must be greater than or equal
to 0, and less than or equal to the length of this sequence.
Throws: StringIndexOutOfBoundsException – if the offset is invalid.
Note: length, not capacity, of StringBuilder, not of the input string.
For the notion that sBuilder.setLength(s.length()); solves the problem: only if the perceived problem is the exception alone. setLength initializes the internally used array with (byte)0 btw, which gives a rather odd string as a result.
But then, why use a string builder in the first place? Just set everything in the original string to " " which is not an integer, can be done with a single regex like this one: s.replaceAll("[^0-9]", " ").
Or the other way: don't insert into stringbuilder, just append, solves the problem too, maybe, depending on the interpretation.
Looks like the whole issue belongs more on a code review site, imho.
What I understand that you are simply trying to remove spaces. I may suggest to go for much simpler approach. No need to start with capacity at all.
public class MyClass {
public static String sortSentence(String s) {
StringBuilder sBuilder=new StringBuilder();
String words[]= s.split(" ");
for(int i=0;i<words.length;i++)
{
int pos= Integer.parseInt(words[i].replaceAll("\\D+",""));
// this is the line of error
sBuilder.append(words[i]);
}
return sBuilder.toString();
}
public static void main(String args[]) {
System.out.println(sortSentence("is2 sentence4 This1 a3"));
}
}
OR
Simply use String replaceAll() method.

Check if any part of a string input is not a number

I couldnt find an answer for this in Java, so I'll ask here. I need to check if 3 parts of a string input contains a number (int).
The input will be HOURS:MINUTES:SECONDS (E.g. 10:40:50, which will be 10 hours, 40 minutes and 50 seconds). So far I am getting the values in String[] into an array by splitting it on :. I have parsed the strings into ints and I am using an if statement to check if all 3 parts is equal or larger than 0. The problem is that if I now use letters I will only just get an error, but I want to check if any of the 3 parts contains a character that is not 0-9, but dont know how.
First I thought something like this could work, but really dont.
String[] inputString = input.split(":");
if(inputString.length == 3) {
String[] alphabet = {"a","b","c"};
if(ArrayUtils.contains(alphabet,input)){
gives error message
}
int hoursInt = Integer.parseInt(inputString[0]);
int minutesInt = Integer.parseInt(inputString[1]);
int secondsInt = Integer.parseInt(inputString[2]);
else if(hoursInt >= 0 || minutesInt >= 0 || secondsInt >= 0) {
successfull
}
else {
gives error message
}
else {
gives error message
}
In the end I just want to check if any of the three parts contains a character, and if it doesnt, run something.
If you are sure you always have to parse a String of the form/pattern HH:mm:ss
(describing a time of day),
you can try to parse it to a LocalTime, which will only work if the parts HH, mm and ss are actually valid integers and valid time values.
Do it like this and maybe catch an Exception for a wrong input String:
public static void main(String[] arguments) {
String input = "10:40:50";
String wrongInput = "ab:cd:ef";
LocalTime time = LocalTime.parse(input);
System.out.println(time.format(DateTimeFormatter.ISO_LOCAL_TIME));
try {
LocalTime t = LocalTime.parse(wrongInput);
} catch (DateTimeParseException dtpE) {
System.err.println("Input not parseable...");
dtpE.printStackTrace();
}
}
The output of this minimal example is
10:40:50
Input not parseable...
java.time.format.DateTimeParseException: Text 'ab:cd:ef' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalTime.parse(LocalTime.java:441)
at java.time.LocalTime.parse(LocalTime.java:426)
at de.os.prodefacto.StackoverflowDemo.main(StackoverflowDemo.java:120)
I would personally create my own helper methods for this, instead of using an external library such as Apache (unless you already plan on using the library elsewhere in the project).
Here is an example of what it could look like:
public static void main(String[] arguments) {
String time = "10:50:45";
String [] arr = time.split(":");
if (containsNumbers(arr)) {
System.out.println("Time contained a number!");
}
//You can put an else if you want something to happen when it is not a number
}
private static boolean containsNumbers(String[] arr) {
for (String s : arr) {
if (!isNumeric(s)) {
return false;
}
}
return true;
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(.\\d+)?");
}
containsNumbers will take a String array as an input and use an enhanced for loop to iterate through all the String values, using the other helper method isNumeric that checks if the String is a number or not using regex.
This code has the benefit of not being dependent on Exceptions to handle any of the logic.
You can also modify this code to use a String as a parameter instead of an array, and let it handle the split inside of the method instead of outside.
Note that typically there are better ways to work with date and time, but I thought I would answer your literal question.
Example Runs:
String time = "sd:fe:gbdf";
returns false
String time = "as:12:sda";
returns false
String time = "10:50:45";
returns true
You can check the stream of characters.
If the filter does not detect a non-digit, return "Numeric"
Otherwise, return "Not Numeric"
String str = "922029202s9202920290220";
String result = str.chars()
.filter(c -> !Character.isDigit(c))
.findFirst().isEmpty() ? "Numeric"
: "Not Numeric";
System.out.println(result);
If you want to check with nested loop you can see this proposal:
Scanner scanner = new Scanner(System.in);
String [] inputString = scanner.nextLine().split(":");
for (int i = 0; i < inputString.length; i++) {
String current = inputString[i];
for (int k = 0; k < current.length(); k++) {
if (!Character.isDigit(current.charAt(k))) {
System.out.println("Error");
break;
}
}
}
you could use String.matches method :
String notANum= "ok";
String aNum= "7";
if(notANum.matches("^[0-9]+$") sop("no way!");
if(aNum.matches("^[0-9]+$") sop("yes of course!");
The code above would print :
yes of course
The method accepts a regex, the one in the above exemple is for integers.
EDIT
I would use this instead :
if(input.matches("^\d+:\d+:\d+$")) success;
else error
You don't have to split the string.
I tried to make your code better, take a look. You can use Java regex to validate numbers. also defined range for time so no 24:61:61 values is allowed.
public class Regex {
static boolean range(int timeval,int min,int max)
{
boolean status=false;
if(timeval>=min && timeval<max)
{status=true;}
return status;
}
public static void main(String[] args) {
String regex = "[0-9]{1,2}";
String input ="23:59:59";
String msg="please enter valid time ";
String[] inputString = input.split(":");
if(inputString[0].matches(regex) && inputString[1].matches(regex) && inputString[2].matches(regex) )
{
if(Regex.range(Integer.parseInt(inputString[0]), 00, 24) &&Regex.range(Integer.parseInt(inputString[1]), 00, 60) && Regex.range(Integer.parseInt(inputString[2]), 00, 60))
{msg="converted time = " + Integer.parseInt(inputString[0]) + " : " +Integer.parseInt(inputString[1])+ " : " +Integer.parseInt(inputString[2]) ;}
}
System.out.println(msg);
}
}

String Cannot Be Converted To Int

This is just a little bit of my code, but I am trying to loop through two strings, get the value of the first number in one string, and then use that number as the position to find in the other string, then add that word into a new string. But it comes up with the error "String cannot be converted to int" can anyone help?
String result = "";
for (int i = 0; i < wordPositions.length; i++){
result += singleWords[wordPositions[i]];
}
if your wordPositions is a String array when you do this:
result += singleWords[wordPositions[i]];
it like if you does this
result += singleWords["value of the wordPositions array at index i"];
but is need to be an int in [] not a string that why you have the exception String can not be cast to Int
If wordPositions is an array of numbers inside a string for example
String[] wordPositions = new String[]{"1","2","3"};
Then you nees to use
Integer.parseInt(NUMBER_IN_STRING);
To change the string value to an int value.
You are getting this error because wordPositions[i] returns a string and you need to convert it to int before trying to acess singlewords[].
result += singleWords[Integer.parseInt(wordPositions[i])];
Use this to convert String into int
Integer.parseInt(integerString);
The completed line of code:
result += singleWords[Integer.parseInt(wordPositions[i])];

Is there such thing as math.substring in java?

Okay, I'm just getting curious. But I was wondering if there was such thing as a substring for numbers (math.substring ?), and then it would get the character(s) in the position specified.
Example (really poorly thought out one)
int number = 5839;
int example = number.substring(0,1)
println = example;
and then it displays 5?
Why don't you just convert it to a string, and then call substring(0,1)?...
int number = 5839;
int example = Integer.parseInt((number+"").substring(0,1));
Where calling number+"" causes the JVM to convert it into a String, and then it calls substring() on it. You then finally parse it back into an int
int number = 5839;
String numString = Integer.toString(number);
String example = numString.substring(0,1)
int subNum = Integer.parseInt(example);
System.out.println(subNum);
Change it to a String first.
Here's a little function I wrote:
public static int intSubstring(int number, int beginIndex, int endIndex) {
String numString = Integer.toString(number);
String example = numString.substring(beginIndex,endIndex)
int subNum = Integer.parseInt(example);
return subNum;
}
Or compressed:
public static int intSubstring(int number, int beginIndex, int endIndex) {
return Integer.parseInt((number+"").substring(beginIndex,endIndex));
}
No there is not. But you could possibly convert the integer to string and get the substring and again parse back to integer
No there no such thing, but you can do the following:
String s = ""+number; //You can now use the Substring method on s;
Or if you just want to remove the last y digits:
number = (int)(number/y);
of if you want to keep only the last z digits:
number = number%(Math.pow(10,z)); // % means modulo
No, there is none. int is a primitive data type. You can however, accomplish your need with one statement.
Integer.parseInt(String.valueOf(12345).substring(1, 2))

Extract a substring up to 1000th comma

I have a string (comma seperated)
For example:
a,bgf,sad,asd,rfw,fd,se,sdf,sdf,...
What I need is to extract a substring up to the 1000th comma.
How to achieve this in Java?
An efficient way of doing this would be to use indexof(int ch, int fromIndex) intead of using split(String regex, int limit) or split(String regex) especially if the given string is long.
This could be done something like this
[pseudocode]
asciiCodeForComma = 0x2c
nextIndex=0
loop 1000 times
nextIndex= csv.indexof(asciiCodeForComma , nextIndex)
requiredSubString = csv.subString(0, nextIndex)
String csv = "some,large,string";
String[] parts = csv.split(",");
String thousandthElement = null; // the default value if there are less than 1000
if (parts.length > 999)
thousandthElement = parts[999];
You can use StringTokenizer with comma as separator, then loop nextToken() 1000 times.
I think he is asking for all 1000 element.. This should solve your problem. Understand and then copy-paste as this is ur homework :)
public static void main(String[] args) {
// TODO Auto-generated method stub
String samplecsv = "a,bgf,sad,asd,rfw,fd,se,sdf,sdf,";
String[] splitedText = samplecsv.split(",");
StringBuffer newtext = new StringBuffer();
for (int i = 0; i < 3; i++) {
newtext.append(splitedText[i]);
}
System.out.println(newtext);
}
So to solve this problem what you need to do is understand how to extract a string from a delimiter separated input stream. Then executing this for the case for N strings is trivial. The pseudocode for doing this for the individual record is below:
function parse(inputValue, delimiter)
{
return inputValue.split(delimiter)
}
Now to do that for the case where there are N inputValues is equally as trivial.
function parse(inputValues, delimiter)
{
foreach inputValue in inputValues
returnValue.append(parse(inputValue,delimiter)
return returnValue
}
There is actually built in functionality to do this by putting a second argument into split. If what you're really looking for is the whole string before the 1000th comma, you can still use this function but you will have to concatenate the first section of the array.
public static void main(String[] args){
String sample = "s,a,m,p,l,e";
String[] splitSample = sample.split(",",1000);
if (splitSample.length == 1000)
System.out.println(splitSample[1000]);
else
System.out.println("Your error string");
}

Categories

Resources