有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我得到了0的位置?什么时候应该是1

我学习Java,现在我在ArrayList,我写了一些关于银行业务的方法,当我想在一个特定的分支机构添加一个新客户时,职位总是返回0。这是我所说的方法的源代码:

  • 主类中的实例:

    public static Scanner scanner = new Scanner(System.in);
    public static Bank newBank = new Bank("BMCE");
    
  • Main类(添加新客户的静态方法):

    public static void addNewCostumer(){
    System.out.println("Choose a branch :");
    String branchChoosed = scanner.nextLine();
    Branches branches = newBank.queryBranch(branchChoosed);
    if(branches == null){
        System.out.println("There are a problem, or you are entered a wrong name of branch");
    
    }
    else{
        System.out.println("Enter the name costumer :");
        String nameOfCostumer = scanner.nextLine();
        System.out.println("Enter the transaction number :");
        double transactions = scanner.nextDouble();
        scanner.nextLine();
        if(newBank.addNewCostumer(branches,nameOfCostumer,transactions)){
            System.out.println("The costumer was created in branch name :"+branches.getNameOfBranch());
    
    
        }else{
    
            System.out.println("Sorry you dindn't create a costumer in "+branches.getNameOfBranch()+" Try again please :)");
    
        }
    
    }
    
  • 银行类中的实例:

    private String name;
    private ArrayList<Branches> branchesArrayList = new ArrayList<>();
    
  • 银行类别:

    public boolean addNewCostumer(Branches nameOfExistingBranch,String nameOfNewCostumer,double newTransaction){
    int position = findBranch(nameOfExistingBranch);
    
    
    if(position<0){
        System.out.println("There is not branch with this name");
        return false;
    }
    else{
        if(this.branchesArrayList.get(position).findCostumer(nameOfNewCostumer)>=0){
            System.out.println("You have already an existing costumer with that name");
            return false;
        }
        else{
    
            this.branchesArrayList.get(position).addNewCostumer(nameOfNewCostumer,newTransaction);
            return true;
    
        }
    
    }
    
    }
    
  • 查找分支的方法:

    public int findBranch(Branches branches){
    int position = this.branchesArrayList.indexOf(branches);
    if(position>=0){
    
        return position;
    
    }
    else
        return -1;
    }
    
  • 输入:

    0-Mdiq
    1-Casa
    2-Rabat

当我向拉巴特或卡萨分行添加新客户时,该客户始终记录在Mdiq中(位置0)


共 (1) 个答案

  1. # 1 楼答案

    我在代码中发现了一个错误,所以问题就解决了。 在一个查询方法中,我编写了this.branchesArrayList.get(0);,而不是使用位置作为参数