[英]Arrays, having trouble understanding how to set it up
使用數組時,問題是:
我只有幾行代碼,我不知道我應該做什么。
public class ch9_problem1{
public static void main(String[] args){
double[] alpha = new double[50];
for(int x = 0; x < 25; x++){
System.out.print(alpha[x] + "\n");
}
}
}
你走在正確的軌道上,你應該繼續嘗試。
你的循環在迭代前25個元素時是正確的,你清楚地了解如何訪問數組中的元素,如下所示。
alpha[x]
從這里開始,您應該能夠使用一些簡單的數學和循環計數器x(您的索引變量)來設置每個元素(alpha [x])。
對於下半場,你只是從25而不是0開始你的循環!
我不會只是給你答案,因為這顯然是為了一個班級,但我添加了一些偽代碼來幫助你。 希望這不會太過分。
public class ch9_problem1
{
public static void main(String[] args)
{
// STEP 1 - You got this right!
double[] alpha = new double[50];
// STEP 2 - SOLVE:
// for int i - make a loop that goes through the first half of the array {
// alpha[i] = i * i;
// }
// STEP 3 - SOLVE:
// for int i - make a loop that goes through the second half of the array {
// alpha[i] = 3 * i;
// }
// I changed the loop to go until we're at the last element of the array
for(int x = 0; x < alpha.length-1; x++)
{
System.out.print(alpha[x]);
// STEP 4 - SOLVE:
// If this element's position is a multiple of 10
// System.out.print("\n");
// HINT: Use a remainder (modulo) operator
}
}
}
public static void main(String[] args)
{
double[] alpha = new double[50];
for(int x = 0; x < 50; x++)
{
if (x<25) alpha[x] = x*x;
if (x>=25) alpha[x] = x*x*x;
System.out.print(alpha[x]);
if (x%10 == 0) System.out.print("\n");
}
}
...聲明一個數組alpha到50個double類型的元素。
這是對的。
double[] alpha = new double[50];
初始化數組,使前25個數字等於索引變量的平方,最后25個元素等於索引變量的3倍。
這部分是通過你的循環來完成的
for(int x = 0; x < 25; x++)
x
是您的索引變量,每次迭代都會有另一個值。 它從0開始,以24結束(<25)。
現在你必須使用x作為你的索引並為你的值分配,前25個用索引的平方,比如
alpha[x] = x*x;
另外25個等於索引的3倍,所以你應該用x*3
分配下25 x*3
。
之后,您必須在5的循環中執行10循環,一次輸出10個條目,並輸入所有條目,即50。
希望有所幫助。
index*index
的值。 這將需要循環二十五次迭代。 3*index
的值。 這將需要循環二十五次迭代。 (提示:可以將它與前一個循環合並,給出一個25次迭代的循環。) 我的還好還是有什么辦法可以讓它更好?
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
//declare length of array and its data type
int number[] = new int[5];
int i;
System.out.println("Enter five numbers: ");
int max = number[0];
//for loop to ask user input
for(i = 0;i < number.length;i++) {
System.out.print("Number "+(i+1)+": ");
number[i] = input.nextInt();
if (number[i] > max)
max = number[i];
}
//display maximum value of array elements
System.out.println("The maximum value is: " + max);
//for loop to print list of array
for(i = 0;i<number.length;i++){
System.out.println("number["+i+"]" +" = "+ number[i]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.