提问人:Heisenberg RandaBhai 提问时间:4/20/2023 最后编辑:marstranHeisenberg RandaBhai 更新时间:4/20/2023 访问量:58
我正在学习java,目前是初学者。我正在尝试使用方法参数,但弹出了这个意外的错误
I'm learning java,currently a beginner.I was trying to use method parameters but this unexpected error has popped up
问:
public class MyClass {
public static void main(String[] args){
//A method is a block of code which only runs when it is called
sayHello(name:"Raj",age:20);
}
//method should be defined in the class
public static void sayHello(String name, int age){
System.out.println("Hello!");
}
}
此代码返回第 7 行的 folowwing 错误: ')' 预期 ';' 预期 “不是声明”
我原以为代码会按原样运行,但我似乎无法识别错误。
答:
1赞
ΦXocę 웃 Пepeúpa ツ
4/20/2023
#1
在 Java 中,没有命名参数,只有位置参数
所以这是无效的:
sayHello(name:"Raj",age:20);
请改为:
sayHello("Raj", 20);
0赞
RickChen
4/20/2023
#2
我复制了您的代码并运行了它。如果粘贴了完整的代码,则方法输入参数有问题。应该是 sayHello(“Raj”,20),而不是 sayHello(name:“Raj”,age:20),只是按照方法定义行参数的顺序传入实际参数,然后我注意到你的方法中的属性 name 和 age 在方法中根本没有作用。定义函数时,应确保每个形式参数都发挥作用。如果要输入姓名和年龄打印到控制台,可以参考以下代码
公共类 MyClass { public static void main(String[] 参数){
//A method is a block of code which only runs when it is called
sayHello("Raj",20);
}
//method should be defined in the class
public static void sayHello(String name, int age){
// output the name and its age
System.out.println("Hello!,name:"+name+",age:"+age);
}
}
评论
name:
age:
sayHello("Raj", 20);
name
age