【问题标题】:Difficulty with displaying array data in java在java中显示数组数据的困难
【发布时间】:2022-01-13 03:14:58
【问题描述】:

我正在自学 Java,并使用 Quentin Charatan 和 Aaron Kans 的《Java in Two Sesesters》一书。 我目前正在阅读关于类和对象的章节,我在解决练习题的最后一部分时遇到了困难。 我对对象、类和数组有基本的了解。 我还没有读过关于收藏的文章 我会非常感谢这里的一些帮助。提前致谢。

问题:设计并实现一个按以下方式执行的程序:

  1. 程序启动时,会创建两个银行帐户,使用名称和 写入代码的数字。
  2. 然后要求用户输入帐号,然后输入金额 存入该帐户。
  3. 然后相应地更新相应帐户的余额 — 或者如果 输入了错误的帐号,因此会显示一条消息。
  4. 然后询问用户是否希望进行更多存款。
  5. 如果用户回答确实希望进行更多存款,则流程继续。
  6. 如果用户不希望进行更多存款,则两个帐户的详细信息 (帐号、账户名称和余额)显示

作者提供了一个 BankAccount 类文件,我必须使用它来创建银行账户以及该类中提供的存款和获取余额的方法。 我在这里提供我尝试的代码

import java.util.Scanner;
 
public class ProgEx4
{
public static void main(String[] args)
  {
      int choice;
      Scanner keyboard = new Scanner(System.in);
    do
    { // Create a MENU system for user to choose options 
      System.out.println();
      System.out.println("Welcome to Bank Accounts");
      System.out.println("MENU");
      System.out.println("[1] Deposit Amount");
      System.out.println("[2] Exit");
  
      // User can enter choice here
      System.out.print("What would you like to do today? : ");
      choice = keyboard.nextInt();
  
      // switch used to process choice entered by user
      switch(choice)
      {
        case 1: deposit(); // this will go to the deposit method 
                break;
        case 2: break;    // this will exit the program 
        default: System.out.println("Invalid Choice"); // if user enters an invalid choice this will allow another attempt at entering choice
                 System.out.print("Please enter a option ( 1 or 2): ");
                 choice = keyboard.nextInt();
      }
      }while(choice != 2); // the loop will go on till user chooses to exit
   }
      static void deposit() // created a method which takes no values and also returns no values
      {
  
      Scanner keyboard = new Scanner(System.in);
      BankAccount[] account = new BankAccount[2];        // created an array account[] using the BankAccount class provided by book
  
      account[0] = new BankAccount("88","John Smith");   // filled the array as required by the BankAccount class constructor
      account[1] = new BankAccount("99","Robert Jones"); // passing to string values containing account number and account name 
  
      System.out.print("Enter the account number: ");    // ask user to enter the account number        
      String accNum = keyboard.nextLine();               // declare a String variable 'accNum' to take account number from user
  
      String num0 = account[0].getAccountNumber();       // access the account numbers held in the account array 
      String num1 = account[1].getAccountNumber();       // using two string variables num0 and num1 to hold these strings
  
      if(accNum.equals(num0))                        // compare two strings accNum and num0 to confirm account number entered by user is correct
      {
        System.out.print("How much would you like to deposit: ");  // user will deposit here
        double depositAmount = keyboard.nextDouble();              // created a double variable depositAmount to take entered amount
  
        account[0].deposit(depositAmount);                         // using BankAccount class deposit method to enter amount into account
        System.out.println("The current balance is " + account[0].getBalance());  // using BankAccount class getBalance method to get Balance
      }
      else if(accNum.equals(num1))       // same as above for account[0] on line 48 but this time for account[1]
      {
        System.out.print("How much would you like to deposit: ");
        double depositAmount = keyboard.nextDouble();
        account[1].deposit(depositAmount);
        System.out.println("The current balance is " + account[1].getBalance());
      }
      }
   /*
      {    
  
        System.out.println("The Account belonging to " + account[0].getAccountName() + " with Account Number " + account[0].getAccountNumber());
        System.out.println(" has the balance: " + account[0].getBalance());
  
  
        System.out.println("The Account belonging to " + account[1].getAccountName() + " with Account Number " + account[1].getAccountNumber());
        System.out.println(" has the balance: " + account[1].getBalance());
        
      }
  
      */
  
  }
  

BankAccount 类文件在下面

   
   
   public class BankAccount
   {
   // the attributes
   private String accountNumber;
   private String accountName;
   private double balance;
   
  // the methods
  
  // the constructor
  public BankAccount(String numberIn, String nameIn)
  {
  accountNumber = numberIn;
  accountName = nameIn;
  balance = 0;
  }
  
  // methods to read the attributes
  public String getAccountName()
  {
  return accountName;
  }
  
  public String getAccountNumber()
  {
  return accountNumber;
  }
  
  public double getBalance()
  {
  return balance;
 }
  
  // methods to deposit and withdraw money
  public void deposit(double amountIn)
  {
  balance = balance + amountIn;
  }
  public boolean withdraw(double amountIn)
  {
      if(amountIn > balance)
      {
        return false; // no withdrawal was made
      }
      else
      {
    balance = balance - amountIn;
    return true; // money was withdrawn successfully
  }
    }
  }
  

当用户请求退出程序时,我不知道如何发送 account[] 数组以在 main 方法中打印,因为我不知道它是什么类型的数组。我想知道如何将此数组发送到 main 方法。

【问题讨论】:

  • 请不要发布带有行号的代码,因为这会使其他 SO 用户难以复制和测试您的代码。
  • 对不起,我现在会正确发帖
  • 不要在存款方式中创建账户,而是在main中。通过正确号码的账户进行存款。
  • 感谢您的帮助。要将帐户发送到 deposit 方法,我需要知道我不知道的类型,因为我还没有创建 BankAccount 类。我不知道类型是String,double还是.....
  • “你不知道它的类型”是什么意思?您创建 BankAccounts,它们会是什么其他类型?

标签: java arrays class


【解决方案1】:

您可以将 accountArray 定义为类静态变量,而不是 deposit 方法中的成员变量。 然后你可以在类加载的时候初始化这个静态变量。

【讨论】:

  • 我的书还没到静态或类变量的阶段,不过谢谢我现在就去查一下试试。问候
  • 为什么要让事情变得过于复杂。只需在 main() 方法中定义数组并将其传递到 deposit() 方法即可。
  • 是的,这就是我现在正在做的事情。感谢您的回复。
【解决方案2】:

如果您询问如何显示数组的内容,一个简单的方法是使用默认的 Arrays#toString(arr) 方法。

int[] arr   = {1, 2, 3, 4, 5};
String str1 = java.util.Arrays.toString(arr);

StringBuilder[] strings = {new StringBuilder("Hello, Java"), new StringBuilder(":)")};
String str2             = java.util.Arrays.toString(strings);

System.out.printf(%s%n%s, str1, str2);

我还强烈建议您学习如何覆盖您的类的 toString() 方法:这样,您可以获得更易于理解的字符串来打印。

public class BankAccount {
  .. all of your other methods here.

  @Override
  public String toString() {
    return String.format("%s's Bank Account [#%s] has a balance of %f", this.getAccountName(), this.getAccountNumber(), this.getAccountBalance());
  }
}

在您的 main 方法中,或者您调用打印帐户对象的任何地方,您可以简单地编写 System.out.print(yourAccountObject) 本身,而无需处理字符串格式或任何特殊的事情。

希望这有帮助! :)

【讨论】:

  • 非常感谢您的回复。我还没有达到 Arrays#toString(arr) 方法或 String Builder 方法。但我确实明白你在说什么,我会阅读它然后尝试这个。
【解决方案3】:

所以我在评论中的意思是这样的。

class ProgEx4 {
  public static void main(String[] args) {
    // create an array with two accounts
    BankAccount[] accounts = new BankAccount[2];
    // fill the array with your account objects
    accounts[0] = new BankAccount("88","John Smith");
    accounts[1] = new BankAccount("99","Robert Jones");

    String accountNumber = readAccountNumber();
    double depositAmount = readAmount();

    BankAccount depositTo = findAccountWithNumber(accountNumber, accounts);
    depositTo.deposit(depositAmount);
  }

  // TODO:

  // returns the account with the given number in the given array
  private static BankAccount findAccountWithNumber(String number, BankAccount[] searchIn) { ...  }
  private static String readAccountNumber() { ... }
  private static double readAmount() { ... }
}

findAccountWithNumber本质上只是迭代数组,直到找到具有给定号码的帐户。如果不存在此类帐户,您还必须包含逻辑,但两者都是很好的做法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    相关资源
    最近更新 更多