gpt4 book ai didi

java - 字符串索引越界异常 : String index out of range 0

转载 作者:行者123 更新时间:2023-12-02 00:12:46 25 4
gpt4 key购买 nike

我正在尝试编写一个程序来获取用户输入的第一个字母来生成用户名。我试图编写它,以便如果用户将输入留空,则用于生成用户名的字母默认为字母“z”。

这是我的完整代码:

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

最佳答案

这行不通:

char firstLetter = firstLower.charAt(0);
...

if (first.length() == 0) {
firstLetter = 'z';
}

如果长度为0,则charAt(0)将在标题中抛出异常。你可以这样做:

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

关于java - 字符串索引越界异常 : String index out of range 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12380837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com