简体   繁体   English

在程序中使用 charAt

[英]using charAt in a program

What I am trying to do is very elementary.我正在尝试做的是非常基本的。 The user should enter a name and the program prints only the initials of the name except for the last word.用户应输入姓名,程序仅打印姓名的首字母,最后一个单词除外。

Eg:例如:

input - "Mansha Mannan UL Haque"
output - "M.M.U.Haque"

The program is as follows but it does not compile.程序如下,但不能编译。

class joke
{
    public static void main(String str)
    {
        String alter=" "+str;
        int n=alter.length();
        for(int i=0;i<=n;i++)
        {
            char f=alter.charAt(i);
            if (f.compareTo(" ")>0)
            {
                System.out.println(alter.charAt(i+1));
            }
        }
    }
}

The error showed is char cannot be dereferenced.显示的错误是 char 不能取消引用。

Split your input string into string array then access each word and print its first char, for last word print it whole.将您的输入字符串拆分为字符串数组,然后访问每个单词并打印其第一个字符,最后一个单词将其全部打印出来。

class joke
{
public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    String alter=sc.nextLine(); //take input from user
    String arr[] = alter.split(" ");
    int n=arr.length(); //total words in user string
    for(int i=0;i<n;i++)
    {

        if(i==n-1){   //if last word
             System.out.print(arr[i]);
        }
        else{
             System.out.print(arr[i].charAt(0)+". ");
        }
    }
}

} }

This should do the trick这应该可以解决问题

in this case name would be your input在这种情况下, name将是您的输入

  String name = "Mansha Mannan UL Haque";
    String[] nameArray = name.split(" ");
    String newName = "";
    for(int i = 0; i < nameArray.length; i++)
    {
        if(i != nameArray.length -1)
        {
            newName += nameArray[i].substring(0, 1) + ".";
        }
        else
        {
            newName += nameArray[i];
        }
    }

and you should also make your class joke public and change String str to String[] args并且您还应该公开您的课堂joke并将String str更改为String[] args

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM