将java数组元素转换成句子

时间:2015-11-30 00:07:08

标签: java arrays

我需要获取我的数组中的元素,并使用它来制作这样的输出消息“你的句子是(这是元素将去的地方)”。但我知道如何做的唯一方法是使用for循环。

private void sentanceArray() {
        int size = 0;
        String word = "";
        int i = 0;


        Scanner input = new Scanner(System.in);

        System.out.println("How many words would you like to enter?");

        size = input.nextInt();

         String [] sentance = new String[size];

        System.out.println("Please enter a word.");

        word = input.next();

        while( i < size){
           if( i < size){
                sentance[i] = word;
                i++;
                System.out.println("Please enter another word.");

                word = input.next();

           }//end of if 
        }//end of while

        displayArray(sentance);
    } // end of sentanceArray


    public static void displayArray(String []sentance){

        for(int i = 0; i < sentance.length; i++){               
            System.out.print( "Your sentance is " + sentance[i] +"\t" );
        }

    }//end of displayResults

我的问题是它显示“你的遗产是”,然后一次只显示一个元素

1 个答案:

答案 0 :(得分:0)

请改为尝试:

System.out.print("Your sentence is ");
for(String x : sentance)
    System.out.print(x + "\t");

此外,

   while( i < size){
       if( i < size){ // You dont need this condition, while loop checks for that