如何在Android中使用if else

丹尼

我正在尝试使用if else方法来初始化String数组..但它无法正常工作。怎么做 ?

if(itemno==2){
        String[] values = new String[] { "Category31", 
                "Category32",
                "Category33",
                "Category34", 
                "Category35", 
                "Category36", 
                "Category37", 
                "Android Example List View" ,
                "daniel",
                "dude",
                "hello",
                "super,","dukker"

               };}

else if(itemno==3){
        String[] values = new String[] { "Category31", 
                "Category32",
                "Category33",
                "Category34", 
                "Category35", 
                "Category36", 
                "Category37", 
                "Android Example List View" ,
                "daniel",
                "dude",
                "hello",
                "super,","dukker"

               };}


    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, values);
    l.setAdapter(adapter); 

但在适配器显示错误,表明变量不被接受..帮帮我

lucian.pantelimon

您要valuesif的块中声明变量在您的情况下,变量的范围是从if的开始到结束。

if(something)
{
   //start of if scope

   String[] values = {"one"};

   //values available here with contents: {"one"}
   //end of if scope
}
else
{
   //start of else scope

   String[] values;

   //values available here - different from the values above. this variable value is null here
   //end of else scope
}
//none of the values declared above are available here. From the compiler's PoW, no values variable has been declared here.

解决方案是将values声明移到ifelse范围之外:放在String[] values;之前if,然后String[]ifelse块中删除声明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章