-2

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.

user2342558
  • 5,567
  • 5
  • 33
  • 54
Hoeins
  • 49
  • 4
  • Can you give more details of what ur input is? Also attach a full functioning code with the main class, so that we can run and debug? – Echo Nov 29 '19 at 09:02
  • 4
    Your `public String phone = "";` never gets altered and thus is always 0 length. Yet you try to access characters which are out of the bounds. https://www.tutorialspoint.com/What-are-class-variables-instance-variables-and-local-variables-in-Java – XtremeBaumer Nov 29 '19 at 09:03
  • Maybe time to learn how to use the debugger or to add simple print statements to your code to help you figure out what is going on – Joakim Danielson Nov 29 '19 at 09:06
  • Also having `i<1` in the for loop of `setPhone` is likely a bug. I would guess it should be `10` (or `len`) instead. – second Nov 29 '19 at 09:07
  • And the handling of System.in and Scanner is another issue – Joakim Danielson Nov 29 '19 at 09:09
  • Does this answer your question? [What is IndexOutOfBoundsException? How can I fix it?](https://stackoverflow.com/questions/40006317/what-is-indexoutofboundsexception-how-can-i-fix-it) – default locale Nov 29 '19 at 09:12

3 Answers3

3

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.

user2342558
  • 5,567
  • 5
  • 33
  • 54
2

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.

SimonC
  • 1,547
  • 1
  • 19
  • 43
  • Thank you. Sorry I'm still kinda learning while I'm doing this stuff and when I get stuck I have no clue how to fix it. It seems like i bothered a lot of people with this question but I mean did y'all understand all of this after only doing it for 3 semesters in college? – Hoeins Nov 29 '19 at 09:19
  • "The StringOutOfBoundsException is thrown whenever you're attempting to access a character in the string that doesn't exist" may be changed to "The StringOutOfBoundsException is thrown whenever you're attempting to access a character in the string that doesn't exist **at the specified index**" – user2342558 Nov 29 '19 at 09:34
  • @Hoeins That's just SO. Someone's always bound to be upset with the way a question is asked or an answer is written, it's just the way things are. I would argue that this has nothing to do with the time you've been at college. If you ask me, people interested in developing software will also do so in their free time and will continue to be interested in the topic. Personally, I never studied; I'm self-taught (which is sadly evident from my initial questions here). – SimonC Nov 29 '19 at 09:40
0

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";
    }
}