Why does my code keep throwing a StringIndexOutOfBoundsException?

java.lang.stringindexoutofboundsexception: string index out of range: 4
stringindexoutofboundsexception substring
how to handle string index out of bound exception in java
string index out of bound exception in javatpoint
string index out of range java
string index out of bounds exception string index out of range
java.lang.stringindexoutofboundsexception: string index out of range: 0
how to fix stringindexoutofboundsexception

I have been trying to fix this for a while now and I just can't seem to get it. I'm trying to get the phone number from the user so I can display it but when I get all the users info the error occurs. Any help would be appreciated. Thank you.

Here is the code:

import java.util.Scanner;

public class Event 
{
    public static double pricePerGuestHigh = 35.00;
    public static double pricePerGuestLow = 32.00;
    public static final int LARGE_EVENT_MAX = 50;
    public String phone = "";
    public String eventNumber;
    private int guests;
    private double pricePerEvent;

    public void setPhone()
    {
        Scanner input = new Scanner(System.in);
        int count = 0;

        System.out.println("Enter your phone number: ");
        String phone = input.nextLine();
        int len = phone.length();
        for(int i=0; i<1; i++)
        {
            char c = phone.charAt(i);
            if(Character.isDigit(c))
            {
                count++;
                String ss = Character.toString(c);
                phone = phone.concat(ss);
            }
        }
        if(count != 10)
        {
            phone = "0000000000";
        }
    }

    public String getPhone()
    {
        // The error occurs in this method
        String ret = "(" + this.phone.charAt(0) + "" + this.phone.charAt(1)
        + "" + this.phone.charAt(2) + ")" + this.phone.charAt(3) 
        + "" + this.phone.charAt(4) + "" + this.phone.charAt(5)
        + "" + this.phone.charAt(6) + "" + this.phone.charAt(7)
        + "" + this.phone.charAt(8) + "" + this.phone.charAt(9);
        return ret;
    }

    public void setEventNumber()
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the event number: ");
        eventNumber = input.nextLine();
    }

    public void setGuests(int guests)
    {
        this.guests=guests;
        if(isLargeEvent())
            pricePerEvent = pricePerGuestHigh;
        else
            pricePerEvent = pricePerGuestLow;
    }

    public int getGuestsCount()
    {
        return guests;
    }

    public boolean isLargeEvent()
    {
        if(guests >= LARGE_EVENT_MAX)
        {
            return true;
        }
        else if(guests < LARGE_EVENT_MAX)
        {
            return false;
        }
        return isLargeEvent();
    }

    public String getEventNumber()
    {
        String ret1 = "Event Number: " + this.eventNumber;
        return ret1;
    }

    public int getGuests(boolean largeEvent)
    {
        return guests;
    }
}

The code where the error occurs has been marked with a comment.


The StringOutOfBoundsException is thrown whenever you're attempting to access a character in the string that doesn't exist at the given index.

From the code you've provided it seems as though you're accessing an empty string in the method getPhone().

You can fix this by first checking if the string is empty with phone.isEmpty().

public String getPhone() {

    if (phone == null || /*this.*/phone.isEmpty()) {
        // Handle the error accordingly.
        return null; // example
    }
    String ret = "(" + this.phone.charAt(0) + "" + this.phone.charAt(1)
    + "" + this.phone.charAt(2) + ")" + this.phone.charAt(3) 
    + "" + this.phone.charAt(4) + "" + this.phone.charAt(5)
    + "" + this.phone.charAt(6) + "" + this.phone.charAt(7)
    + "" + this.phone.charAt(8) + "" + this.phone.charAt(9);
    return ret;
}

While we're at it, I'd recommend not using string concatenation, as this will produce a large amount of overhead. Instead, use Java's string formatting.

This will not only increase the readability of your code, but it will (as mentioned before) reduce overhead, because strings in Java are immutable.

java.lang.StringIndexOutOfBoundsException, This exception is thrown by the methods of the String class, StringIndexOutOfBoundsException if any index is negative, or the endIndex is greater String str = "Java Code Geeks!" ; The comment form collects your name, email and content to allow us keep track of the comments placed on the website. StringIndexOutOfBoundsException. If you try to access the character of a String at the index which is greater than its length a StringIndexOutOfBoundsException is thrown. Example. The String class in Java provides various methods to manipulate Strings. You can find the character at a particular index using the charAt() method of this class.


The error means that you are trying to access the phone's character at an index that does not exists.

Precisely, your phone field is never set inside your code so it's an empty String.

Anyway, you should also fix the for loop by using the len variable:

int len = phone.length();
for(int i = 0; i < len; i++)
{
    ...
}

By doing that, you cannot concern about StringIndexOutOfBoundsException because now the for automatically traverse only the chars present in the String.

StringIndexOutOfBoundsException, Learn StringIndexOutOfBoundsException as part of the Java Exceptions Course public static void main(String[] args) { try { // StringIndexOutOfBoundsException will be thrown The code we examined above attempts to access the character at the Play around with the index number to stop the exception from occurring. asalamon74 posted the code I required, but I don't know why he deleted it. In any case here it is. There is a bug already filed in Java's bug database. (Thanks for this reference, asalamon.) yourString.replaceAll("\\\\", "\\\\"); Amazingly, both search and replace string are the same :) but still it does what I require.


To make your code work you should make new local var (for example inputPhone) and than change phone var of Event object. Also you should change condition in for loop.

public void setPhone()
{
    Scanner input = new Scanner(System.in);
    int count = 0;

    System.out.println("Enter your phone number: ");
    String inputPhone = input.nextLine();
    int len = inputPhone.length();
    for(int i=0; i<len; i++)
    {
        char c = inputPhone.charAt(i);
        if(Character.isDigit(c))
        {
            count++;
            String ss = Character.toString(c);
            phone = phone.concat(ss);
        }
    }
    if(count != 10)
    {
        phone = "0000000000";
    }
}

CSCI 2310: Exceptions and Throws Clauses, Throwing and catching exceptions Java has a collection of objects called exceptions, each indicating a reason why something went wrong. For example, one of the exceptions is called StringIndexOutOfBoundsException, indicating that an index used in charAt does not exist in a string. public class StringIndexOutOfBoundsException extends IndexOutOfBoundsException Thrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string.


How to handle the StringIndexOutOfBoundsException (unchecked , The StringIndexOutOfBoundsException is one of the unchecked can use try and catch block around the code snippet that can possibly throw� I'd imagine you have a trailing newline " " character at the end of your file, and your program is reading this line in and attempting to split it.


How to handle StringIndexOutOfBoundsException in Java?, StringIndexOutOfBoundsException. If you try to access the character of a String at the index which is greater than its length a StringIndexOutOfBoundsException is thrown. If you try to access the character of a String at the index which is greater than its length a StringIndexOutOfBoundsException is thrown.


java.lang.StringIndexOutOfBoundsException java code examples , @throws IndexOutOfBoundsException if {@code index} is negative or greater than or A special wrapper for a StringBuffer that keeps track of the * number of � The above code will generate the StringIndexOutOfBounds exception because there isn't 100 characters in string test. Jax Don't get me started about those stupid light bulbs .