【发布时间】:2015-04-17 05:37:36
【问题描述】:
我的编程 I 课程有一个实验室,我们需要设计一个程序,该程序使用电阻的 ArrayList 来计算并联和串联电路的总电阻。对于并联电路,我需要将 ArrayList 中的每个项目更改为其倒数(1/项目)。我到了这一点,似乎无法找到为什么这是错误的以及可能的解决方法。谢谢。
**我得到的错误是“ArrayList 类型中的方法 get(int) 不适用于参数 (double)”,用于“resistances = 1 / resistances.get(index);”行**
-业务逻辑类-
import java.util.ArrayList;
/**
* The class Circuit gathers the resistances of a user-defined number of
* resistors for a user-defined type of circuit and displays the total
* resistance of the circuit for the main method of the Presentation class.
*/
public class Circuit {
private double arrayListSize;
public double n;
public double sum;
public double finalSum;
public ArrayList<Double> resistances = new ArrayList<Double>();
/**
* @param initialPop
* user-defined initial population
*/
public final void setArraySize(final double alSize) {
arrayListSize = alSize;
}
public final double getArraySize() {
return arrayListSize;
}
public final void setResistors(double alResistances) {
for (n = 0; n < getArraySize(); n++) {
resistances.add(alResistances);
}
}
public ArrayList<Double> getResistors() {
return resistances;
}
public final void setPResistance(ArrayList<Double> resistances) {
for (double index : resistances) {
resistances = 1 / resistances.get(index);
}
sum = 0;
for (double i : resistances) {
sum =sum + i;
}
double finalSum = 1 / sum;
}
public final double getPResistance() {
return finalSum;
}
}
-演示类-
import java.util.Scanner;
/**
* The Class Presentation
*/
public class Presentation {
/**
* The main class uses the Circuit class and user input
* to calculate the total resistance of a circuit.
*
* @param args
* command line arguments
*/
public static void main(final String[] args) {
Scanner keyboard = new Scanner(System.in);
Circuit resistanceTotal = new Circuit();
System.out.println("This program will calculate the"
+ " total resistance of either a parallel or "
+ " a series circuit.\n");
System.out.println("Would you like to calculate the"
+ " resistance of a parallel circuit (1) or a"
+ " series circuit (2)?");
int userChoice = keyboard.nextInt();
System.out.println("How many resistors are there in the circuit?");
resistanceTotal.setArraySize(keyboard.nextDouble());
System.out.println("Enter resistance of resistor #" + (resistanceTotal.n + 1));
resistanceTotal.setResistors(keyboard.nextDouble());
resistanceTotal.getResistors();
if (userChoice == 1) {
resistanceTotal.setPResistance(resistanceTotal.getResistors());
resistanceTotal.getPResistance();
}
if (userChoice != 1 & userChoice != 2) {
System.out.println("You must enter 1 or 2!!!");
}
keyboard.close();
}
}
【问题讨论】:
-
您的问题到底是什么?请发布任何异常或不正确的输出
-
**我得到的错误是“ArrayList 类型中的方法 get(int) 不适用于参数 (double)”,用于“resistances = 1 / resistances.get(index)”行;" **
-
好的,那么您希望将数组列表中的每个值替换为其倒数吗?
-
是的,这正是我想要的。