StringIndexOutOfBoundsException: String index out of range 0

Posted by Evan F on Stack Overflow See other posts from Stack Overflow or by Evan F
Published on 2012-09-12T03:31:25Z Indexed on 2012/09/12 3:38 UTC
Read the original article Hit count: 160

Filed under:
|

I'm trying to write a program to take the first letter of the user input to generate a username. I'm trying to write it so that if the user leaves the input blank, then the letter that would otherwise be taken to generate the username defaults to the letter 'z'.

Here is my full code:

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

© Stack Overflow or respective owner

Related posts about java

Related posts about index