for(String i:array)
时间: 2024-02-21 22:01:40 浏览: 20
这是一个 Java 中的增强 for 循环语法,用于遍历数组或集合。其中,array 可以是一个数组或者实现了 Iterable 接口的集合类对象。每次循环迭代时,将会将 array 中的元素依次赋值给 i 变量,直到遍历完所有元素为止。
例如,如果 array 是一个 String 类型的数组,那么可以使用如下代码遍历其所有元素:
```
String[] array = {"Hello", "World", "!"};
for (String i : array) {
System.out.println(i);
}
```
输出结果为:
```
Hello
World
!
```
相关问题
for(String i:array),这个语句我觉得应该是一个循环语句,但是和我这个初学者平时见到的不一样,我平时见到的for循环语句的括号内一般包含初始值、循环条件、自增或自减这三个操作,但是这个语句却没有,能向我解释一下这个语句的意思吗?
当您使用 `for(String i:array)` 这样的语句时,它实际上是 Java 5 引入的 "增强型 for 循环",也被称为 "for-each 循环"。这种语法用于遍历数组或集合中的所有元素,而无需使用传统的 for 循环语法。
在这个语句中,`array` 是一个数组,`String i` 表示每一次循环时,`i` 将会被赋值为数组 `array` 中的一个元素。这个语句的含义是:遍历数组 `array` 中的每一个元素,并将其依次赋值给 `i`,然后执行循环体内的代码。
这个语句的优点是简单易懂,代码更加简洁,同时也减少了一些出错的可能性。但是,它的缺点是无法访问元素的索引位置,如果需要索引位置的值,仍需要使用传统的 for 循环语法。
希望这个解释能够对您有所帮助。
string translate to array int
To convert a String to an array of integers in Java, you can use the following code:
```
String str = "12345";
int[] arr = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
arr[i] = Character.getNumericValue(c);
}
```
In this code, we first create a String `str` with the value we want to convert to an array of integers. We then create an integer array `arr` with the same length as the String `str`.
We use a `for` loop to iterate over each character in the String `str`. For each character, we use the `charAt()` method to get the character at the current index, and then use the `Character.getNumericValue()` method to convert the character to an integer. We then assign this integer value to the corresponding index in the integer array `arr`.
After the loop completes, the integer array `arr` will contain the integer values corresponding to the characters in the String `str`.