繁体   English   中英

如何获得try / catch语句的正确输出?

[英]How do I get the correct output for the try/catch statement?

我想通过输入列表位置的数字在列表中添加一个新项目。 当我为应用程序运行此代码时,即使不输入数字,也只会执行catch语句。 我如何执行try语句? 这是我键入的代码(请手动删除将代码手动添加到列表l1的代码行,除非必须进行更改以解决我的问题):

public void m(View view) {
    //Define reference for the list
    List<Integer> l1;

    int x;
    int y;
    int z; //For storing removed item 
    EditText input;
    TextView tv;
    int pos; //For position of the list that user input

    input = (EditText) findViewById(R.id.user_input);
    tv = (TextView) findViewById(R.id.text_answer);

    pos = input.getInputType();

    //Create the list 
    l1 = new ArrayList<Integer>();

    //Add items to the list l1
    l1.add(0, 20);
    l1.add(1, 52);

    //Display the size 
    tv.setText("List's size is " + l1.size() + "\n");

    //Retrieve an item
    x = l1.get(0);

    //Display the retrieved item
    tv.append("Retrieved value is " + x + "\n"); 

    //Add more items to the list, but change its position
    l1.add(0, 61);
    l1.add(1, 17);
    l1.add(2, 6);

    //Show the updated size
    tv.append("After adding more items, List's size is " + l1.size() + "\n");

    //Retrieve an item at position (or index) 2
    y = l1.get(2);

    //Display the new retrieved item
    tv.append("The second retrieved item is " + y + "\n");

    //Remove an item at position 3
    z = l1.get(3);
    tv.append("Next, I will remove the item at position 3, which is " + z + "\n");
    l1.remove(3);

    //Display the final size
    tv.append("After removing one item from the list, List's size is " + l1.size() + "\n");

    //Use the toast message
    try {
        l1.add(pos, 777);
        Toast.makeText(MainActivity.this, "Added item to the list", Toast.LENGTH_SHORT).show();
    } catch(IndexOutOfBoundsException e) {
        Toast.makeText(MainActivity.this, "Could not add item to thie list. Bad index:" + 
                        pos, Toast.LENGTH_SHORT).show();
    }
} 

您将pos读为;

pos = input.getInputType();

这可能始终导致IndexOutOfBoundsException 相反,您可能想将EditText内容转换为此代码行附近的int;

pos = Integer.parseInt(input.getText().toString());

另外,添加一些完整性检查以避免整数解析异常。

暂无
暂无

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

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