在我的AP计算机科学课上,我们正在开发一个实验室,让我们创建一系列具有参数高度,重量和年龄的怪物对象。我们需要打印出Array,打印出最大和最小的数组,然后对数组进行排序。我正在努力比较两个物体的高度。而不是返回对象,它返回null。这是我的主要类文件。
package lab64;
import static java.lang.Integer.parseInt;
import java.util.Arrays;
import javax.swing.JOptionPane;
public class Monsterz
{
static String MONSTER;
static Monster MONSTERS[];
static int HT;
static int WT;
static int AGE;
/* public Monsterz(int ht, int wt, int age)
{
} */
public static void main(String[] args)
{
MONSTER = JOptionPane.showInputDialog("Input number of monsters in the herd ::");
int len = parseInt(MONSTER);
MONSTERS = new Monster[len];
for (int i = 0; i <= MONSTERS.length - 1; i++)
{
String Height = JOptionPane.showInputDialog("Input Ht ::");
String Weight = JOptionPane.showInputDialog("Input Wt ::");
String Age = JOptionPane.showInputDialog("Input Age ::");
HT = parseInt(Height);
WT = parseInt(Weight);
AGE = parseInt(Age);
MONSTERS[i] = new Monster(HT,WT,AGE);
}
JOptionPane.showMessageDialog(
null,
"HERD :: " + Arrays.toString(MONSTERS) + "\nLARGEST :: " + getLargest(),
"Monster Lab",
JOptionPane.PLAIN_MESSAGE);
}
public static Monster getLargest()
{
Monster largest = null;
for(int c = 0; c > MONSTERS.length; c++)
{
if (MONSTERS[c].getHeight() > MONSTERS[c+1].getHeight())
{
largest = MONSTERS[c];
}
}
return largest;
}
}
这是Monster类文件
package lab64;
class Monster {
int ht = 0;
int wt = 0;
int age = 0;
Monster(int HT, int WT, int AGE)
{
ht = HT;
wt = WT;
age = AGE;
}
public int getHeight()
{
return ht;
}
public int getWeight()
{
return wt;
}
public String toString()
{
return ht + " " + wt + " " + age;
}
}
如何解决此问题以使其有效?
答案 0 :(得分:2)
纠正你的状况。
更改for(int c = 0; c > MONSTERS.length; c++)
到
for(int c = 0; c < MONSTERS.length; c++)
同样纠正找到数组中最大元素的逻辑:
Monster largest = MONSTERS[0];
for(int c = 0; c < MONSTERS.length; c++)
{
if (largest.getHeight() > MONSTERS[c].getHeight())
{
largest = MONSTERS[c];
}
}