java在这里构建代码的更好方法是什么?
我是一个新手,尝试编写一个应用程序,在按下按钮后输入/输出1-10之间的数字。我希望这段代码在输入值超出1-10边界时抛出一个异常
Caused by: java.lang.reflect.InvocationTargetException
我相信这与我将rand()函数放入onClick()监听器的方式有关。我写得很差,这是对的吗
如果你能帮忙,非常感谢
这是我的密码:
public Button button; public TextView textView; public EditText editText; Random r; public int max=0; public int min=0; public int temp=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button)findViewById(R.id.button); editText=(EditText)findViewById(R.id.editText); editText.setText(""); textView=(TextView) findViewById(R.id.output); } public void onClick(View view) { rand(Integer.parseInt(editText.getText().toString())); } public void rand(int temp) throws IndexOutOfBoundsException{ temp = Integer.parseInt(editText.getText().toString()); if(temp >10 || temp<0){ throw new IndexOutOfBoundsException("out of bounds... between 1-10"); } if(!editText.equals("")){ min = 10-temp; max = r.nextInt(min + 1)+1; } String set = String.valueOf(max); textView.setText(set); }
另外,这是我的XML
<安卓.support.v7.widget.Toolbar 安卓:id="@+id/toolbar" 安卓:layout_width="match_parent" 安卓:layout_height="?attr/actionBarSize" 安卓:background="?attr/colorPrimaryDark" 安卓:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> </安卓.support.v7.widget.Toolbar> <TextView 安卓:id="@+id/textView" 安卓:layout_width="wrap_content" 安卓:layout_height="wrap_content" 安卓:layout_row="1" 安卓:layout_column="0" 安卓:layout_columnSpan="0" 安卓:text="Enter a Number Between 1 and 10:" 安卓:textSize="30sp" /> <EditText 安卓:id="@+id/editText" 安卓:layout_width="wrap_content" 安卓:layout_height="wrap_content" 安卓:layout_row="2" 安卓:layout_column="0" 安卓:ems="10" 安卓:inputType="number" /> <Button 安卓:id="@+id/button" 安卓:layout_width="369dp" 安卓:layout_height="wrap_content" 安卓:layout_row="3" 安卓:layout_column="0" 安卓:layout_columnSpan="2" 安卓:text="Button" 安卓:onClick="onClick" 安卓:textSize="30sp" /> <TextView 安卓:id="@+id/output" 安卓:layout_width="wrap_content" 安卓:layout_height="wrap_content" 安卓:layout_row="4" 安卓:layout_column="0" 安卓:text="output" 安卓:textSize="30sp" />
# 1 楼答案
您必须将函数调用放入try/catch块: