2

I'm trying to parse an int from a dummy String for test reasons. The string will be:

String numOfStudents = "Number of Students: 5";

I want to parse this String, ensuring it contains the line 'Number of Students' as well as finding out the int value.

How can I achieve this? I need the int value to compare it to another int value.

Thanks

1

3 Answers 3

2
    final String NUM_OF_STUDENTS = "Number of Students: ";

    String numOfStudents = "Number of Students: 5";
    int lastIndex = numOfStudents.lastIndexOf(NUM_OF_STUDENTS);

    if (lastIndex != -1){
        String number = numOfStudents.substring((lastIndex + (NUM_OF_STUDENTS.length())) , numOfStudents.length());
        Integer yourResultNumber = Integer.parseInt(number);
        System.out.println(yourResultNumber);
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Your code throws exceptions if String does not contain "Number of Students"
After copying the fix from my answer and downvoting it.
Well, your code did had an exception, I would thank you if you consider vote up my answer.
1

Since Integer cannot parse String values it throws NumberFormatException because numbers are expected as input, I would suggest you as you have static type of Strings use like this:

String numOfStudents = "Number of Students: 5";
String[] p = numOfStudents.split(":");

Integer i= Integer.parseInt(p[1].trim());
System.out.println(i);

As, p[0] contain String (label) and p[1] contain its value. You can use it later if you want.

Comments

1
String numOfStudents = "Number of Students: 55546";
int lastIndex = numOfStudents.lastIndexOf(" ");
if(lastIndex > -1 && lastIndex+1 < numOfStudents.length()) {
String num = numOfStudents.substring(lastIndex+1);
System.out.println(Integer.parseInt(num));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.