2012-09-12 112 views
0

我正在嘗試編寫一個程序,將用戶輸入的第一個字母生成用戶名。我試圖編寫它,以便如果用戶將輸入留空,那麼否則將用於生成用戶名的字母默認爲字母'z'。StringIndexOutOfBoundsException:字符串索引超出範圍0

這裏是我的全碼:

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

請包括堆棧跟蹤。如果你很容易幫助你,人們會。 – Aidanc

回答

1

異常很可能是被扔在這裏:

char firstLetter = firstLower.charAt(0); 

要調用charAt(0)檢查,看看如果輸入是空的之前。嘗試這樣的事情,而不是:

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

注意first.isEmpty()是等價表達first.length() == 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); 
+0

好得多。謝謝! –

0

ü從該行

char firstLetter = firstLower.charAt(0); 

下面一個足以讓第一個字母得到例外。因此,保持這隻

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

以同樣的方式u必須檢查其他輸入字符串值

相關問題