StringIndexOutOfBoundsException:字符串索引超出范围0

时间:2012-09-12 03:31:25

标签: java indexing

我正在尝试编写一个程序来获取用户输入的第一个字母以生成用户名。我正在尝试编写它,以便如果用户将输入留空,那么生成用户名的字母默认为字母'z'。

这是我的完整代码:

    import java.util.Scanner;
    /**
      UsernameGenerator.java
      Generates a username based on the users inputs.
      @author: Evan Fravert
      */
public class UsernameGenerator {
/**
  * Generates a username based on the users inputs.
  *@param args command line argument
  */
  public static void main(String[] args)
{ // abcde
  String first;
  String middle;
  String last;
  String password1;
  String password2;
  int randomNum;
  randomNum = (int) (Math.random() * 1000) + 100;
  Scanner userInput = new Scanner(System.in);
  System.out.println("Please enter your first name:");
  first = userInput.nextLine();
  String firstLower = first.toLowerCase();
  System.out.println("Please enter your middle name:");
  middle = userInput.nextLine();
  String middleLower = middle.toLowerCase();
  System.out.println("Please enter your last name:");
  last = userInput.nextLine();
  int lastEnd = last.length()-1;
  String lastLower = last.toLowerCase();
  System.out.println("Please enter your password:");
  password1 = userInput.nextLine();
  System.out.println("Please enter your password again:");
  password2 = userInput.nextLine();

  char firstLetter = firstLower.charAt(0);
  char middleLetter = middleLower.charAt(0);
  char lastLetter = lastLower.charAt(0);
  char lastLast = lastLower.charAt(lastEnd);

  if first.length() == 0) {
      firstLetter = 'z';
  }
  else {
  firstLetter = firstLower.charAt(0);
  }

  System.out.println("Your username is " + firstLetter + ""
  + middleLetter + "" + lastLetter + "" + "" + lastLast + "" + randomNum); 
  System.out.println("Your password is " + password1);
  System.out.println("Welcome " + first + " " + middle + " " + last + "!");
}
}

3 个答案:

答案 0 :(得分:2)

这不起作用:

char firstLetter = firstLower.charAt(0);
...

if (first.length() == 0) {
    firstLetter = 'z';
}

如果长度为0,则charAt(0)将在标题中抛出异常。你可以这样做:

char firstLetter = first.length() == 0 ? 'z' : firstLower.charAt(0);

答案 1 :(得分:1)

可能会抛出异常:

char firstLetter = firstLower.charAt(0);

您在检查前调用charAt(0) 以查看输入是否为空。尝试这样的事情:

char firstLetter = first.isEmpty() ? 'z' : firstLower.charAt(0);

请注意,first.isEmpty()first.length() == 0的等效表达式。

答案 2 :(得分:0)

你从这一行获得例外

char firstLetter = firstLower.charAt(0);

低于一个就足以得到第一个字母。所以只保留这个

char firstLetter;
if (first.length() == 0) {
      firstLetter = 'z';
  }
  else {
  firstLetter = firstLower.charAt(0);
  }

以同样的方式,你必须检查其他输入字符串值