我仍然是java的新手并且遇到循环问题。
我试图用随机值创建一个对象。 当我在main中调用方法时,它返回无限的对象。
public class knights{
public double health;
public weapons weapons;
public double speed;
public knights(double health,int weapons, double speed){
this.health = health;
this.weapons = new weapons(weapons);
this.speed = speed;
}
public static knights choosePick(){
knights Pick = new knights((70 + (Math.random() * (130 - 70))),-1,(100 + (Math.random() * (150 - 100))));
System.out.println("The knight Pick is equipped with " + Pick.weapons.type + ". Its damages are " +Pick.weapons.atk + " It has " + Pick.weapons.acc + " accuracy " + "\n" + "He has " + Pick.health + " Health points" + "\n" + "His speed is " + Pick.speed);
return choosePick();
}
}
我想打电话给choosePick
import java.util.Scanner;
public class main_1vs1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int knight =0;
while(knight != 1 && knight !=2) {
System.out.println("which knight do you choose? Pick is fast (1), Crock is strong (2). " + "\n" + "Make your choice :" + "\n");
knight = sc.nextInt();
if (knight==1){
knights.choosePick();
break;
}
else if (knight==2){
knights.chooseCrock();
break;
}
}
}
}
如果我点击1,它将创造无数的骑士。挑选并展示无数的统计描述。
答案 0 :(得分:2)
一旦你到达这个陈述knights.choosePick();
,你就会陷入这里的递归
public static knights choosePick(){
knights Pick = new knights((70 + (Math.random() * (130 - 70))),-1,(100 + (Math.random() * (150 - 100))));
System.out.println("The knight Pick is equipped with " + Pick.weapons.type + ". Its damages are " +Pick.weapons.atk + " It has " + Pick.weapons.acc + " accuracy " + "\n" + "He has " + Pick.health + " Health points" + "\n" + "His speed is " + Pick.speed);
return choosePick();
// ^^^ calling recursion
解决方案
public static knights choosePick(){
knights Pick = new knights((70 + (Math.random() * (130 - 70))),-1,(100 + (Math.random() * (150 - 100))));
System.out.println("The knight Pick is equipped with " + Pick.weapons.type + ". Its damages are " +Pick.weapons.atk + " It has " + Pick.weapons.acc + " accuracy " + "\n" + "He has " + Pick.health + " Health points" + "\n" + "His speed is " + Pick.speed);
return Pick;
// ^^^ return object instead of calling this function again
答案 1 :(得分:1)
您会收到此行为,因为您的方法choosePick
以return choosePick()
结尾,这意味着它会调用自身以使其无穷无尽,因此您最终得到StackOverflowError
,只需替换{{} 1}}与
return
答案 2 :(得分:0)
在您的knights
课程方法choosePick
中,您不应该return choosePick()
而是return Pick;