Java 仅打印数组或数组索引的当前值
Java新手: 我使用for循环来迭代数组并检查其值。 例如:如果数组包含数字100。然后做点什么, 但是,如果没有,则获取当前变量的当前值 进行检查时,是否可以获取当前变量的值 目前,当我使用else打印时,我会将所有内容打印出来 像这样:Java 仅打印数组或数组索引的当前值,java,Java,Java新手: 我使用for循环来迭代数组并检查其值。 例如:如果数组包含数字100。然后做点什么, 但是,如果没有,则获取当前变量的当前值 进行检查时,是否可以获取当前变量的值 目前,当我使用else打印时,我会将所有内容打印出来 像这样: 1 2 3 Found Something! 请原谅我的无知。只是试验: public class MyArrayExample { private int[] intArray = new int[] {1, 2, 3, 100};
1
2
3
Found Something!
请原谅我的无知。只是试验:
public class MyArrayExample {
private int[] intArray = new int[] {1, 2, 3, 100};
public int[] getArrayValues() {
return intArray;
}
public static void main(String[] args)
{
MyArrayExample example = new MyArrayExample();
int[] arrayValues = example.getArrayValues();
for(int counter=0; counter<arrayValues.length; counter++) {
int current = arrayValues[counter];
if(current == 100)
{
System.out.println("Found Something!");
}
else{
System.out.println(current);
}
}
}
}
公共类MyArrayExample{
私有int[]intArray=newint[]{1,2,3100};
public int[]getArrayValues(){
返回阵列;
}
公共静态void main(字符串[]args)
{
MyArrayExample示例=新建MyArrayExample();
int[]arrayValues=example.getArrayValues();
for(int counter=0;counter要在进行检查时获取当前值,请在for循环外部声明它,以便访问变量值并添加布尔标志isFound:
int current = 0;
boolean isFound = false;
for(int counter=0; counter<arrayValues.length; counter++) {
current = arrayValues[counter];
if(current == 100)
{
isFound = true;
// do something
}
}
注意。如果您要查找的值在数组中不存在,则current始终与数组中的最后一个值一起分配。作为一个加法-您甚至不必自己编写循环,您可以使用现有的数组/收集方法,例如:
Integer[]intArray=新整数[]{1,2,3,100};
List myList=Arrays.asList(intArray);
System.out.println(myList.contains(100));//检查数组中是否存在100
System.out.println(myList.indexOf(100));//显示元素100的位置
是的,你能做到,你执行了你的代码吗?它应该可以正常工作,看不到任何错误。这正是我想要理解的:非常感谢你解释并提供了一个例子:因此评估必须在for循环之外进行,以便只打印当前值。哪里打印所有不等于100的项目?@Gangnus:这就是为什么我说“作为补充”,因为我认为在这方面使用他的阵列可能会有帮助。
if (isFound) {
System.out.println("Found Something!");
} else {
System.out.println("current: " + current);
}
Integer[] intArray = new Integer[] {1, 2, 3, 100};
List<Integer> myList = Arrays.asList(intArray);
System.out.println(myList.contains(100)); // checks if 100 exists in your array
System.out.println(myList.indexOf(100)); // shows the position of the element 100