那么,如何让它更紧凑?
public static boolean isDirectOrder( int[] data )
{
boolean answer = true;
if ( ( data != null ) && ( data.length > 1 ) )
{
int last = data[0];
for (int i = 0; i < data.length; i++)
{
if ( last <= data[i] )
{
last = data[i];
}
else
{
answer = false;
break;
}
}
}
return answer;
}
可能存在相同检查的标准工具吗?
答案 0 :(得分:4)
public static boolean isDirectOrder( int[] data )
{
if (data != null)
for (int i = 1; i < data.length; i++)
if (data[i] < data[i - 1])
return false;
return true;
}
答案 1 :(得分:2)
也许这样(未经测试)。
public static boolean isDirectOrder( int[] data )
{
if ((data != null))
{
for (int i = 1; i < data.length; i++)
{
if (data[i] <= data[i - 1])
return false;
}
}
return true;
}
答案 2 :(得分:2)
class A {
public static boolean isDirectedOrder(int[] d) {
if (d == null) return true;
for (int i = 0, l = d.length - 1; i < l; i ++) if (d[i] > d[i + 1]) return false;
return true;
}
public static void main(String[] args) {
System.out.println(isDirectedOrder(new int[] { 1, 2, 3, 4, 5, 6, 8, 10 }));
System.out.println(isDirectedOrder(new int[] { 1 }));
System.out.println(isDirectedOrder(new int[] { 3, 2, 5, 1, 5, 7 }));
}
}
答案 3 :(得分:0)
对我来说看起来很紧凑。您正在尝试查找数组是否已排序。您可以删除一些if语句的大括号:
if ( last <= data[i] )
{
last = data[i];
}
可能会成为
if ( last <= data[i] )
last = data[i];
答案 4 :(得分:0)
data == null
时返回true有点不合逻辑。
public static boolean isDirectOrder( int[] data )
{
if (data == null)
throw new NullPointerException("Array is null");
for (int i = 1; i < data.length; ++i)
if (data[i] < data[i - 1]) // When this one is smaller than the previous one.
return false;
return true;
}
事实上,语句data.length
也会抛出NullPointerException:
public static boolean isDirectOrder( int[] data )
{
for (int i = 1; i < data.length; ++i)
if (data[i] < data[i - 1])
return false;
return true;
}