gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:54:09 25 4
gpt4 key购买 nike

我想通过输入列表位置的数字来在列表中添加新项目。当我为应用程序运行此代码时,即使没有输入数字,也只会执行 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());

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

关于java - 如何获得 try/catch 语句的正确输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28564636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com