Java中的新用途(有人能告诉我为什么这不起作用吗?就像我不断收到错误一样)



有人能告诉我这在哪里不起作用吗?特别是new关键字在两种方法中的使用。

import java.util.Scanner;
public class dotPractice {
    public static void main (String args[]) {
        BankAccount b1 = new BankAccount("Ade", 500.00);
    }
    public static void BankAccount(String Password, double balance) {
        // so i created a method for a bank account
        Scanner input = new Scanner(System.in);
        String Password = input.nextLine();
        balance = input.nextDouble();
    }
}

您似乎已经将BankAccount定义为dotPractice类的静态方法,而我认为您希望将BankAccount定义为类本身:

public class BankAccount
{
    public BankAccount(String password, double balance)
    {
        //
    }
}
public class dotPractice
{
    public static void main(String[] args)
    {
        BankAccount b1 = new BankAccount("Ade", 500.00);
    }
}

BankAccount应该是一个类,而不是静态方法。

import java.util.Scanner;
public class DotPractice {
  public static void main (String args[]) {
    BankAccount b1=new BankAccount("Ade", 500.00);
  }
public class BankAccount {
  public BankAccount(String Password, double balance) {
    //so i created a method for a bank account
    Scanner input= new Scanner(System.in);
    String Password=input.nextLine();
    balance=input.nextDouble();
    }
  }
}

您不能创建新方法(新BankAccount)您需要使用构造函数创建一个名为BankAccount的新类(新的.java文件)

public class BankAccount {
     public BankAccount(String password, double balance){
         Scanner input= new Scanner(System.in);
         String Password=input.nextLine();
         balance=input.nextDouble();
     }
}

比你可以从你的主打电话

BankAccount b1=new BankAccount("Ade", 500.00);

如果你想在新的BankAccount中创建一个值为u的新对象("Ade",500.00);代码应该是这个

  public class BankAccount {
         private String password;
         private double balance;
         public BankAccount(String password, double balance){
             this.password = password;
             this.balance = balance;
         }
    }

这样做的目的是将给定字符串和余额存储在这个类(银行账户对象)的私有变量中,只有它才能访问它你可以把它设置为公共的,然后你可以在主体中写作b1.balance并获得平衡,但这是一种糟糕的编程风格。

相关内容

最新更新