如何使用if else语句来检查用户是否根据数组列表索引输入了有效条目?

huangapple go评论64阅读模式
英文:

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 &lt; 0 || Mod &gt;= Notes.size()) {
  // complain
} else {
  // index is good
}

huangapple
  • 本文由 发表于 2020年5月5日 08:52:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/61604029.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定