有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将三个单词组合成一个单词?

我必须做一个程序,需要生成三个10个字母的单词,每个单词的第一个字母为大写字母。之后,我必须把这三个单词组合成一个单词,而且这个单词应该只有第一个字母作为大写字母

到目前为止,我做到了:

public static void main(String[] args) {
    new DZ05();
}

public DZ05() {
    Random word = new Random();
     for(int i = 0; i<= 10; i++) {
        int x = word.nextInt(25)+97;
        if(i==0) {
            tekst1+= Character.toUpperCase((char) (x));
        } else {
        tekst1+= (char) (x);
        }
    }       
         for(int i = 0; i<= 10; i++) {
        int x = word.nextInt(25)+97;
        if(i==0) {
            tekst2+= Character.toUpperCase((char) (x));
        } else {
        tekst2+= (char) (x);
        }
    }
             for(int i = 0; i<= 10; i++) {
        int x = word.nextInt(25)+97;
        if(i==0) {
            tekst3+= Character.toUpperCase((char) (x));
        } else {
        tekst3+= (char) (x);
        }
    }      
    System.out.println(tekst1);
    System.out.println(tekst2);
    System.out.println(tekst3);

这就是我不知道还能做什么的地方


共 (2) 个答案

  1. # 1 楼答案

    我将假设tekst1、tekst2和tekst3是字符串,因为在提供的代码中没有显示

    首先,for循环生成的单词不是10个字母,而是11个字母。应该是:

    for (int i = 0; i < 10; i++)
    

    现在,可以使用String类中的各种方法来实现目标。您可以使用String concatenation组合以下单词:

    String combinedWords = tekst1 + tekst2 + tekst3;
    

    使用字符串方法toLowerCasesubstring获取除第一个小写字母外的所有字母:

    String lowerCaseChars = combinedWords.toLowerCase().substring(1);
    

    使用字符串方法charAt获取第一个字母:

    char upperChar = combinedWords.charAt(0);
    

    最后,将upperCharlowerCaseChars结合起来,可以得到您想要的结果:

    String result = upperChar + lowerCaseChars
    
  2. # 2 楼答案

    <>你应该考虑把问题分解成多种方法,让你的主程序调用这些方法。

    例如,您可以构建如下内容:

    private String randomWord(int length) { ... }
    private String titleCase(String word) { ... }
    

    你的主程序可以调用它们,并且更容易遵循:

    String fiveLetterWord = randomWord(5);
    String titleCasedWord = titleCase("threeConcatenatedWords");