我有两节课。
在第一堂课中,需要整数low
和high
。
在第二节课中,我想宣布并更改low
和high
。
public class DisplayMessageActivity extends ActionBarActivity {
int low = 0;
int high = 101;
这很好 - 但是在以下函数运行之后,整数没有改变。
public int close (View v) {
EditText low2 = (EditText) findViewById(R.id.editText2);
EditText high2 = (EditText) findViewById(R.id.editText3);
int low = Integer.parseInt(low2.getText().toString());
int high = Integer.parseInt(high2.getText().toString());
high ++;
Toast.makeText(getApplicationContext(), "Low: " + low +" High: "+high, Toast.LENGTH_SHORT).show();
if (low > high) { //you can ignore it
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("False Numbers");
builder.setMessage("You set the lower number higher than the higher one.");
builder.show();
} else {
this.finish();
}
return low; //I want to return low AND high - but this command will not change low or high!
}
编辑代码:
public class HighAndLow{
int high= 0;
int low = 101;
}
public int[] close(View v){
EditText low2 = (EditText) findViewById(R.id.editText2);
EditText high2 = (EditText) findViewById(R.id.editText3);
low = Integer.parseInt(low2.getText().toString()); //cant find low now
high = Integer.parseInt(high2.getText().toString()); //cant find high now
high ++;
Toast.makeText(getApplicationContext(), "Low: " + low +" High: "+high,
Toast.LENGTH_SHORT).show();
if (low > high) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("False Numbers");
builder.setMessage("You set the lower number higher than the higher one.");
builder.show();
}
else{
this.finish();
}
return HighAndLow; //DONT WORK
}
答案 0 :(得分:2)
在Java(和Android)中,您无法从函数返回多个值。您只能返回单个值。但是,该单个值可以是包含多个字段的对象。
您可以考虑创建一个包含两个值的新类。像这样:
public class HighAndLow{
int high;
int low;
}
然后你可以从你的方法返回这个类的实例,调用代码可以通过那种方式访问高值和低值。
事实上,Android已经有一个类来执行此操作:Range
答案 1 :(得分:1)
为什么不将高低整数创建为类的属性?然后实现你通常的getter / setter。通过close方法设置它们,并在需要时从第一个实例化的类中获取它们。
答案 2 :(得分:-1)
这不是推荐和面向对象的方式,但如果以前的答案不满足,你可以这样做:
public int[] close (View v) {
EditText low2 = (EditText) findViewById(R.id.editText2);
EditText high2 = (EditText) findViewById(R.id.editText3);
int low = Integer.parseInt(low2.getText().toString());
int high = Integer.parseInt(high2.getText().toString());
high ++;
Toast.makeText(getApplicationContext(), "Low: " + low +" High: "+high, Toast.LENGTH_SHORT).show();
if (low > high) { //you can ignore it
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("False Numbers");
builder.setMessage("You set the lower number higher than the higher one.");
builder.show();
} else {
this.finish();
}
int[] values = {high,low};
return values; //I want to return low AND high - but this command will not change low or high!
}
之后
int[] myHighAndLow = close(someView);
//you need to remember what came first(First In First Out)
int high = myHighAndLow[0];
int low = myHighAndLow[1];