英文:
How do I use the if else statement to check if the user has inputted a valid entry in relation to array list index?
问题
public static void Modify() {
readelements();
System.out.println("Enter the desired # of the entry you would like to modify");
int Mod = Cons.nextInt();
if (Mod != Notes.size()) {
System.out.println("You've selected an invalid entry!\n");
} else {
System.out.println(Notes.get(Mod));
Notes.remove(Mod);
System.out.println("Please copy and paste your entry for re-entry");
String NewMod = Cons.next();
Notes.add(Mod, NewMod);
}
Execute.Instruct();
}
英文:
Im trying to create a modify method that allows the user to see their entry that was previously inputted and be able to re input that entry thus replacing the entry. However, when I try to code the if else statement that checks if their input is a valid index the program claims that no matter what you input its incorrect. please advise.
public static void Modify()
{
readelements();
System.out.println("Enter the desired # of the entry you would like to modify");
int Mod = Cons.nextInt();
if (Mod != Notes.size())
{
System.out.println("You've selected an invalid entry!\n");
}
else {
System.out.println(Notes.get(Mod));
Notes.remove(Mod);
System.out.println("Please copy and paste your entry for re-entry");
String NewMod = Cons.next();
Notes.add(Mod, NewMod);
}
Execute.Instruct();
}
答案1
得分: 0
当你有一个大小为 n
的数组时,有效的索引为 0..n-1
。列表(Lists)同样适用这个规则。
因此,例如,如果你的列表有4个元素,有效的索引分别为 0、1、2 和 3。
你的输入验证条件应为
if (Mod < 0 || Mod >= Notes.size()) {
// 抱怨
} else {
// 索引是有效的
}
英文:
When you have a n-
sized array, valid indices are 0..n-1
. Same applies to Lists.
So for instance, if your list has 4 elements, valid indices are 0, 1, 2, and 3.
Your input validation condition should become
if (Mod < 0 || Mod >= Notes.size()) {
// complain
} else {
// index is good
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论