gpt4 book ai didi

java - 如何在main中使用方法变量?

转载 作者:太空宇宙 更新时间:2023-11-04 13:19:23 25 4
gpt4 key购买 nike

对于我的学校,我需要创建一种将 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 + "\n\n");
move();

i++;
System.out.println("Would you like to enter another bug? \n 0-No, 1-Yes\n");
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-Yes\n");
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;
}

基本上我需要做的就是使用错误位置的值和方法中生成的随机数。我对 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-Yes\n");
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 函数,然后根据需要多次读取。

关于java - 如何在main中使用方法变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33245003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com