gpt4 book ai didi

java - 我是 Java 新手,这是一种好的编码技术吗?

转载 作者:行者123 更新时间:2023-11-30 06:16:07 24 4
gpt4 key购买 nike

我正在尝试学习一些java,我从codefights的一些作业开始,我只是想问一下我的编码技术是否好?例如,可以在 for 循环和多个 return 语句中使用break吗?

    boolean almostIncreasingSequence(int[] sequence) 
{
int i;
int firstTry = 0; /* to indicate the first try */
int secondTry = 0; /* to indicate the second try */
int indexOfBreakingElement = 0; /* to indicate which index of the array is not following the almost increasing sequence */
int sizeOfSequence = sequence.length;
int[] newFixedArray = new int[sizeOfSequence - 1]; /* an array used to store the edited or fixed array for further processing */
for(i = 0; i < sizeOfSequence-1; i++)
{
if(sequence[i] >= sequence[i+1])
{
indexOfBreakingElement = i+1;
firstTry = 1;
break;
}
}


if(firstTry==1)
{
for(i = 0; i < indexOfBreakingElement; i++)
{
newFixedArray[i] = sequence[i];
}
for(i = indexOfBreakingElement+1; i < sizeOfSequence; i++)
{
newFixedArray[i-1] = sequence[i];
}
}

for(i = 0; i < sizeOfSequence-2; i++)
{
if(newFixedArray[i] >= newFixedArray[i+1])
{
indexOfBreakingElement = i;
secondTry = 1;
break;
}
}

if(secondTry==1)
{
for(i = indexOfBreakingElement+1; i < sizeOfSequence; i++)
{
newFixedArray[i-1] = sequence[i];
}
}

for(i = 0; i < sizeOfSequence-2; i++)
{
if(newFixedArray[i] >= newFixedArray[i+1])
{
return false;
}
}
return true;
}

最佳答案

是的,您的编码技术很好(或者至少可以接受)。

for 循环中使用 break 完全没问题。事实上,这表明您可能拥有有关 Java 的高级知识,因为您已经证明您知道 break 将结束循环。

多次使用 return 也是如此,因为它表明您知道函数一旦 return 就会停止运行,这意味着您知道使用多个 return可以提高效率。

此外,您频繁使用 for 循环表明您可以轻松地使用它们,这很好。您使用 ij 作为计数器变量强化了这种印象。

注意:我想指出的是,使用冗长的变量名称并不是最佳实践,因为您更容易出现拼写错误(也就是说,您对变量使用驼峰命名法是件好事)。

关于java - 我是 Java 新手,这是一种好的编码技术吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49161696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com