简体   繁体   English

Java:for循环,不兼容的类型

[英]Java: for loop, incompatible types

I'm trying to run this for loop;我正在尝试运行这个 for 循环;

        for (int col= 0; grid[0].length; col++)

However every time I try to compile I get an error stating 'incompatible types - found int but expected boolean'但是,每次我尝试编译时,都会收到一条错误消息,指出“不兼容的类型 - 找到 int 但预期为布尔值”

I can't work out what I'm doing wrong!我无法弄清楚我做错了什么!

the second statement: grid[0].length is an integer. 第二个语句:grid [0] .length是一个整数。 The second statement in a for loop is a condition statement and needs to be a boolean. for循环中的第二个语句是条件语句,需要是一个布尔值。

If you're trying to loop while col is less than the length of grid[0], then you need this as your second statement: 如果你在col小于grid [0]的长度时试图循环,那么你需要这个作为你的第二个语句:

col < grid[0].length; col <grid [0] .length;

for (int col= 0; col < grid[0].length; col++)   // See the typo

grid[0].length is the integer that the message refered to. grid[0].length是消息所指的整数。 A boolean value was expected there: 那里有一个布尔值:

col < grid[0].length

您需要将代码更改为:
for (int col= 0; col<grid[0].length; col++)

For anyone interested in where this is specified: Check out docs.oracle.com for the Java Language Specification.对于任何对指定位置感兴趣的人:查看docs.oracle.com以获取 Java 语言规范。 Chapter 14 §14.1 states the rules for a basic for loop:第 14 章 §14.1 说明了基本 for 循环的规则:

BasicForStatement:
  for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement

with the addendum that:附有以下说明:

The type of the Expression must be boolean or Boolean, or a compile-time error occurs. Expression的类型必须是 boolean 或 Boolean,否则会发生编译时错误。

This particular citation was taken from the Java SE 17 specification.这个特定的引用取自 Java SE 17 规范。 Since this post was 11+ years ago, (almost twelve at the time of this response) the question likely refers to Java SE 7, which has the same rule and almost the same verbiage verbatim.由于这篇文章是 11 多年前发布的(在此回复时几乎是 12 年),这个问题可能是指 Java SE 7,它具有相同的规则和几乎相同的字面意思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM