显然,在Java中以多种方式使用冒号.有人会介意解释它的作用吗?
比如这里:
String cardString = "";
for (PlayingCard c : this.list) // <--
{
cardString += c + "\n";
}
Run Code Online (Sandbox Code Playgroud)
你会如何for-each以不同的方式编写这个循环,以便不包含:?
我想要两个不同类型的循环变量.有没有办法让这项工作?
@Override
public T get(int index) throws IndexOutOfBoundsException {
// syntax error on first 'int'
for (Node<T> current = first, int currentIndex; current != null;
current = current.next, currentIndex++) {
if (currentIndex == index) {
return current.datum;
}
}
throw new IndexOutOfBoundsException();
}
Run Code Online (Sandbox Code Playgroud) 目前,我只能使用以下方法进行基于范围的循环:
for (auto& value : values)
Run Code Online (Sandbox Code Playgroud)
但有时我需要一个值的迭代器,而不是一个引用(无论出于何种原因).是否有任何方法无需通过整个矢量比较值?
假设我有一个Unix shell变量,如下所示
variable=abc,def,ghij
Run Code Online (Sandbox Code Playgroud)
我想使用for循环提取所有值(abc,def和ghij)并将每个值传递给过程.
该脚本应允许从中提取任意数量的逗号分隔值$variable.
对于Android应用,我有以下功能
private ArrayList<String> _categories; // eg ["horses","camels"[,etc]]
private int getCategoryPos(String category) {
for(int i = 0; i < this._categories.size(); ++i) {
if(this._categories.get(i) == category) return i;
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
这是编写函数获取元素位置的"最佳"方法吗?或者我应该利用java中的一个奇特的shmancy本机函数?
假设你有一个像这样的for循环
for(n in 1:5) {
#if(n=3) # skip 3rd iteration and go to next iteration
cat(n)
}
Run Code Online (Sandbox Code Playgroud)
如果满足某个条件,如何跳到下一次迭代?
由于一切都有限制,我想知道嵌套for循环的数量是否有限制,或者只要我有内存,我可以添加它们,Visual Studio编译器可以创建这样的程序吗?
当然,64个或更多嵌套for循环对调试来说不方便,但是它可行吗?
private void TestForLoop()
{
for (int a = 0; a < 4; a++)
{
for (int b = 0; b < 56; b++)
{
for (int c = 0; c < 196; c++)
{
//etc....
}
}
}
}
Run Code Online (Sandbox Code Playgroud) 这更像是一个概念性问题.我最近在Python中看到了一段代码(它在2.7中工作,也可能在2.5中运行),其中一个for循环对迭代的列表和列表中的项使用相同的名称,这既是一种糟糕的做法,也是一种根本不起作用的东西.
例如:
x = [1,2,3,4,5]
for x in x:
print x
print x
Run Code Online (Sandbox Code Playgroud)
产量:
1
2
3
4
5
5
Run Code Online (Sandbox Code Playgroud)
现在,我觉得打印的最后一个值是从循环中分配给x的最后一个值,但是我不明白为什么你能够为for循环的两个部分使用相同的变量名并且它按预期运作.它们在不同的范围内吗?引擎盖下发生了什么让这样的事情发挥作用?
2017年Javascript中使用for()循环与.forEach的当前标准是什么.
我目前的工作我的方式,通过柯尔特史蒂尔斯的"Web开发训练营"在Udemy他热衷forEach在for他的教导.然而,我在练习期间搜索了各种各样的东西,作为课程工作的一部分,我发现越来越多的建议使用for-loop而不是forEach.大多数人似乎都认为for循环更有效率.
这是自课程编写以来发生过变化的事情(大约在2015年),或者是每个人的真正优点和缺点,哪个人将学习更多经验.
任何建议将不胜感激.
为什么这种结构会导致Scala中出现类型不匹配错误?
for (first <- Some(1); second <- List(1,2,3)) yield (first,second)
<console>:6: error: type mismatch;
found : List[(Int, Int)]
required: Option[?]
for (first <- Some(1); second <- List(1,2,3)) yield (first,second)
Run Code Online (Sandbox Code Playgroud)
如果我用List切换Some,它编译得很好:
for (first <- List(1,2,3); second <- Some(1)) yield (first,second)
res41: List[(Int, Int)] = List((1,1), (2,1), (3,1))
Run Code Online (Sandbox Code Playgroud)
这也很好:
for (first <- Some(1); second <- Some(2)) yield (first,second)
Run Code Online (Sandbox Code Playgroud)