这是我的代码:我在这个方法中遇到错误
public void saying(){
System.out.println("Your first gf was %s", getName());
}
.....
无法使用getName()...因为它要求将返回类型更改为Object [],而返回与Scanner对象输入类型不兼容,因为必须输入String Value .... here String temp = input.nextLine();
public class UsingManyMethodsInstances2 {
private String girlName;
public void setName(String temp){
girlName=temp;
}
public String getName(){
return girlName;
}
public void saying(){
System.out.println("Your first gf was %s", getName());
}
}
public class ManyMethodsInstances2 {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
UsingManyMethodsInstances2 manyMethodsInstances2Object = new UsingManyMethodsInstances2();
System.out.println("Enter name of first gf here: ");
String temp = input.nextLine();
manyMethodsInstances2Object.setName(temp);
manyMethodsInstances2Object.saying();
}
}
答案 0 :(得分:2)
更改
System.out.println("Your first gf was %s", getName());
到
System.out.printf("Your first gf was %s", getName());
println只接受对象或字符串。
答案 1 :(得分:0)
你的问题是System.out.println()
只接受一个参数。字符串应该与变量连接。您的saying()
方法应该是:
public void saying(){
System.out.println("Your first gf was " + getName());
}
如果您确实想使用占位符,可以使用System.out.printf()
:
public void saying(){
System.out.printf("Your first gf was %s", getName());
}
或者您也可以在String.format()
内使用println()
:
public void saying(){
System.out.println(String.format("Your first gf was {0}", getName()));
}
答案 2 :(得分:0)
您错误地使用该方法来打印连接的消息...
你可以这样做:
System.out.printf("Your first gf was %s", getName());
或
System.out.println(String.format("Your first gf was %s", getName()));
但是
`System.out.println("Your first gf was %s", getName());`
不正确,因为该方法需要仅1 参数..