[英]How to get part of array elements by user input using a loop
我正在創建一個程序,該程序需要各種雙精度數組並顯示它們。 該數組是10個元素,要求我使用循環從用戶輸入中獲取元素2到9的值。 我已經嘗試過for循環,但我只是不明白如何完成此操作。
int c;
for(c = 0; c >= 2 && c <= 9; c++){
System.out.println("Enter a value for the elements 2-9: ");
}
System.out.println(" ");
如果您具有以下Java數組:
double myarr[10];
您可以通過索引訪問數組中的元素(假設數組已填充數據)
double somenum = myarr[3]; // extracts the *fourth* element from the list
要在數組中設置值,請使用賦值運算符並指定一個值:
myarr[7] = 3.14159; // sets the *eighth* element to value '3.14159'
如果希望迭代一定范圍的數字,則可以使用for循環。 For循環具有以下格式:
for (initialization; condition; increase)
如果要打印1到10之間的所有數字,可以編寫:
for (int i=1; i<=10; i++) {
System.out.println(i);
}
訣竅是在for循環中使用變量i
,並確保循環在適當的范圍內進行迭代。 提示:您可以將i
用作數組索引。
這里有一些很好的資源:
c需要從1開始(因為您要第二個要素),然后從8停止(第九個),因此for(int c=1;c<9;c++)
應該是循環
編寫循環時,請記住;
這是一個循環和供用戶輸入的方法 :
Scanner reader = new Scanner(System.in);
for(int i=2; i<8; i++){
System.out.println("Enter Element "+i);
a=reader.nextInt();
//store "a" somewhere
}
在這里看看for循環的語法
Console console = System.console();
double arr[10];
for(int c = 1; c<10; c++){
String input = console.readLine("Enter a value for the elements 2-9: ");
arr[c] = Double.parseDouble(input);
System.out.println(arr[c]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.