繁体   English   中英

在这里构建我的代码的更好方法是什么?

[英]What is a better way to structure my code here?

我是一个新手,正在尝试编写一个应用程序,该应用程序在按下按钮后输入/输出 1-10 之间的数字。 当输入值超出 1-10 边界时,我希望这段代码抛出异常。

引起: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

 <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimaryDark" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> </android.support.v7.widget.Toolbar> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_row="1" android:layout_column="0" android:layout_columnSpan="0" android:text="Enter a Number Between 1 and 10:" android:textSize="30sp" /> <EditText android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_row="2" android:layout_column="0" android:ems="10" android:inputType="number" /> <Button android:id="@+id/button" android:layout_width="369dp" android:layout_height="wrap_content" android:layout_row="3" android:layout_column="0" android:layout_columnSpan="2" android:text="Button" android:onClick="onClick" android:textSize="30sp" /> <TextView android:id="@+id/output" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_row="4" android:layout_column="0" android:text="output" android:textSize="30sp" />

你必须把你的函数调用放到一个 try/catch 块中:

public void onClick(View view) {

try{
  rand(Integer.parseInt(editText.getText().toString()));
}catch(IndexOutOfBoundsException e){
  e.printStackTrace();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM