JAVA:使用数字位置替换数组中的数字并打印出来
问题描述:
我在这里有一个小问题。我想用数字位置替换数组中的所有负数。我的问题是,数组被打印出来,被替换的数字面前,我想打印出数组就被替换后... 这里是我的代码:JAVA:使用数字位置替换数组中的数字并打印出来
public class oppgave33{
public static void main(String[] args) {
int[] heltall = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int counter = 0;
int sumNeg = 0;
while(counter < heltall.length){
//array print out
System.out.println("array[" + counter + "] = " + heltall[counter]);
if(heltall[counter] < 0){
System.out.println(heltall[counter]);
}
//replacing negative numbers
if(heltall[counter] < 0){
heltall[counter]=counter;
}
if(heltall[counter] < 0){
sumNeg++;
}
//negative numbers position print out
if(heltall[counter] < 0){
System.out.println("Negative numbers position in array is : " + counter);
}
counter++;
}
//printing out how many negative numbers
System.out.println("There are : " + sumNeg + " negative numbers.");
}
}
最后一点:如果你删除在if设置中,负数由阵列中的位置替换,您将获得打印出负数的位置,以及有多少负数。 我希望你能帮助我! :) 谢谢!
答
您的代码中有太多冗余条件。您的尝试是非常密切的,你可以简单地做到以下几点:
while (counter < heltall.length) {
// if the number is negative, replace it with its index
if (heltall[counter] < 0) {
heltall[counter] = counter;
}
counter++;
}
// outside the loop
System.out.println(Arrays.toString(heltall));
重要的提示:在这种情况下,你应该调试你的代码。这将帮助您更好地理解代码流,并发现您不知道的问题。我强烈建议您调试您的当前代码,然后尝试修复它。
答
你不需要太多的条件来取代负数。当你在循环中得到一个负数时,一个接一个地替换。
删除冗余:需要记住的一件事:当您有相同条件的某些语句时,您不需要单独执行它们。在块中写入所有语句。
例如,在你的代码:
if (heltall[counter] < 0) {
System.out.println(heltall[counter]);
}
if (heltall[counter] < 0) {
heltall[counter] = counter;
}
if (heltall[counter] < 0) {
sumNeg++;
}
if (heltall[counter] < 0) {
System.out.println("Negative numbers position in array is : " + counter);
}
可以被替代:
if(heltall[counter] < 0) { // do all in the same if condition block
System.out.println(heltall[counter]);
heltall[counter] = counter;
sumNeg++;
System.out.println("Negative numbers position in array is : " + counter);
}
解决方案:总之,整个代码看起来是这样的:
while (counter < heltall.length) {
// replacing negative numbers
if (heltall[counter] < 0) {
heltall[counter] = counter;
sumNeg++;
}
counter++;
}
System.out.println("There were : " + sumNeg + " negative numbers.");
System.out.println("Array after replacing negative numbers: "+Arrays.toString(heltall));
答
以下是您的代码的工作版本:
注意:您必须在更换后放置打印命令。代码按照顺序逐步执行。顶部行的语句首先运行,然后是较低的行(确定按顺序)。
public class oppgave33{
public static void main(String[] args) {
int[] heltall = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int counter = 0;
int sumNeg = 0;
while(counter < heltall.length){
if(heltall[counter] < 0){
//replacing negative numbers
heltall[counter]=counter;
//counting negative number amount
sumNeg++;
//array print out after replace
System.out.println("array[" + counter + "] = " + heltall[counter]);
//negative numbers position print out
System.out.println("Negative numbers position in array is : " + counter);
}
counter++;
}
//printing out how many negative numbers
System.out.println("There are : " + sumNeg + " negative numbers.");
}
}
可能重复的http://stackoverflow.com/questions/39528556/replacing-array-values,但这次是从提问者的努力。 :-) –