为什么我的位置是0?何时应为1

时间:2019-06-20 00:02:47

标签: java arraylist position indexof autoboxing

我学习Java,现在我在ArrayList上,我写了一些有关银行业务的方法,当我想在特定分支添加新客户时,该位置总是返回0。这是我所用方法的源代码在谈论:

  • Main类中的实例:

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

    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或Casa分支添加新客户时,该客户总是记录在Mdiq(位置0)中。

1 个答案:

答案 0 :(得分:0)

对不起,我发现我的代码中有一个错误,因此问题已解决,谢谢 在查询方法中,我被写道 this.branchesArrayList.get(0); 而不是使用位置作为参数