我正在尝试创建一个整数值的数组列表并运行一些基本的数学运算,如下所示。
int dice1 = 4;
int dice2 = 3;
int dice3 = 6;
int dice4 = 4;
int dice 5 = 5;
ArrayList numbers = new ArrayList();
numbers[4] = dice5;
numbers[3] = dice4;
numbers[2] = dice3;
numbers[1] = dice2;
numbers[0] = dice1;
numbers[3] = numbers[3] * numbers[2];
但是,计算机不允许我这样做并产生错误“运算符”*“不能应用于'对象'和'对象'类型的操作数”。我该如何解决?我认为我必须将数组列表定义为整数数组...但是我不太确定。请保持答案简单,因为我对C#unity来说很陌生。
谢谢!
答案 0 :(得分:2)
ArrayList将所有内容存储为“对象”,基本上是C#中最基本的类型。你有几个选择。如果你想继续使用ArrayList,那么你需要做你正在成倍增加的东西,比如:
numbers[3] = ((int)numbers[3]) * ((int)numbers[2])
或者,您可以抛弃ArrayList并使用更现代的List<>类型。您需要将using System.Collections.Generic
添加到顶部,然后您的代码将如下:
int dice1 = 4;
int dice2 = 3;
int dice3 = 6;
int dice4 = 4;
int dice5 = 5;
List<int> numbers = new List<int>(); //List contains ints only
numbers[4] = dice5;
numbers[3] = dice4;
numbers[2] = dice3;
numbers[1] = dice2;
numbers[0] = dice1;
numbers[3] = numbers[3] * numbers[2]; //Works as expected
最后,如果你知道你的收藏只有一定数量的东西,你可以使用数组。您的代码现在将是:
int dice1 = 4;
int dice2 = 3;
int dice3 = 6;
int dice4 = 4;
int dice5 = 5;
int[] numbers = new int[5]; //Creates an int array with 5 elements
//Meaning you can only access numbers[0] to numbers[4] inclusive
numbers[4] = dice5;
numbers[3] = dice4;
numbers[2] = dice3;
numbers[1] = dice2;
numbers[0] = dice1;
numbers[3] = numbers[3] * numbers[2]; //Works as expected
答案 1 :(得分:0)
避免使用数组列表
使用List<int>
或int[]
然后输入包含的对象而不是对象
答案 2 :(得分:0)
您可以在一行中完成:
public class Animation implements Runnable {
private volatile boolean running;
private final SolarSystemGUI frame;
private final SolarSystemModel model;
public Animation(SolarSystemGUI frame, SolarSystemModel model) {
this.frame = frame;
this.model = model;
this.running = true;
}
@Override
public void run() {
sleep(5000L);
long duration = 1000L / model.getFramesPerSecond();
while (running) {
List<Body> bodies = model.getBodies();
Point center = null;
for (Body body : bodies) {
if (center != null) {
body.setCenter(center);
}
center = body.getOrbitPoint();
}
repaint();
sleep(duration);
}
}
private void sleep(long duration) {
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void repaint() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame.repaint();
}
});
}
public synchronized void setRunning(boolean running) {
this.running = running;
}
}
答案 3 :(得分:-1)
您需要将对象解析为字符串,然后解析为int值,然后将其与*运算符配合使用。但是,您首先必须使用空值初始化arraylist,然后分配数字值,这样, 使用以下代码,我为您做了明确的更改。
int dice1 = 4;
int dice2 = 3;
int dice3 = 6;
int dice4 = 4;
int dice5 = 5;
int capacity=5;
ArrayList numbers = new ArrayList(capacity);
for (int i = 0; i < capacity;i++ )
{
numbers.Add(null);
}
numbers[4] = dice5;
numbers[3] = dice4;
numbers[2] = dice3;
numbers[1] = dice2;
numbers[0] = dice1;
numbers[3] = (int.Parse(numbers[3].ToString()) * int.Parse(numbers[2].ToString()));
print(numbers[3]);