我已经尝试修复了一段时间,但似乎还是无法解决。我正在尝试从用户那里获取电话号码,以便可以显示它,但是当我获得所有用户的信息时,就会发生错误。任何帮助,将不胜感激。谢谢。
这是代码:
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;
}
}
发生错误的代码已用注释标记。
每当您尝试访问给定索引中不存在的字符串中的字符时,都会引发StringOutOfBoundsException 。
根据您提供的代码,似乎您正在访问方法中的空字符串getPhone()。
您可以通过先检查字符串是否为空来解决此问题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;
}
在进行此操作时,建议不要使用字符串连接,因为这会产生大量开销。相反,请使用Java的字符串格式。
这不仅会提高代码的可读性,而且(如前所述)将减少开销,因为Java中的字符串是不可变的。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。