java - 基本 Java 数组列表

标签 java arraylist

编写一个 Java 方法,接收未声明的整数 ArrayList 和一个整数作为参数,在 ArrayList 中搜索该整数,如果找到则返回 true

A)使用while循环进行搜索。 B) 再试一次,但使用 for 循环 C)再试一次,但使用 for-each 循环 D)(这很难)编写一个 Java 方法,该方法接收整数 ArrayList 作为参数,并返回集合中最大整数的索引。

//part a 
int i =0 ;
while (i<500) 
{
    if (values [i] == 3927)
    { 
        system.out.prinln("FOUND IT!");
        break;
    }
    i++; 
}  

如果需要,我会发布我想出的代码,如果需要请评论。我真的很难编译它。

最佳答案

好吧啊啊啊啊啊。让我们从顶部开始吧,我的好人。

While 循环

文档: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

while 循环是一条语句,内容如下:

while the current statement is true
      keep doing everything inside the brackets.

例如..

while(!found) // While found is not equal to true
{
    if(x == 4) found = true;
}

一旦x等于4,循环就会结束。这些循环是在您不知道要循环多少次时设计的。按照这个示例,您需要了解一些细节。首先,您需要知道用户正在寻找什么,我们将其称为。其次,您需要搜索列表,我们将其命名为 myList。您将返回一个 boolean,因此您的方法将如下所示:

public boolean exists(Integer value)
{
    int position = 0; // The position in myList.

    while(!found && position < myList.size())
    {
        // You're going to work this bit out.
    }

    return false; // Value doesn't exist.
}

这里的技巧是,如果 myList 中的值位于 position 位置,则将 found 设置为 true >,等于

<小时/>

For 循环

文档:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

当您知道要循环多少次时,通常会使用For 循环。然而,由于这是一项学术练习,我们暂时忽略这个小细节。 for循环的思想如下:

for(some value x; check x is less/more than some value; do something with x) {
}

例如:

for(int x = 0; x < 10; x++)
{
    System.out.println("Hello: " + x);
}

上面的循环将打印出Hello:0Hello:1...Hello:9。现在,您要做的就是执行与 while 循环 中完全相同的操作,但只需将其包装在 for 循环中即可。

for(int position = 0; position < myList.size(); position++)
{
    // if value, in myList at position equals value, then return true.
}

return false; // Value doesn't exist.
<小时/>

For-Each 循环

文档: http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

for-each 循环与 for 循环 非常相似,只是语法更好一点,特别是当您想要循环遍历 a 中的每个值时列表数组

for(Integer item : myList)
{
    // Creates a variable called value. If item == value, return true.
}

return false;

至于最后一个,这一切都取决于你,伙计,但我会告诉你一些技巧。您将循环遍历列表中的每个值(参见上文!!!)

关于java - 基本 Java 数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21958751/

相关文章:

java - 适合在数组列表中使用的泛型

java - Java中的Arraylist和继承

Java:创建一个 HashMap 列表

java - 比较数组列表的字符串元素中的字符导致indexoutofboundsException

math - java.lang.Math 与 kotlin.math 兼容吗?

java - 将数组索引号分配给for循环java中的变量

java - Infinispan/JGroups集群连接失败,当TCPPING.initialHost包含多个主机时

java - Intellij IDEA 远程调试无效断点

java - 在 Java 中对 ArrayList 进行排序

java - 如何从单元格表中删除一行