首页 > 解决方案 > 类中的 Java 函数不起作用

问题描述

如果这是一个非常简单的解决方法,请提前道歉。但我是 Java 世界的新手,并试图为咯咯笑创建一个简单的脚本。

我创建了一个简单的类,我在其中调用了我的 Pet 类。它包含类的简单蓝图,以及我希望能够在我的 Main 类中调用的函数。

import java.awt.*;

public class Pet {

    String petType;
    Color petColor;
    String petSound;

    public Pet(String inputType, Color inputColor, String inputSound){
        this.petType = inputType;
        this.petColor = inputColor;
        this.petSound = inputSound;
    }

    public void petSpeak(String Pet.petType){
        System.out.println(Pet.petSound + "!!");
    }
}

但是,我认为我做的不对/遗漏了什么。因为我使用的 IDE (IntelliJ) 在Pet.petType.

我的 Main 类包含以下代码:

Pet Rex = new Pet("Dog", Color.BLACK, "Woof!");
Pet Thumper = new Pet("Rabbit", Color.WHITE, "...");
Pet Jim = new Pet("Budgie", Color.YELLOW, "Cheep Cheep!");

System.out.println(petSpeak(Rex.petSound));

我要做的petSpeak是调用 when (以 petType 作为参数)。宠物的声音被打印给用户。

让这个工作的任何帮助都会很棒!

标签: javaclassintellij-idea

解决方案


更改public void petSpeak(String Pet.petType)public void petSpeak()

System.out.println(petSpeak(Rex.petSound));Rex.petSpeak();

基本上你不需要参数,void petSpeak()因为对象 Rex 已经在这里分配了这个值Pet Rex = new Pet("Dog", Color.BLACK, "Woof!");,你可以通过键入从类中调用方法objectName.methodName


推荐阅读