字符串索引超出范围错误7

时间:2012-09-12 00:25:42

标签: java string indexoutofboundsexception

  

可能重复:
  String index out of range: n

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

线程“main”中的异常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 + "!");
  }
  }

提前致谢!

2 个答案:

答案 0 :(得分:4)

Java数组基于零,最后一个索引是last.length() - 1

答案 1 :(得分:1)

试试这个:

char lastLast = lastLower.charAt(lastEnd-1);