Java 返回用户键入的索引处的字符串(ArrayList)

Java 返回用户键入的索引处的字符串(ArrayList),java,arraylist,Java,Arraylist,我正在尝试创建一个简单的方法。基本上,我希望这个方法(称为“returnIndex”)返回用户键入的ArrayList索引号处的单词 例如: 如果用户在“1”中键入,is应返回ArrayList中索引1处的任何字符串 这就是我到目前为止所做的: public void returnIndex () { Scanner in = new Scanner (System.in) while (in.hasNextLine()) { if (in.equals(

我正在尝试创建一个简单的方法。基本上,我希望这个方法(称为“returnIndex”)返回用户键入的ArrayList索引号处的单词

例如: 如果用户在“1”中键入,is应返回ArrayList中索引1处的任何字符串

这就是我到目前为止所做的:

public void returnIndex ()
{
    Scanner in = new Scanner (System.in)
    while (in.hasNextLine())
    {
        if (in.equals(1))
        {
            //return item at that index
        }
    }
}
我只是不知道如何在Java中说“返回该索引处的项”。当然,我必须使代码与任何其他数字一起工作,而不仅仅是“1”。但现在,我关注的是“1”。甚至不确定.equals(1)中的
部分是否100%正确

如果这个问题看起来有点简单,我很抱歉。我还在用我的Java。请只是提示,没有完整的答案。非常感谢。

公共字符串返回索引(扫描仪输入,列表){
public String returnIndex(Scanner in, List<String> list) {
    return list.get(in.nextInt());
}
return list.get(in.nextInt()); }
  • 不要创建新的扫描仪,因为它可能会导致微妙的问题。相反,只创建一个并继续使用它。这意味着您应该将其传递到此函数中
  • 当列表可以使用时,不需要使用ArrayList(就像这里一样)
  • 如果希望函数返回
    字符串
    ,则需要使其返回
    字符串,而不是
    无效
公共静态void main(字符串[]args){
列表值=新的ArrayList();
价值。添加(“一”);
加上(“两”);
增加(“三”);
字符串结果=getStringAtIndex(值);
System.out.println(“结果:+result”);
}
公共静态字符串getStringAtIndex(列表){
扫描仪=新的扫描仪(System.in);
int指数=0;
索引=scanner.nextInt();
返回列表.get(索引-1);
}

ArrayList在哪里?
public static void main(String[] args) {

        List<String> values = new ArrayList<String>();
        values.add("One");
        values.add("Two");
        values.add("Three");

        String result = getStringAtIndex(values);
        System.out.println("The result:" + result);

    }

    public static String getStringAtIndex(List<String> list) {
        Scanner scanner = new Scanner(System.in);
        int index = 0;
        index = scanner.nextInt();
        return list.get(index-1);
    }