2015-02-09 81 views
1

所以我正在寫一個程序,我要求用戶輸入數組的大小並填寫名稱。之後,我要求用戶鍵入數字,程序將搜索數組中有長度的名稱。但是我不斷收到一個不兼容的類型錯誤。字符串[]不能轉換爲字符串。字符串[]不能轉換爲字符串

package LAB4_1; 

import java.util.Arrays; 
import java.util.Scanner; 

public class LAB4_1 

{ 

public static void main(String[] args) 
{ 
    Scanner sc = new Scanner(System.in); 
    String names []; 
    int length_typed; 
    String names_printed; 

    // Read the number of kids 
    System.out.print("How many kids are there? "); 
    int size = sc.nextInt(); 

    // Read the names of the kids 
    String [] kids = new String [size]; 

    for (int k = 0; k < kids.length; k++) 
    { 
     System.out.print("Enter name of kid #" + k + ": "); 
     kids[k] = sc.next(); 
    } 
    // Print all the names of the kids and the length of their names 
    System.out.println("Names of kids with lengths are: "); 

    for (int i = 0; i < kids.length; i++) 
    { 
     System.out.println(kids[i] + " " + kids[i].length()); 
    } 

    // Prompt for sequence of name lengths: 
     System.out.print("Enter lengths of names as promted, 0 to terminate."); 

    // Read the lengths and print list of names till 0 is entered 
     length_typed = sc.nextInt(); 

該錯誤是這裏

 names_printed = LAB4_1.filterByLength(names, length_typed); 

字符串[]不能被轉換成字符串。我是不是正確調用方法?

 System.out.println(names_printed); 

} 

/** 
* Count the number of names in an array that have a certain length 
* @param names: An array of names 
* @param length : an integer length 
* @return the number of names in the array whose length is given 
*/ 

static int countByLength(String [] names, int length) 
{ 
int count = 0; 

for(int i = 0;i < names.length;i++) 
{ 
    if(names[i].length() == length) 
     count++; 
} 


return count; 
} 


/** 
* Filter an array of names and keep only those names with a given length 
* @param names: an array of names 
* @param length: an integer length 
* @return the array of names that have the given length 
*/ 
static String [] filterByLength(String [] names, int length) 
{ 
    String [] filtered = new String[countByLength(names, length)]; 
    int index = 0; 

    for(int k = 0; k < filtered.length; k++) 
    { 
     if(names[k].length() == length) filtered[index++]=names[k]; 
    } 

    return filtered; 
} 

}

+4

您正在嘗試將字符串數組分配給字符串變量。 – Zavior 2015-02-09 06:32:01

+1

我認爲錯誤信息是完全清楚的,您將'filter [']'從'filterByLength'方法返回給'String'變量 – 2015-02-09 06:33:51

回答

1

不,你沒有正確調用方法。您的方法filterByLength返回類型String[]。您正嘗試將該值放在String對象中,即names_printed

這是行不通的。請重新輸入names_printed作爲String[],並且您的代碼應該可以正常工作。但是,您將無法使用println並獲得可讀的輸出。你應該使用println(Arrays.toString(names_printed))