根据用户输入搜索arraylist

时间:2018-11-27 04:53:47

标签: java

我已经做到了,但是for循环不起作用 有人会纠正吗??

package bankapp;

import java.util.ArrayList;
import java.util.Scanner;


public class BankApp {


    public static void main(String[] args) {
        ArrayList <Accounts> accounts = new ArrayList<Accounts>();
      Accounts acct = new Accounts();

      acct.setFname("Arsh");
      acct.setLname("Singh");
      acct.setId(1001);
      acct.setBalance(1232.09);
      accounts.add(acct);

      acct.setFname("Gagan");
      acct.setLname("Deep");
      acct.setId(1002);
      acct.setBalance(3500.3);
      accounts.add(acct);


      acct.setFname("love");
      acct.setLname("Deep");
      acct.setId(1003);
      acct.setBalance(3535.5);
      accounts.add(acct);

         Scanner input = new Scanner(System.in);
           System.out.println("Enter User Id");
           int id = input.nextInt();

       class SearchUser { 
          public int SearchId(int id ){

              for (Accounts account : accounts) {
                  if (account.getId() == id) {
                System.out.println("which account do you want to Access ?(S for Savings and C for checkings)");
                  }
              }
            return 0;
        }

1 个答案:

答案 0 :(得分:2)

尽管您的帖子含糊不清,但我已经可以告诉您问题是代码的这一部分:

  Accounts acct = new Accounts();

  acct.setFname("Arsh");
  acct.setLname("Singh");
  acct.setId(1001);
  acct.setBalance(1232.09);
  accounts.add(acct);

  acct.setFname("Gagan");
  acct.setLname("Deep");
  acct.setId(1002);
  acct.setBalance(3500.3);
  accounts.add(acct);


  acct.setFname("love");
  acct.setLname("Deep");
  acct.setId(1003);
  acct.setBalance(3535.5);
  accounts.add(acct);

您只有一个帐户对象,并且要将同一对象多次添加到数组中。如果您尝试打印阵列,则会得到3个“ love Deep”,因为所有先前的数据都将被覆盖。

像这样声明多个新帐户:

  Accounts acct = new Accounts();
  Accounts acct1 = new Accounts();
  Accounts acct2 = new Accounts();

  acct.setFname("Arsh");
  acct.setLname("Singh");
  acct.setId(1001);
  acct.setBalance(1232.09);
  accounts.add(acct);

  acct1.setFname("Gagan");
  acct1.setLname("Deep");
  acct1.setId(1002);
  acct1.setBalance(3500.3);
  accounts.add(acct1);


  acct2.setFname("love");
  acct2.setLname("Deep");
  acct2.setId(1003);
  acct2.setBalance(3535.5);
  accounts.add(acct2);