gpt4 book ai didi

java - 如何用给定值填充数组

转载 作者:行者123 更新时间:2023-12-01 22:39:02 24 4
gpt4 key购买 nike

我必须获取一个数字序列并计算它需要多少次,然后将其放入一个数组中,以便我可以对数组进行排序并查找第 10 大的。我可以得到计数,但似乎无法填充数组,我要么在数组中的每个索引处输入最终计数,要么只是将索引 0 处的数组值增加到所有数字的计数,任何人都可以帮忙。

public class seBuilder

{

//int count=0;


//int [] myArray= new int[10];


public static void main (String args[])
{
int count=0;
int [] myArray= new int[13];
int z=0;
for(int i=2;i<=myArray.length;i++)
{
z=valuegetter(i);
System.out.println(z);

}

//arraycounter(myArray, z);


}

public static int valuegetter(int num)
{
int count=0;
do// do while loop
{
//if its an odd number
if(num%2==1){
num=(num*3)+1;//do this from the question
count++;// add one to count
}
//if num is 2 this will catch and make the code break out
else if(num==2){
//devide num by 2, this will give you 1 allways
System.out.println(num/2);
count++;//adds 1 again
}
else
{
num=num/2;//this will use if number is even
count++;//adds one to count
}

}
while(num>2);//the condition to jump out of loop
//System.out.println("there are "+count+" sequences in that mumber");
return count;
}


public static int[] arraycounter(int myArray[], int count)
{

for(int i=0;i<=myArray.length-1;i++)
{
myArray[i]=count;
System.out.println(" "+myArray[i]);
}
return myArray;
}

public static int tenhigh()
{

}
}

最佳答案

尝试将您的 main 更改为:

public static void main (String args[])
{
int count=0;
int [] myArray= new int[13];
int z=0;
for(int i=2;i<=myArray.length;i++) {
z=valuegetter(i);
System.out.println(z);
arraycounter(myArray, z, i);

}
for (int i=0; i < myArray.length; i++) {
System.out.print(myArray[i] + ", ");
}
}

还将您的 arrayCounter 方法更改为:

public static int[] arraycounter(int myArray[], int count, int i)
{
int j = i - 2;
myArray[j] = count;
return myArray;
}

关于java - 如何用给定值填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26452381/

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