无法弄清楚如何做这件事。我需要存储和计算"跳跃的数量" "跳跃"在数组中。 控制台必须显示如下内容:
:跳转1,向左移动
:跳2,方向右
在下面的代码中,当我打印数组元素时,int jump
总是等于0;
我尝试了很多变化,有时我得到了(例如):
jump();
jump();
jump();
jump();
它会打印:{0,0,0,4}
,而不是{1,2,3,4};
public class Jump {
int jump;
String direction;
Jump[] jumpArray = new Jump[100];
int storeJump;
String storeDirection;
public void jump() {
jump++;
if (jump > 50) {
System.out.println("need a rest");
return;
} else {
for (int i = 0; i < jumpArray.length; i++) {
jumpArray[i] = new Jump();
}
}
jumpArray[jump].storeJump = jump;
jumpArray[jump].storeDirection = direction;
}
public static void main(String[] args) {
Jump jumper = new Jump();
jumper.jump();
jumper.jump();
for (int i = 0; i < jumper.jump; i++) {
System.out.println(jumper.jumpArray[i].jump);
}
}
}
答案 0 :(得分:0)
我认为将jumpArray
移到main()
:
public class Jump {
String direction;
//int storeJump; Not sure what this is for
//String storeDirection; Or this
@Override
public String toString() {
return direction;
}
// Static function that creates an initializes a Jump object
public static Jump jump(String direction) {
Jump jump = new Jump();
jump.direction = direction;
return jump;
}
public static void main (String[] args)
{
Jump[] jumpArray = new Jump[100];
int numJumps = 0;
// A list of directions for testing
String [] path = new String[]{"north", "south", "east", "west"};
// Create a bunch of jumps
for (String dir : path) {
if (numJumps > 50) {
System.out.println("need a rest");
break;
}
// Create a new jump and add to the array
jumpArray[numJumps++] = Jump.jump(dir);
}
// Print the jumps
for (int i = 0; i < numJumps; i++) {
System.out.println(i + " " + jumpArray[i]);
}
}
}
答案 1 :(得分:0)
我认为下面的代码可以解决您的问题,但我认为您应该改进您的代码。
int jump;
String direction;
Jump[] jumpArray = new Jump[100];
int storeJump;
String storeDirection;
public void jumping() {
jump++;
if (jump > 50) {
System.out.println("need a rest");
return;
} else {
jumpArray[jump] = new Jump();
}
jumpArray[jump].storeJump = jump;
jumpArray[jump].storeDirection = direction;
}
public static void main(String[] args) {
Jump jumper = new Jump();
jumper.jumping();
jumper.jumping();
Set<Jump> mySet = new HashSet<Jump>(Arrays.asList(jumper.jumpArray));
for (int i = 1; i < mySet.size(); i++) {
System.out.println(jumper.jumpArray[i].storeJump);
}
}