[英]Java: filling a 2D array to find Power of a circuit
嗨,我正在嘗試為具有恆定電阻和增加電流的作業編寫代碼,然后計算功率。 我想將所有數據放入一個數組中,只是為了使其簡潔明了。 但是我正在努力填充它,我不知道要使用的語法,但是我想我已經初始化了數組。 老實說,任何事情都會有所幫助,謝謝!
package assignment_10_18_2018;
public class lab_10_18_2018_a {
public lab_10_18_2018_a() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
final int LENGTH_FOR_CURRENT = 11 ;
int resistance = 10 ;
int[][] circuitArray = new int [10][3];
for(int i = 0; i < 10 ; i++) {
for(int r = 0; r < ...; r++) {
circuitArray[i][r] = ...;
}
}
}
}
您必須使用簡單的 if 循環將不同的內容放在不同的列中,如下所示:
//Pseudo code
public class lab_10_18_2018_a {
public lab_10_18_2018_a() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
final int LENGTH_FOR_CURRENT = 11 ;
int resistance = 10 ;
int[][] circuitArray = new int [10][3];
for(int i = 0; i < 10 ; i++) {
for(int r = 0; r < 3; r++) {
if(r==0){ //first column
circuitArray[i][r] = i+1; //current will go from 1 to 10 in this case in the first column. Modify appropriately to suit your needs
}
else if(r==1){ //second column
circuitArray[i][r] = resistance;
}
else if(r==2){//third column
circuitArray[i][r] = circuitArray[i][r-2]*circuitArray[i][r-2]*circuitArray[i][r-1]; //Electric Power formula
}
}
}
}
}
此外,如果您遵循 Java 命名約定會更好。 您可以在https://www.oracle.com/technetwork/java/codeconventions-135099.html上閱讀更多內容
這里我們只需要 1 行,因為resistance
是恆定的(比如 10),但根據問題,我們需要將current
從 0 更改為 10。所以我們需要一個具有 1 行 11 列的數組。
int power[][] = new int[1][11];
//current increases from 0-10
int resistance = 10,i,j;
for(i=0;i<power.length;i++)
{
for(j=0;j<power[i].length;j++)
{
power[i][j] = j*j*resistance;
}
}
計算每個電流值的 power 值並將它們存儲在power
數組中。
public static void main(String[] args) {
int resistance = 10 ;
//you need 11 rows and 3 columns
int[][] circuitArray = new int [11][3];
//for each row i set first cell to i
//second cell to your constant
//third cell with callculated value (first_cell * firs_cell * second_cell)=(I*I*R)
for(int i = 0; i < 11 ; i++) {
circuitArray[i][0] = i;
circuitArray[i][1] = resistance;
circuitArray[i][2] = circuitArray[i][0] * circuitArray[i][0] * circuitArray[i][1];
}
//print header
System.out.printf("%-10s %-10s %-10s%n","I(amps)","R(ohms)","P(watts)");
//print values
for(int[] row : circuitArray){
System.out.printf("%-10d %-10d %-10d%n",row[0],row[1],row[2]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.