我有一个编程I类的实验室,我们需要设计一个程序,使用一个电阻ArrayList来计算并联和串联电路的总电阻。对于并行电路,我需要将ArrayList中的每个项目更改为其倒数(1 /项目)。我达到了这一点,似乎无法找到为什么这是错误的,并且可能解决这个问题。感谢。
**我得到的错误是“类型ArrayList中的方法get(int)不适用于参数(double)”对于行“resistances = 1 / resistances.get(index);” **
-businesslogic class -
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;
}
}
-presentation class -
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();
}
}
答案 0 :(得分:1)
您的错误在setPResistance
方法中。方法arrayList.get(i)
将int
值作为参数,并向其传递位置的实际值,即double
。
要将arraylist中的每个项目替换为其倒数,请更改方法,如下所示:
public final void setPResistance(ArrayList<Double> resistances) {
for (int c = 0; c < resistances.size(); c++) {
resistances.set(c, 1/resistances.get(c));
}
}
set(int index, Double element)
方法上的Java文档:
用此替换此列表中指定位置的元素 指定的元素。