2013-02-23 73 views
0

我需要從用戶處獲取一些單詞,然後輸出一個由單詞最後一個字母連接而成的最終單詞用戶有輸入。通過連接Java中給定字符串集的最後一個字母來創建一個新字符串

這是代碼。但是,我如何從循環中提取這些字母並連接它們?

import java.util.Scanner; 
public class newWord { 
    public static void main(String args[]) { 

     System.out.println("How many words are you going to enter?"); 
     Scanner num = new Scanner(System.in); 
     int number = num.nextInt(); 
     System.out.println("Please Enter the "+number+" words:"); 
     for(int n=1;n<=number;n++) 
     { 

      Scanner words = new Scanner(System.in); 
      String thisword = words.nextLine(); 

      char str2 = thisword.charAt(thisword.length()-1); 
      System.out.println(str2); 
     } 

    } 
} 
+0

謝謝大家對你的幫助。提示或代碼,我正在學習:) – Sabharish 2013-02-23 07:38:56

回答

4

僅提示 ...因爲這顯然是某種學習練習。

但是,我該如何從循環中將這些字母連接起來並將它們連接起來呢?

你不知道。你在循環內連接它們

字符串串聯可以使用字符串+運算符或StringBuilder完成。

剩下的就是給你。 (請忽略那些發佈完整解決方案並自行解決的dingbats,它會幫你做好的!)

1

您可以使用StringBuilderappend方法來連接最新的字符的字符串。

1

我相信(如果我錯了,請糾正我)你要求拿出每個單詞的最後一個字母,把它變成最後一個單詞。所有你需要做的是把每個最後的字母,並將它們添加到一個字符串來保存它們。在整個for循環之後,變量appended應該是您要求的單詞。

public static void main(String args[]) { 

    System.out.println("How many words are you going to enter?"); 
    Scanner num = new Scanner(System.in); 
    int number = num.nextInt(); 
    System.out.println("Please Enter the "+number+" words:"); 
    String appended = ""; // Added this 
    for(int n=1;n<=number;n++) 
    { 

     Scanner words = new Scanner(System.in); 
     String thisword = words.nextLine(); 

     char str2 = thisword.charAt(thisword.length()-1); 
     appended +=str2; // Added this 
     System.out.println(str2); 
    } 

} 
+1

偉大的工作(不!)...現在他不需要做他的功課。 – 2013-02-23 07:25:45

1

只要你錯過的東西,以保持在一個地方終值,最後打印

public static void main(String args[]) { 

      System.out.println("How many words are you going to enter?"); 
      Scanner num = new Scanner(System.in); 
      int number = num.nextInt(); 
      System.out.println("Please Enter the "+number+" words:"); 
      StringBuffer sb = new StringBuffer(); 
      for(int n=1;n<=number;n++) 
      { 

       Scanner words = new Scanner(System.in); 
       String thisword = words.nextLine(); 

       char str2 = thisword.charAt(thisword.length()-1); 
       sb.append(str2); 

      } 
      System.out.println(sb.toString()); 

     } 
+1

偉大的工作(不!)...現在他不需要做他的功課。 – 2013-02-23 07:26:08

+0

@StephenC無論如何感謝!!!!!!!! – sunleo 2013-02-23 07:27:42

相關問題