Android 2D阵列

时间:2013-03-10 00:35:19

标签: android

我正在尝试根据RadioButtons显示数组的内容。我用了2套按钮。该按钮应指向我的数组中的[x, y]。应显示数组的String值(使用Toast)。

是的,我是新手,但我试图挑选几个类似的例子,运气不佳。

public class MainActivity extends Activity {
    String[][] tipSize = {
            {"N/A","N/A","Pink","Lt Blue","Purple","Yellow","Brown","Orange","Tan","Blue","White","Beige"},
            {"N/A","Pink","Lt Blue","Purple","Yellow","Brown","Orange","Green","Tan","Blue","White","Beige"},
            {"N/A","N/A","Pink","Purple","Turquoise","Yellow","Green","Tan","Blue","White","Red","No Tip"},
            {"Pink","Lt Blue","Purple","Yellow","Orange","Green","Tan","Blue","Red","Beige","Gray","N/A"},
            {"Pink","Lt Plue","Purple","Orange","Green","Tan","Blue","White","Beige","Black","Gray","N/A"},
            {"Pink","Lt Blue","Yellow","Brown","Orange","Green","Tan","Blue","White","Beige","Black","N/A"},
            {"Pink","Lt Blue","Yellow","Brown","Tan","Blue","White","Red","Beige","Black","No Tip","N/A"},
            {"Pink","Lt Blue","Purple","Yellow","Orange","Green","Tan","Blue","Red","Beige","Gray","N/A"},
    };

private RadioGroup dispenser,ounce_pg;
private RadioButton disp,o_pg;
String tip = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button finishBtn = (Button) findViewById(R.id.button1);
    finishBtn.setOnClickListener (new View.OnClickListener() {      
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            MainActivity.this.showit(); 
        }
    });     
}

protected void showit() {
    // TODO Auto-generated method stub
    disp = (RadioButton) findViewById(R.id.dispenser);
    o_pg = (RadioButton) findViewById(R.id.ounce_pg);
    tip = String tipSize [disp,o_pg];
    // tip is the displayed answer (Color of tip), tipSize[][] is the Array, disp is RadioButton 1 - o_pg is Radio Button 2 values. 

    Toast.makeText(MainActivity(),tip,Toast.LENGTH_LONG).show();
}

}

2 个答案:

答案 0 :(得分:0)

这一行有很多问题:

 tip = String tipSize [disp,o_pg];
  1. [disp,o_pg]应为[disp][o_pg],因为访问2D数组是通过array [x][y]

  2. 完成的
  3. String tipSize没有意义,你不能在这里声明一个类型。如果你做了(String)它就会成为一个演员,那就没问题了(但是因为你有一个String数组,所以这是多余的 - 从String投射到String }没有做任何事情。)

  4. dispo_pg应为int

  5. 这是因为在访问索引时,您无法将Object传递给数组,该数组将不会“搜索”您。这意味着您需要确定要访问的位置并将其传递出去。另请注意,索引从0开始,而不是1

    可编辑的例子是:

    tip = tipSize [0][0]; //first element of the first array ("N/A")
    

答案 1 :(得分:0)

快速而肮脏的方法是创建一个包含分隔字符串的简单字符串数组,该字符串将第二个值组合在一起,然后使用split函数,该函数本身返回一个字符串数组以获取各个值。

String [] allTips = {"a;b;c", "d;e;f"};
String [] sometips = alltips[1].split(";")
String tip = sometips[2];

会产生字母f