gpt4 book ai didi

java - 我如何知道对象实例使用什么类型的变量?

转载 作者:行者123 更新时间:2023-12-02 03:10:32 25 4
gpt4 key购买 nike

package RPG;
import java.util.Random;
import java.util.Scanner;

public class Beginnings
{
public static boid main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Pick a class:");
System.out.println("Fighter: Deals more damage");
System.out.println("Mage: Has more health");
System.out.println("Theif: Deals less damage but has more health");
String Class = scan.nextLine();
if (Class.matches(".*Fighter.*"));
Fighter user = new Fighter();
else if (Class.matches(".*Mage.*"));
Mage user = new Mage();
else if (Class.matches(".*Thief.*"));
Thief user = new Thief();
else
Human user = new Human();
user.Name();
user.Explore();

/*当我运行代码时,它突出显示第一个“用户”并显示“此处不允许变量声明” 我不知道如何解决这个问题。*/

最佳答案

您有一些拼写错误,可能会导致问题

public static boid main (String[] args)

应该是

public static void main (String[] args)

System.out.println("Theif: Deals less damage but has         more health");

应该是

System.out.println("Thief: Deals less damage but has         more health");

此外,大写的 Class() 和小写的 class 也已经存在于 Java SDK 中。您应该使用不同的变量名称。我在下面的示例中使用了 characterStr。标准实践规定,应使用驼峰命名法来命名变量,使用大写法来命名 Java 类。当实例化一个Class()对象时,人们通常将其实例化为Class clazz = new Class()

展望 future ,我认为您应该为不同的用户类创建一个 super 类。设置如下:

public abstract class Character
public class Fighter extends Character
public class Thief extends Character
public class Mage extends Character
public class Human extends Character

这样,main() 中的代码就可以使用您的 Character() 对象

public static void main(String[] args)
{
// Prompt the user for the character they want
Scanner scan = new Scanner(System.in);
System.out.println("Pick a class:");
System.out.println("Fighter: Deals more damage");
System.out.println("Mage: Has more health");
System.out.println("Theif: Deals less damage but has more health");

// Get the user's response
String characterStr = scan.nextLine();

Character user; // You might have to initialize this. Did not test
if (characterStr.matches(".*Fighter.*"))
{
user = new Fighter();
}
else if (characterStr.matches(".*Mage.*"));
{
user = new Mage();
}
else if (characterStr.matches(".*Thief.*"));
{
user = new Thief();
}
else
{
user = new Human();
}

user.Name();
user.Explore();

}

关于java - 我如何知道对象实例使用什么类型的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41109079/

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