【发布时间】:2018-04-13 00:55:00
【问题描述】:
假设我想以相反的顺序打印数组。但是,如果数组为空,则应打印“数组为空”
为什么这段代码不起作用:
我们可以假设如果数组为空a.length 为 0 还是为空?
if() 语句中的 a.length 应该是 ==。for 循环中不允许它工作的 if 语句有什么问题?还是从来没有进入过for循环?
public class Test2 {
public static void main(String[] args) {
int[] a = {};
for (int i = a.length - 1; i >= 0; i--) {
System.out.print(a[i] + " ");
if (a.length == 0)
System.out.print("The array is empty");
}
}
}
此代码有效:
if (a.length == 0)
System.out.print("The array is empty");
else
{
for(int i = a.length - 1 ; i >= 0 ; i--)
{
System.out.print (a[i] + " ");
}
}
这也有效:
for(int i = a.length - 1 ; i >= 0 ; i--)
{
System.out.print (a[i] + " ");
}
if (a.length == 0)
System.out.print("The array is empty");
【问题讨论】:
-
如果您使用的是java,请将其添加到标签中。
-
请指定语言
-
在您的第一段代码中,
if (a.length == 0)行在您的for循环中(与其他两个部分不同)。数组长度在循环内永远不会为零,所以你不会得到你想要的输出。 -
戴夫你说数组长度在循环内永远不会为零。如果数组开始为空......或者这是否意味着你永远不能创建一个没有元素的数组。因此,数组的长度总是必须为 1 或更多长度?