提问人:metamorphisis 提问时间:7/4/2020 最后编辑:bad_codermetamorphisis 更新时间:7/5/2020 访问量:58
构造函数中的 Java 参数与类修饰符的问题
Java parameter in constructor issue with class modifier
问:
我的构造函数在以下位置不断出现错误:public Customer(String initName)
a { 预期。
这是我的代码:
public class CustomerConstructorTestProgram {
public static void main(String args[]) {
Customer c1, c2, c3;
// Create Bob
c1 = new Customer("Bob");
c1.name = "Bob";
c1.age = 17;
c1.money = 10;
// Create Dottie
c2 = new Customer("Dottie");
c2.name = "Dottie";
c2.age = 3;
c2.money = 0;
// Create blank customer
c3 = new Customer("Jane");
public Customer(String initName) {
name = initName;
age = 0;
money = 0.0f;
}
System.out.println("Bob looks like this: " + c1.name + ", " +
c1.age + ", " + c1.money);
System.out.println("Dottie looks like this: " + c2.name + ", "
+ c2.age + ", " + c2.money);
System.out.println("Customer 3 looks like this: " + c3.name +
", " + c3.age + ", " + c3.money);
}
}
答:
2赞
Sagar Kulkarni
7/4/2020
#1
该类必须正确贴花(该类在代码中不存在)。您已经对公共类进行了贴贴,其中 the 变成了一个方法,而不是一个构造函数!为此,您需要创建一个单独的类或修改类名!
Customer
Customer
CustomerConstructorTestProgram
public Customer(String initName)
Customer
该类应包含成员,即在您的情况下为 3 个变量(在您的代码中再次缺失)
name, age, money
因此,我将为您提供 2 种可能的解决方案!选择您需要的使用方式。
解决方案 1:统一使用类
public class Customer
{
String name;
int age;
float money;
public Customer(String initName)
{
name = initName;
age = 0;
money = 0.0f;
}
public static void main(String args[])
{
Customer c1, c2, c3;
// Create Bob
c1 = new Customer("Bob");
c1.age = 17;
c1.money = 10;
// Create Dottie
c2 = new Customer("Dottie");
c2.age = 3;
c2.money = 0;
// Create blank customer
c3 = new Customer("Jane");
System.out.println("Bob looks like this: " + c1.name + ", " +
c1.age + ", " + c1.money);
System.out.println("Dottie looks like this: " + c2.name + ", "
+ c2.age + ", " + c2.money);
System.out.println("Customer 3 looks like this: " + c3.name +
", " + c3.age + ", " + c3.money);
}
}
解决方案 2 : 类的分离
class Customer
{
String name;
int age;
float money;
public Customer(String initName)
{
name = initName;
age = 0;
money = 0.0f;
}
}
public class CustomerConstructorTestProgram
{
public static void main(String args[])
{
Customer c1, c2, c3;
// Create Bob
c1 = new Customer("Bob");
c1.age = 17;
c1.money = 10;
// Create Dottie
c2 = new Customer("Dottie");
c2.age = 3;
c2.money = 0;
// Create blank customer
c3 = new Customer("Jane");
System.out.println("Bob looks like this: " + c1.name + ", " +
c1.age + ", " + c1.money);
System.out.println("Dottie looks like this: " + c2.name + ", "
+ c2.age + ", " + c2.money);
System.out.println("Customer 3 looks like this: " + c3.name +
", " + c3.age + ", " + c3.money);
}
}
评论
Customer
main()
Customer
Customer
java
标签信息页面以获取更多指导。CustomerConstructorTestProgram
static class Customer
Customer.java