2017-03-29 27 views
0
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)); 

例子:如何使用掃描儀做不同的事情與令牌

用戶輸入以下弗雷德 - 約翰·塞繆爾·史密斯

輸出應該是 - FJS SMITH

的代碼沒有按't不工作,因爲輸出是這樣的:

FJSS SMITH

如何分割最後一個單詞的前三個單詞?

+0

注意:掃描儀不需要用於此目的。檢查[String#split](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-)方法。用空格拆分字符串,使用'for'來循環結果數組,並使用索引來檢查是否到達最後一個單詞。 – BackSlash

+0

而關於你的問題:可能重複[如何大寫字符串中每個單詞的第一個字符](http://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-每個字-IN-A-字符串) – BackSlash

回答

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()); 


      } 
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++; 
}