java - 类中的 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 作为参数)。宠物的声音被打印给用户。
让这个工作的任何帮助都会很棒!
解决方案
更改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
推荐阅读
- php - 将中间件传递给控制器返回错误
- python - 从私人 Git 存储库进行 Pip 安装,在 Git URL 中使用个人访问令牌
- javascript - 如何从地图中删除特定值
- python - python,分解成多个mixin
- python - 如何从数据集中行的唯一值创建新列
- stored-procedures - Redshift 存储过程 - [Amazon](500310) 无效操作:“$1”处或附近的语法错误;
- android - 如何在导入的 jar 中使用类?
- javascript - Fullcalendar 通过点击月份时间周等获取当前视图
- python - AWS Lambda 导入模块失败
- spring-boot - 使用reactivemongodb查询mongodb集合SpringWebFlux