2013-02-23 74 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

相关问题