如何获得3个单词的第一个字母?

时间:2016-03-13 17:29:55

标签: java string

我要制作一个应用程序,将输入的单词的第一个字母输入到大写字母。我没有收到任何错误,我只是没有得到任何继续运行的东西。

package threeletteracronym;

import java.util.Scanner;

/**
 *
 * @author Matthew
 */
public class ThreeLetterAcronym {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {

        String s;

        Scanner keyboard = new Scanner(System.in);

        System.out.println("Please enter words.");
        s = keyboard.nextLine();       
        char a = keyboard.next().charAt(0);
        a = Character.toUpperCase(a);
        char b = keyboard.next().charAt(0);
        b = Character.toUpperCase(a);
        char c = keyboard.next().charAt(0);
        c = Character.toUpperCase(a);         

        System.out.println("Your new Acronym form " + s + " is " + a + b + c);       
    }

}

3 个答案:

答案 0 :(得分:1)

您正在阅读并放弃第一行输入。

如果你不想这样做,我建议你放弃这一行s = keyboard.nextLine();

如果您单步执行代码,这是调试器的帮助。

答案 1 :(得分:0)

您的代码无效,因为: 您需要删除keyboard.nextLine() AND 您复制/粘贴错误

b = Character.toUpperCase(a);并且必须

b = Character.toUpperCase(b);

实施例

System.out.println("Please enter words.");
// s = keyboard.nextLine();
char a = keyboard.next().charAt(0);
a = Character.toUpperCase(a);
char b = keyboard.next().charAt(0);
b = Character.toUpperCase(b); // uppercase of b and not a
char c = keyboard.next().charAt(0);
c = Character.toUpperCase(c); // uppercase of c and not a

答案 2 :(得分:0)

你可以这样做:

import java.util.Scanner;
public class test4 {
public static void main(String[] args) {
    @SuppressWarnings("resource")
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please enter words.");
    char a = keyboard.next().charAt(0);
    a = Character.toUpperCase(a);
    char b = keyboard.next().charAt(0);
    b = Character.toUpperCase(a);
    char c = keyboard.next().charAt(0);
    c = Character.toUpperCase(a);
    System.out.println("Your new Acronym form is:" + a + b + c);
}
}

还有其他方法可以将每个字符保存到数组中。然后,您可以显示该数组作为结果。 这是通过使用字符串缓冲区:

import java.util.Scanner;
public class test4 {
public static void main(String[] args) {
    @SuppressWarnings("resource")
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please enter words: ");
    char text;
    StringBuffer sBuffer = new StringBuffer(5);
    for(int i=0; i < 3; i++) {
        text = keyboard.next().charAt(0);
        text = Character.toUpperCase(text);
        sBuffer = sBuffer.append(text);
    }
    System.out.println("Your new Acronym form is: " + sBuffer);
}
}