java - 为什么 for 循环可以保存返回的布尔值但不能保存原始布尔值?
问题描述
看一下以下代码片段的for 循环。
class Practice
{
static boolean foo(char c){
System.out.print(c);
return true;
}
public static void main( String[] args ){
int i = 0;
for (foo('A'); foo('B') && (i < 2); foo('C')){
i++;
foo('D');
}
}
}
这部分代码在编译执行时不会报错。即使它从函数中获取布尔值
for (foo('A'); foo('B') && (i < 2); foo('C')){
i++;
foo('D');
}
虽然这是一个错误,
boolean b = true;
for (b;some_condition;b){
//statements
}
// or,
for (true;some_condition;true){
//statements
}
解决方案
这是来自 Oracle 的 java 官方语法:
ForControl:
ForVarControl
ForInit ; [Expression] ; [ForUpdate]
ForVarControl:
{VariableModifier} Type VariableDeclaratorId ForVarControlRest
ForVarControlRest:
ForVariableDeclaratorsRest ; [Expression] ; [ForUpdate]
: Expression
ForVariableDeclaratorsRest:
[= VariableInitializer] { , VariableDeclarator }
ForInit:
ForUpdate:
StatementExpression { , StatementExpression }
据我了解 ForInit 和 ForUpdate 期望一个语句,而不是像这样的文字值true
或像b
.
https://docs.oracle.com/javase/specs/jls/se7/html/jls-18.html
推荐阅读
- wagtail - 如何访问 Wagtail 片段菜单
- html - 调整页面大小时如何在 CSS 中将这些框居中?
- c++ - 为什么 std::atomic
在 C++14 中无限期阻塞? - c# - C# 使用带有和不带有“外部别名”的相同 DLL(程序集)
- intellij-idea - 使用 SVN 在 intellij IDEA 中与相同的新创建目录合并冲突
- laravel - Laravel Eloquent 将属性传递给关系
- android - Alert.alert 在 React 本机 iOS 中不起作用,但在 Android 中非常好
- php - 更新后字符类中的 Wordpress 无效范围
- python - 如何从列名中删除非 ASCII 字符和空格
- java - 有没有办法使用 google auto-ml 的 rest api 生成客户端 ID 和客户端密钥?