在Java中,如何获取Java中元素的当前索引?
for (Element song: question){
song.currentIndex(); //<<want the current index.
}
Run Code Online (Sandbox Code Playgroud)
在PHP中你可以这样做:
foreach ($arr as $index => $value) {
echo "Key: $index; Value: $value";
}
Run Code Online (Sandbox Code Playgroud) 是否有可能在增强的for循环中找到当前索引?如果是这样的话?
我知道我们可以用一个额外的变量检查它.但还有其他方法.
public boolean cancelTicket(Flight f, Customer c) {
List<BookingDetails> l = c.getBooking();
if (l.size() < 0) {
return false;
} else {
for (BookingDetails bd : l) {
if(bd.getFlight()==f){
l.remove() // Index here..
}
}
}
}
Run Code Online (Sandbox Code Playgroud) 因为没有可访问的计数器或i在那里重置为零.
有没有办法玩continue或break实现这一目标?
class CommandLine {
public int[] sort(int array[]) {
int temp;
for (int i=0; i<array.length-1; i++) {//must have used for-each
if (array[i] > array[i+1]){
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
i=-1;
}//if end
}//for end
return array;
}//main end
}//class end
Run Code Online (Sandbox Code Playgroud) 我有两个数组:
name[] and roll[]
Run Code Online (Sandbox Code Playgroud)
有没有办法遍历每个循环中的两个数组.两个数组的大小保持不变.
我知道使用两个单独的循环,我们可以遍历和infact一个也不是什么大不了,但我想要这样的东西:
for(String n:name,int r:roll){
//blah blah
}
Run Code Online (Sandbox Code Playgroud)
请稍微谢谢..... Ankur
每个循环我有两个,我试图为每个第二个结果输出不同的东西:
foreach ($wppost as $wp) {
$wp_title = $wp->post_title;
$wp_date = strtotime($wp->post_date);
$wp_slug = $wp->post_name;
$wp_id = $wp->ID;
// Start Permalink Template
$wp_showurl = $wp_url;
$wp_showurl = str_replace("%year%", date('Y', $wp_date), $wp_showurl);
$wp_showurl = str_replace("%monthnum%", date('m', $wp_date), $wp_showurl);
$wp_showurl = str_replace("%day%", date('d', $wp_date), $wp_showurl);
$wp_showurl = str_replace("%hour%", date('H', $wp_date), $wp_showurl);
$wp_showurl = str_replace("%minute%", date('i', $wp_date), $wp_showurl);
$wp_showurl = str_replace("%second%", date('s', $wp_date), $wp_showurl);
$wp_showurl = str_replace("%postname%", $wp_slug, $wp_showurl);
$wp_showurl = str_replace("%post_id%", $wp_id, $wp_showurl);
// Stop Permalink Template
$wp_posturl = $blog_address . $wp_showurl; …Run Code Online (Sandbox Code Playgroud) 这样做有什么好处,如果有的话:
for (int i = 0, size = foo.size(); i < size; i++) {}
而不是这个:
for (int i = 0 ; i < foo.size(); i++) {}
(foo是一个List对象)
我必须读取字符串"hello world"并仅使用for循环输出每个字母的频率.教练暗示我需要使用两个循环并给我们以下代码开始:
int ch, count;
for (ch ='a'; ch <='z'; ch++) {
//count the number of occurrences in a line
//Print the count>0
}
Run Code Online (Sandbox Code Playgroud)
编辑:我想我会解决这个问题并发布我一年前找到的解决方案,因为这个问题已经得到了相当多的点击量.
int count;
int value;
for (int i=65; i<91; i++) {
count=0;
for (int j=0; j<S.length; j++) {
value=(int)S[j];
if (value == i) {
count++;
}
}
if (count>0)
System.out.println((char)i+" -- "+count);
}
Run Code Online (Sandbox Code Playgroud)