[英]How do I make an IF statement that compares 2 integers assigned to 2 string variables in 1 class then execute the code in another class in Java?
I have these 2 string variables, Hulk
and Thing
, Hulk
has a strength of 10
and Thing
has a strength of 53
, they both fight (the IF statement) where the higher integer strength wins. 我有这两个字符串变量,
Hulk
和Thing
, Hulk
的强度为10
, Thing
的强度为53
,它们都在较高的整数强度取胜的情况下进行战斗(IF语句)。
Then Hulk received a powerup boosting his strength to 110, now both fight again. 然后,绿巨人获得了一次能量提升,将自己的力量提高到110,现在双方都再次战斗。 The winner's name is printed on the screen both times.
两次都将获奖者的名字打印在屏幕上。
I have 2 classes (a main class
and a supporting one
). 我有2个班级(
main class
和supporting one
main class
)。 The IF statement of my supporting class is attached along with my getStrength()
method (if anymore code is needed let me know). 我的支持类的IF语句与
getStrength()
方法一起附加(如果需要更多代码,请告诉我)。
I am getting an error
where is says: if (name1.getStrength() > name2.getStrength()) ;
我在哪里说了一个
error
: if (name1.getStrength() > name2.getStrength()) ;
the error is that getStrength()
isn't defined for string where name1
and name2
are. 错误是没有为
name1
和name2
所在的字符串定义getStrength()
。
Also, after solving this, how do I call this subroutine
in my main class
? 另外,解决了这个问题之后,如何在
main class
调用此subroutine
? Thanks in advance! 提前致谢!
IF Statement: IF声明:
if (name1.getStrength() > name2.getStrength())
{
System.out.println(name1 + " Wins!");
}
else {
System.out.println(name2 + " Wins!");
}
getStrength method: getStrength方法:
int getStrength() {
return this.strength;
}
You need to make the characters as objects of class that has properties like name, strength, etc. 您需要将字符作为具有名称,强度等属性的类的对象。
Then this thing should work : if (Hulk.getStrength() > Thing.getStrength())
然后这件事应该起作用:
if (Hulk.getStrength() > Thing.getStrength())
Firstly you should read about java first steps. 首先,您应该阅读有关Java的第一步。 But in your app, you should create class which is representing your fighters and in this class create methods which get the strength from it, ie:
但是,在您的应用程序中,您应该创建代表您的战斗机的类,并在该类中创建从中获得力量的方法,即:
public class Fighter {
private String name;
private int strenght;
public int getStrength() {
return strength;
}
}
of course you need to create constructor or other setters/getters in this class. 当然,您需要在此类中创建构造函数或其他setter / getter。 Then you can create objects, ie:
然后,您可以创建对象,即:
Fighter hulk = new Fighter();
Fighter thing = new Fighter();
// use constructor or setters to set strength and name
Now you can call method from class Fighter: 现在您可以从Fighter类中调用方法:
if(hulk.getStrength() > thing.getStrength()) {
// your code
}
Your error is because you were trying to call getStrength()
method on object of String
type. 您的错误是因为您试图在
String
类型的对象上调用getStrength()
方法。 The best way is to create your own type. 最好的方法是创建自己的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.