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

huangapple 未分类评论51阅读模式
英文:

How do I use the if else statement to check if the user has inputted a valid entry in relation to array list index?

问题

  1. public static void Modify() {
  2. readelements();
  3. System.out.println("Enter the desired # of the entry you would like to modify");
  4. int Mod = Cons.nextInt();
  5. if (Mod != Notes.size()) {
  6. System.out.println("You've selected an invalid entry!\n");
  7. } else {
  8. System.out.println(Notes.get(Mod));
  9. Notes.remove(Mod);
  10. System.out.println("Please copy and paste your entry for re-entry");
  11. String NewMod = Cons.next();
  12. Notes.add(Mod, NewMod);
  13. }
  14. Execute.Instruct();
  15. }
英文:

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.

  1. public static void Modify()
  2. {
  3. readelements();
  4. System.out.println("Enter the desired # of the entry you would like to modify");
  5. int Mod = Cons.nextInt();
  6. if (Mod != Notes.size())
  7. {
  8. System.out.println("You've selected an invalid entry!\n");
  9. }
  10. else {
  11. System.out.println(Notes.get(Mod));
  12. Notes.remove(Mod);
  13. System.out.println("Please copy and paste your entry for re-entry");
  14. String NewMod = Cons.next();
  15. Notes.add(Mod, NewMod);
  16. }
  17. Execute.Instruct();
  18. }

答案1

得分: 0

当你有一个大小为 n 的数组时,有效的索引为 0..n-1。列表(Lists)同样适用这个规则。

因此,例如,如果你的列表有4个元素,有效的索引分别为 0、1、2 和 3。

你的输入验证条件应为

  1. if (Mod < 0 || Mod >= Notes.size()) {
  2. // 抱怨
  3. } else {
  4. // 索引是有效的
  5. }
英文:

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

  1. if (Mod &lt; 0 || Mod &gt;= Notes.size()) {
  2. // complain
  3. } else {
  4. // index is good
  5. }

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

发表评论

匿名网友

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

确定