【问题标题】:Java - How to pull the list position as an integer?Java - 如何将列表位置拉为整数?
【发布时间】:2020-03-08 02:04:31
【问题描述】:

我正在尝试让我的代码提取所有匹配的索引值。我目前不知道如何根据它是否包含输入的相应值来拉取列表的位置值(比如它是否在位置 0、1、2、3 等)。

import java.util.ArrayList;
import java.util.Scanner;

public class Test086 {
    public static void main(String[] args) {

        Scanner user = new Scanner(System.in);
        ArrayList<Integer> array = new ArrayList<>();


        int userIn = 0;
        System.out.println("Please provide your own array of numbers. Hit enter again to exit the program.");

        while (true) {
            userIn = Integer.valueOf(user.nextLine());
            if (userIn == -1) {
                break;
            }
            else {
                array.add(userIn);
            }
        }

        System.out.print("Search for? ");
        int index = Integer.valueOf(user.nextLine());
        int indSize = array.size() - 1;

        for (int i = 0; i < array.size(); i++) {
            if (index == array.get(i)) {
                System.out.print(index + " is at index ");
            }
             System.out.println(indSize);
        }
    }
}

如果我为我的列表输入我的程序:

72
2
8
8
11
-1

Search for? 8

我的期望是将其作为输出:

8 is at index 2
8 is at index 3

什么是我不知道的?有什么方法可以检查位置并将其拉到类似于我拥有的 for 循环?

【问题讨论】:

  • System.out.print(index + " is at index " + i);
  • @Kon 哈哈哇!我现在完全明白了。出于某种原因,我没有意识到当我的索引变量和 array.get(i) 在布尔点中相等时,索引位置将在被拉动时保持,直到它再次增加。谢谢!
  • @mightymorphinParkRanger 没问题!这里有一个重要的经验教训是尝试在大脑的工作记忆中保持各种范围变量及其状态。即使是很小的变量也应该在您建立的任何功能的心智模型中占有一席之地。祝你好运!
  • @mightymorphinParkRanger - 你还应该注意stackoverflow.com/questions/60583899/…中提到的一些事情

标签: java arrays list


【解决方案1】:
    for (int i = 0; i < array.size(); i++) {
        if (index == array.get(i)) {
            System.out.print(index + " is at index " + i); // change here
        }
         System.out.println(indSize);
    }

【讨论】:

    【解决方案2】:

    您需要在for 循环中打印i 的值,如下所示:

    for (int i = 0; i < array.size(); i++) {
        if (index == array.get(i)) {
            System.out.println(index + " is at index " + i);
        }
    }
    

    除此之外,我还建议您使用泛型,例如List&lt;Integer&gt; array = new ArrayList&lt;Integer&gt;() 而不是 ArrayList&lt;Integer&gt; array = new ArrayList&lt;&gt;()。查看this 了解更多信息。

    另一个建议是对用户输入无效值的情况进行异常处理。

    完整程序:

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    public class Test086 {
        public static void main(String[] args) {
    
            Scanner user = new Scanner(System.in);
            List<Integer> array = new ArrayList<Integer>();
    
            int userIn = 0;
            System.out.println("Please provide your own array of numbers. Hit enter again to exit the program.");
    
            while (true) {
                try {
                    userIn = Integer.parseInt(user.nextLine());
                    if (userIn == -1) {
                        break;
                    } else {
                        array.add(userIn);
                    }
                } catch (Exception e) {
                    System.out.println("Invalid input. Try again.");
                }
            }
    
            int index = 0;
            boolean valid;
            do {
                valid = true;
                System.out.print("Search for? ");
                try {    
                    index = Integer.valueOf(user.nextLine());
                } catch (Exception e) {
                    System.out.println("Invalid input. Try again.");
                    valid = false;
                }
            } while (!valid);
            for (int i = 0; i < array.size(); i++) {
                if (index == array.get(i)) {
                    System.out.println(index + " is at index " + i);
                }
            }
        }
    }
    

    示例运行:

    Please provide your own array of numbers. Hit enter again to exit the program.
    72
    2
    a
    Invalid input. Try again.
    abc
    Invalid input. Try again.
    8
    8
    11
    -1
    Search for? a
    Invalid input. Try again.
    Search for? x
    Invalid input. Try again.
    Search for? 8
    8 is at index 2
    8 is at index 3
    

    为了使程序模块化,我还建议将用户输入分解为单独的方法(例如int getIntInput(Scanner)),如下所示:

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    public class Test086 {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            List<Integer> list = new ArrayList<Integer>();
    
            int userIn = 0;
            System.out.println("Please provide your own array of numbers. Hit enter again to exit the program.");
            while (true) {
                userIn = getIntInput(in);
                if (userIn == -1) {
                    break;
                } else {
                    list.add(userIn);
                }
            }
    
            System.out.print("Search for? ");
            int index = getIntInput(in);
            for (int i = 0; i < list.size(); i++) {
                if (index == list.get(i)) {
                    System.out.println(index + " is at index " + i);
                }
            }
        }
    
        static int getIntInput(Scanner in) {
            boolean valid;
            int n = 0;
            do {
                valid = true;
                try {
                    n = Integer.valueOf(in.nextLine());
                } catch (Exception e) {
                    System.out.println("Invalid input. Try again.");
                    valid = false;
                }
            } while (!valid);
            return n;
        }
    }
    

    示例运行:

    Please provide your own array of numbers. Hit enter again to exit the program.
    72
    2
    a
    Invalid input. Try again.
    abc
    Invalid input. Try again.
    8
    8
    11
    -1
    Search for? x
    Invalid input. Try again.
    8
    8 is at index 2
    8 is at index 3
    

    【讨论】:

      【解决方案3】:

      List 对此有一个方法。它使您可以获取对象的索引。它返回遇到的第一个匹配值的索引。使用此功能有两种方法可以解决此问题。两者都使用列表的sublist 功能。

      第一种方法获取lastIndexOf方法获取索引。这样做的好处是,在创建子列表时,不会改变下一项的正常位置。缺点是索引是逆序获取的。

              List<Integer> vals =
                      new ArrayList<>(List.of(10, 20, 1, 9, 10, 55, 9, 9, 9));
      
              int selection = 9;
              for (;;) {
                  int idx = vals.lastIndexOf(selection);
                  if (idx < 0) {
                      break;
                  }
                  System.out.println(selection + " located at index " + idx);
                  vals = vals.subList(0, idx);
              }
      
      

      下一个方法,使用indexOf 来获取值。为确保索引正确,需要进行一些记账以考虑缩短的子列表。

              vals = new ArrayList<>(List.of(10, 20, 1, 9, 10, 55, 9, 9, 9));
              int lastIndex = 0;
              for (;;) {
                  int idx = vals.indexOf(selection);
                  if (idx < 0) {
                      break;
                  }
                  System.out.println(selection + " located at index "
                          + (idx + lastIndex));
                  idx++;
                  lastIndex += idx;
                  vals = vals.subList(idx, vals.size());
              }
      

      最后,再次使用indexOf,如果可以改变提供的列表,只需将当前值替换为不同的值,这样就不会再次找到它。

              vals = new ArrayList<>(List.of(10, 20, 1, 9, 10, 55, 9, 9, 9));
      
              for (;;) {
                  int idx = vals.indexOf(selection);
                  if (idx < 0) {
                      break;
                  }
                  System.out.println(selection + " located at index "
                          + idx);
                  vals.set(idx, selection + 1); // modify selection
              }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-01
        • 2020-01-24
        • 2021-08-08
        • 1970-01-01
        相关资源
        最近更新 更多