2015-06-14 5 views
-1

Я пытаюсь создать банкомат, способный внести депозит, вывод и показать баланс, но моя проблема возникает, когда я пытаюсь сделать свою 11-ю транзакцию (размер моих транзакционных записей равен 10).Ошибка Java ATM arrays

Вот как программа должна работать:

Earlier transactions: 

===================== 

1 

2 

3 

4 

5 

6 

7 

8 

9 

10 

======================= 

Balance: 55 KR 

Earlier transactions: 

===================== 

2 

3 

4 

5 

6 

7 

8 

9 

10 

11 

======================= 

Balance: 65 KR 

я должен использовать эти методы и не полностью переведены на программу на английском языке.

import java.util.Scanner; 

public class Bankomat 
{ 
    public static void main(String[] args) 
    { 
     Scanner in = new Scanner(System.in); 

     // Declarer variables 
     int[] trans = new int[10]; 
     int amount = 0; 
     int balance = 0; 
     int sum = 0; 
     int theChoice = 1; 

     while(theChoice != 4) 
     { 
      theChoice= menu(); 
      switch(theChoice) 
      { 
      case 1: 
       System.out.println("\nDu valde \"deposit\""); 

       System.out.print("\nState the value you want to take in: "); 
       sum = in.nextInt(); 

       if(sum == 0) 
       { 
        System.out.print("\nYou have given are wrong value.\n"); 
       } 
       else 
       { 
        amount = (int) + sum; 
        makeTransactions(trans,amount); 
       } 

       break; 

      case 2: 
       System.out.println("\nDu valde \"withdrawal\""); 

       System.out.print("\nState the value you want to take in: "); 
       sum = in.nextInt(); 

       if(sum == 0) 
       { 
        System.out.print("\nDu har angett ett felaktigt belopp.\n"); 
       } 
       else 
       { 
        amount = (int) - sum; 
        makeTransactions(trans,amount); 
       } 

       break; 

      case 3: 
       System.out.println("\nDu valde \"Balance\""); 
       showTransactions(trans,balance); 
       break; 
      case 4: 
       System.out.println("\nDu valde \"Quit\""); 
       break; 
      } 
     } 
    } 

    /** 
    * MENU 
    * @return val skickar tillbaka input värdet 
    */ 
    public static int menu() 
    { 
     Scanner in = new Scanner(System.in); 

     int choice = 0; 

     // Den här delen kommer att skriva ut menu 
     System.out.println("1. deposit"); 
     System.out.println("2. withdrawal"); 
     System.out.println("3. Balance");     
     System.out.println("4. Quit");         
     System.out.print("Your choice: "); 

     choice = in.nextInt(); 

     return choice; 
    } 

    /** 
    * This method will sum up all the ten latest transaction and show the balance 
    * @param trans array that saves the latest transactions 
    * @param balance Int that sums up all the values 
    */ 
    public static void showTransactions(int[] trans, int balance) 
    { 
     System.out.println(); 
     System.out.println("Tidigare transaktioner: "); 
     System.out.println("-------------------------------------------\n"); 

     for(int i = 0; i < trans.length; i++) 
     { 
      if(trans[i] == 0) 
      { 
       System.out.print(""); 
      } 

      else 
      { 
       System.out.print(trans[i] + "\n"); 
       balance = balance + trans[i]; 
      } 
     } 
     System.out.println("-------------------------------------------\n"); 
     System.out.println("Saldo: " + balance + "KR" + "\n"); 
    } 

    /** 
    * This method saves the latest transaction 
    * @param trans array that saves the latest transactions 
    * @param amount int that saves the latest transaction 
    */ 
    public static void makeTransactions(int[] trans, int amount) 
    { 
     int position = findNr(trans); 
     if(position == -1) 
     { 
      moveTrans(trans); 
     } 
     else 
     { 
      trans[position] = amount; 
     } 
    } 

    /** 
    * This metod will look for a empty position 
    * @param trans array that saves the latest transactions 
    * @return position 
    */ 
    private static int findNr(int[] trans) 
    { 
     int position = -1; 

     for(int i = 0; i < trans.length; i++) 
     { 
      if (trans[i] == 0) 
      { 
       position = i; 
       break; 
      } 
     } 
     return position; 
    } 

    /** 
    * This method will move the transaction 
    * @param trans array that saves the latest transactions 
    */ 
    private static void moveTrans(int[] trans) 
    { 
     for(int i = 0; i < trans.length; i++) 
     { 
      trans[0] = trans[i + 1]; 
     } 
    } 
} 

EDIT:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 
    at stackOverflow.Testing.Bankomat.moveTrans(Bankomat.java:171) 
    at stackOverflow.Testing.Bankomat.makeTransactions(Bankomat.java:135) 
    at stackOverflow.Testing.Bankomat.main(Bankomat.java:41) 

Линия 171:

private static void moveTrans(int[] trans) 
{ 
    for(int i = 0; i < trans.length; i++) 
    { 
     trans[0] = trans[i + 1]; // This is line 171 
    } 
} 
+0

Что ваша ошибка? Можете ли вы быть более конкретным? 'ArrayIndexOutOfBoundsException'? – Gosu

+0

Так что это ** ArrayIndexOutOfBoundsException ** внутри 'moveTrans()' .. – Gosu

ответ

0

Обновленный код:

import java.util.Scanner; 

public class Bankomat 
{ 
    public static void main(String[] args) 
    { 
     Scanner in = new Scanner(System.in); 

     // Declarer variables 
     int[] trans = new int[10]; 
     int amount = 0; 
     int balance = 0; 
     int sum = 0; 
     int theChoice = 1; 

     while(theChoice != 4) 
     { 
      theChoice = menu(); 
      switch(theChoice) 
      { 
      case 1: 
       System.out.println("\nDu valde \"deposit\""); 
       System.out.print("State the value you want to take in: "); 
       sum = in.nextInt(); 

       if(sum == 0) 
       { 
        System.out.print("\nYou have given are wrong value.\n"); 
       } 
       else 
       { 
        amount = (int) + sum; 
        makeTransactions(trans, amount); 
       } 

       break; 

      case 2: 
       System.out.println("\nDu valde \"withdrawal\""); 
       System.out.print("\nState the value you want to take in: "); 
       sum = in.nextInt(); 

       if(sum == 0) 
       { 
        System.out.print("\nDu har angett ett felaktigt belopp.\n"); 
       } 
       else 
       { 
        amount = (int) - sum; 
        makeTransactions(trans, amount); 
       } 

       break; 

      case 3: 
       System.out.println("\nDu valde \"Balance\""); 
       showTransactions(trans,balance); 
       break; 
      case 4: 
       System.out.println("\nDu valde \"Quit\""); 
       break; 
      } 
     } 
    } 

    /** 
    * MENU 
    * @return val skickar tillbaka input värdet 
    */ 
    public static int menu() 
    { 
     Scanner in = new Scanner(System.in); 
     int choice = 0; 

     // Den här delen kommer att skriva ut menu 
     System.out.print("\n1. Deposit\t"); 
     System.out.print("2. Withdrawal\t"); 
     System.out.print("3. Balance\t");     
     System.out.println("4. Quit");         
     System.out.print("Your choice: "); 

     choice = in.nextInt(); 
     return choice; 
    } 

    /** 
    * This method will sum up all the ten latest transaction and show the balance 
    * @param trans array that saves the latest transactions 
    * @param balance Int that sums up all the values 
    */ 
    public static void showTransactions(int[] trans, int balance) 
    { 
     System.out.println(); 
     System.out.println("Tidigare transaktioner: "); 
     System.out.println("-------------------------------------------\n"); 

     for(int i = 0; i < trans.length; i++) 
     { 
      if(trans[i] == 0) 
      { 
       System.out.print(""); 
      } 

      else 
      { 
       System.out.print(trans[i] + "\n"); 
       balance = balance + trans[i]; 
      } 
     } 
     System.out.println("-------------------------------------------\n"); 
     System.out.println("Saldo: " + balance + "KR" + "\n"); 
    } 

    /** 
    * This method saves the latest transaction 
    * @param trans array that saves the latest transactions 
    * @param amount int that saves the latest transaction 
    */ 
    public static void makeTransactions(int[] trans, int amount) 
    { 
     int position = findNr(trans); 
     if(position == -1) 
     { 
      moveTrans(trans); 
      trans[trans.length - 1] = amount; 
     } 
     else 
     { 
      trans[position] = amount; 
     } 
    } 

    /** 
    * This metod will look for a empty position 
    * @param trans array that saves the latest transactions 
    * @return position 
    */ 
    private static int findNr(int[] trans) 
    { 
     int position = -1; 

     for(int i = 0; i < trans.length; i++) 
     { 
      if (trans[i] == 0) 
      { 
       position = i; 
       break; 
      } 
     } 
     return position; 
    } 

    /** 
    * This method will move the transaction 
    * @param trans array that saves the latest transactions 
    */ 
    private static void moveTrans(int[] trans) 
    { 
     for(int i = 0; i < (trans.length - 1); i++) 
     { 
      trans[i] = trans[i + 1]; 
     } 
    } 
} 

Изменения:

  • Обновлено moveTrans() с правильной логикой
    • i < (trans.length - 1) и trans[i] = trans[i + 1];
  • Обновлено makeTrans() таким образом, что он вставляет сделку в правильном положении, когда массив заполнен
    • trans[trans.length - 1] = amount;

ввода/вывода:

1. Deposit 2. Withdrawal 3. Balance 4. Quit 
Your choice: 1 

Du valde "deposit" 
State the value you want to take in: 10 

1. Deposit 2. Withdrawal 3. Balance 4. Quit 
Your choice: 1 

Du valde "deposit" 
State the value you want to take in: 20 

1. Deposit 2. Withdrawal 3. Balance 4. Quit 
Your choice: 1 

Du valde "deposit" 
State the value you want to take in: 30 

1. Deposit 2. Withdrawal 3. Balance 4. Quit 
Your choice: 3 

Du valde "Balance" 

Tidigare transaktioner: 
------------------------------------------- 

10 
20 
30 
------------------------------------------- 

Saldo: 60KR 


1. Deposit 2. Withdrawal 3. Balance 4. Quit 
Your choice: 1 

Du valde "deposit" 
State the value you want to take in: 40 

1. Deposit 2. Withdrawal 3. Balance 4. Quit 
Your choice: 3 

Du valde "Balance" 

Tidigare transaktioner: 
------------------------------------------- 

20 
30 
40 
------------------------------------------- 

Saldo: 90KR 


1. Deposit 2. Withdrawal 3. Balance 4. Quit 
Your choice: 4 

Du valde "Quit" 
+0

Я не могу использовать другие методы, чем те, которые у меня есть, и программа должна показывать десять транзакций всегда. – nillion

+0

@yahya Эти методы работают некорректно, я обновил логику внутри этих методов для достижения желаемого результата. ** количество транзакций ** определяется как ** CONSTANT ** в моей программе, вам просто нужно изменить значение 'TRANS_SIZE' на 10. – Gosu

+0

Я не могу использовать глобальные переменные и константы в своей программе поэтому я могу написать только int [] trans = new int [10]; – nillion