对于我的学校,我需要创建一个在任何方向移动bug的方法。我有以下代码:
package Test;
//imports
import java.util.Scanner;
import java.util.Random;
public class test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ABug[] BugObj = new ABug[4]; //Creating object BugObj of class ABug
int loop = 1;
int i = 0;
do {
BugObj[i] = new ABug(); //creating instance
System.out.println("Please enter the name of the bug:");
BugObj[i].name = reader.next();
System.out.println("Please enter the species of the bug:");
BugObj[i].species = reader.next();
System.out.println("Please enter the horizontal position of the bug:");
BugObj[i].horpos = reader.nextInt();
System.out.println("Please enter the vertical postion of the bug:");
BugObj[i].vertpos = reader.nextInt();
System.out.println("_______________ Bug " +(+i+1) + " _______________n" );
System.out.println("Name: " + BugObj[i].name); //Printing bug information out
System.out.println("Species: " + BugObj[i].species);
System.out.println("Horizontal Position: " + BugObj[i].horpos);
System.out.println("Vertical Postion: " + BugObj[i].vertpos + "nn");
move();
i++;
System.out.println("Would you like to enter another bug? n 0-No, 1-Yesn");
loop = reader.nextInt();
} while(loop == 1);
}
public static void move() {
Scanner reader = new Scanner(System.in);
System.out.println("Would you like this bug to move?n 0-No, 1-Yesn");
if (reader.nextInt() == 0) {
System.exit(0);
}
int r = (int) (Math.random() * (2- -2)) + -2;
System.out.println(r);
}
}
class ABug { //ABug class
int horpos, vertpos, energy, id;
char symbol;
String species, name;
}
基本上,我需要做的就是使用方法中生成的随机数和bug位置的值。我真的是新的java和不确定如何做到这一点,甚至如果它是可能的。
由于对象在java中是通过引用传递的,因此您可以将ABug对象传递给move函数并更改horpos, vertpos属性。所以
move(BugObj[i]);
和
public static void move(ABug bug){
Scanner reader = new Scanner(System.in);
System.out.println("Would you like this bug to move?n 0-No, 1-Yesn");
if (reader.nextInt() == 0)
{
System.exit(0);
}
int r = (int) (Math.random() * (2- -2)) + -2;
int originalHorpos = bug.horpos
int originalVertpos = bug.vertpos
// Now just change the attributes however you see fit. i am just adding r
bug.horpos = originalHorpos + r;
bug.vertpos = originalVertpos + r
/*by the way, we dont need to use variables for the original values. something like this would also work
bug.horpos += r;
bug.vertpos += r;
i just want to explain that in java when you pass objects, they are passed by reference and hence you have access to all of its members.
*/
System.out.println(r);
}
也不需要在move函数中再次声明Scanner对象。您也可以将其传递给move函数,然后根据您的需要读取多少次