【问题标题】:String index out of range error 7 [duplicate]字符串索引超出范围错误 7 [重复]
【发布时间】:2012-09-04 23:22:45
【问题描述】:

可能重复:
String index out of range: 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 + "!");
  }
  }

提前致谢!

【问题讨论】:

标签: java string indexoutofboundsexception


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      • 2013-09-25
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多