如何使用扫描仪与令牌做不同的事情

时间:2017-03-29 11:14:06

标签: java while-loop java.util.scanner

    String line = JOptionPane.showInputDialog("Enter a full name and surname").toUpperCase();

    Scanner l = new Scanner (line);
    int index = line.lastIndexOf(" ");

    while (l.hasNext())
    {
        String name = l.next();
        char ch = name.charAt(0);
        System.out.print(ch);
    }
    System.out.print(" " + line.substring(index + 1));

示例:

用户输入以下内容 - Fred John Samuel Smith

输出应为 - FJS SMITH

代码不起作用,因为输出是这样的:

FJSS SMITH

如何从最后一个单词中拆分前3个单词?

2 个答案:

答案 0 :(得分:1)

这可能是您问题的解决方案。

String line = JOptionPane.showInputDialog("Enter a full name and surname").toUpperCase();

    String l[] = line.split(" ");
    int index =0;
while(index<4)
{
if(index<3)
 System.out.print(l[index].charAt(0));
else
  System.out.print(" "+l[3]);

index++;
}

答案 1 :(得分:0)

尝试我的方法我在评论中提供了详细信息

public static void main(String args[])
            {
                //get the first Three Letter acronym and the last name
                StringBuilder sb = new StringBuilder("");
                String line = JOptionPane.showInputDialog("Enter a full name and surname").toUpperCase();
                sb.append(line.charAt(0));
                int spaces=0;
                //get the actual spaces
                for(int i=0;i<line.length();++i)
                {
                    if(line.charAt(i)==' ')
                        ++spaces;
                }

                for(int i=1;i<line.length();++i)
                {
                    //compare each character of inputted String to space
                    if(line.charAt(i)==' '&&spaces>1)
                    {
                        sb.append(line.charAt(i+1));
                        --spaces;
                    }
                    //if space is now equal to one 
                    else if(line.charAt(i)==' '&&spaces==1)
                    {
                        //it will consume all the remaining letter using this loop including the space character
                        while(i<line.length())
                        {
                            sb.append(line.charAt(i));
                            ++i;
                        }
                    }



                }
                //print test of StringBuilder sb
                System.out.println(sb.toString());


            }