0

可能重复:
字符串索引超出范围:n

我正在编写一个程序来根据用户的输入(名字、中间名和姓氏)生成用户名。我应该从每个名字(名字、中间和姓氏)中获取第一个字符以及姓氏的最后一个字符,以便生成用户名。我已经成功编写了程序来生成每个名字的第一个字符,但是当我试图让我的程序生成姓氏的最后一个字符时,我会收到这个错误:

线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:7

at java.lang.String.charAt(String.java:658)
at UsernameGenerator.main(UsernameGenerator.java:39)

这是我的代码:

    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();
  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 == null || 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 + "!");
  }
  }

提前致谢!

4

2 回答 2

6

Java 数组从零开始,最后一个索引是 last.length() - 1

于 2012-09-12T00:27:36.810 回答
1

尝试这个:

char lastLast = lastLower.charAt(lastEnd-1);
于 2012-09-12T00:29:44.720 回答