简体   繁体   English

为什么我的代码不断抛出 StringIndexOutOfBoundsException?

[英]Why does my code keep throwing a 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 error means that you are trying to access the phone 's character at an index that does not exists .该错误意味着您正试图在不存在的索引处访问phone的字符。

Precisely, your phone field is never set inside your code so it's an empty String.准确地说,您的phone字段从未设置在您的代码中,因此它是一个空字符串。

Anyway, you should also fix the for loop by using the len variable:无论如何,您还应该使用len变量来修复for循环:

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因为现在for仅自动遍历String存在的字符。

The StringOutOfBoundsException is thrown whenever you're attempting to access a character in the string that doesn't exist at the given index .每当您尝试访问给定索引处不存在的字符串中的字符时,就会抛出 StringOutOfBoundsException 。

From the code you've provided it seems as though you're accessing an empty string in the method getPhone() .从您提供的代码看来,您似乎正在访问getPhone()方法中的空字符串。

You can fix this by first checking if the string is empty with phone.isEmpty() .您可以通过首先使用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 .相反,使用 Java 的字符串格式

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 中的字符串是不可变的

To make your code work you should make new local var (for example inputPhone ) and than change phone var of Event object.为了使您的代码工作,您应该创建新的本地inputPhone (例如inputPhone ),而不是更改 Event 对象的phone inputPhone Also you should change condition in for loop.您也应该在 for 循环中更改条件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM