java - Java: Loop thought the list, then check the results with if else
问题描述
I have situation where I have Arraylist, which has name items in it. I need to loop through that namelist which check if the new name that user gave, is already on a list or not. If it is, just give toast to notify user that name is already there, or if it isn't, then add name to the list.
This is what I have:
public class ActivityPlayers extends AppCompatActivity {
public static ArrayList<NameItem> mNameList;
private Button buttonAdd;
private EditText textAdd;
private int checkNumber;
/** When "add" button been clicked... **/
textAdd = findViewById(R.id.name_input);
buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/** Loop the list **/
for (int i = 0; i < mNameList.size(); i++) {
/** Check if user input match to any name in list
and if it does...**/
if (mNameList.get(i).getText1().equals(textAdd.toString().trim())) {
checkNumber = 1;
break;
} else {
/** If it doesn't **/
checkNumber = 0;
}
}
/** if checkNumber is still 0 **/
if (checkNumber == 0) {
/** Close soft keyboard **/
InputMethodManager input = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
input.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
/** ...add a name to the namelist **/
addItem(0);
} else {
/** if name in a list == name from input, give toast **/
Toast toast = Toast.makeText(getApplicationContext(),
"Name is already on a list", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
});
Any ideas why this won't work? It only adds the names to the list, even tho it already exists... but it never detects duplicates...
解决方案
if (mNameList.get(i).getText1().equals(textAdd.toString().trim()))
在上面的代码行中,您将第i个列表元素与 EditText 本身的字符串表示形式进行比较,而不是与其 Text 字段进行比较。而不是textAdd.toString()
,您应该使用textAdd.getText()
.
与问题无关,但我建议使用boolean
变量来表示代码中的逻辑标志,而不是整数计数。
在上面的例子中,它会是这样的:
private boolean nameInList = false;
//...
if (...) {
nameInList = true;
break;
}
//...
if (nameInList) {
//...
} else {
//...
}
推荐阅读
- c# - .NET - 使用方法作为另一个方法的参数
- pandas - 根据索引级别为多索引数据框分配值
- typoscript - Typo3 CMS 8.7 - 如何同时使用流体和网格元素?
- node.js - 如何从 API Nodejs + Expressjs 提交 html 表单
- spring-cloud-skipper - 将包上传到船长时出现“没有可用于'null'的发布管理器”春季云船长错误
- google-cloud-platform - GCP Cloud Run:创建服务失败
- sql - 使用多个条件格式化数据透视数据
- java - 如何将 VarChar 转换为整数?
- python - 我们如何使用 Selenium Python 以其他用户身份打开 Google chrome?
- visual-studio-code - 在 VSCode 上安装 Prettier