I'm trying to make a ATM that can make deposit, withdrawal and show balance. But I have a problem with the program's balance it only shows the balance for the ten most recent transactions rather than all the transactions made.
I'm not allowed to use global variables,other methods and constants.
Here is how it should work
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: 66 KR
Code
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);
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];
}
}
}
[EDITED] Complete solution:
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;
balance += amount;
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;
balance += amount;
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");
}
}
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];
}
}
The problem is because of how you initialized your int[] trans. You're only storing the first 10 transactions. You should use ArrayList instead, because it's dynamic.
ArrayList<Integer> trans = new ArrayList<Integer>, then to add new transactions to your array
It only shows the last 10 because you initialze your array to 10 indexes
int[] trans = new int[10];
Either make it bigger or use something different.
A great class to use in this case would be a vector. You don't need to initialize a size because it resizes itself dynamically.
Now, if you use a vector, but only want to print the last ten transactions, then surround your print statements in conditionals
if(i > trans.length - 10)
{
System.out.print(trans[i] + "\n");
}
The reson for this is in your showTransactions() not only are you printing the transactions, you are also adding them, computing your balance. We want to compute your balance with all your transactions (thus we need to change your array to a vector or other class with dynamic resizing) while also only printing what you need (thus the if statement)
Related
import java.util.Scanner;
public class MainBinaryTreeArray
{
public static void main(String[] args)
{
int choice;
Scanner scan= new Scanner(System.in);
BinaryTreeArray data = new BinaryTreeArray();
Listing l1 = new Listing("Carol", 4354, 3.2);
Listing l2 = new Listing("Timothy", 2353, 4.0);
Listing l3 = new Listing("Dean", 4544, 2.4);
Listing l4 = new Listing("Sue", 3445, 3.0);
data.insert(l1);
data.insert(l2);
data.insert(l3);
data.insert(l4);
do
{
// Choose which operation by entering a number
System.out.println("*****************(Menu Operations:)******************");
System.out.println(" (Press 1). Insert.");
System.out.println(" (Press 2). Fetch.");
System.out.println(" (Press 5). Output all student records.");
System.out.println(" (Press 6). Exit the program.");
System.out.println("Enter your choice: ");
choice = scan.nextInt();
switch(choice)
{
case 1:
System.out.println("Are students inserted: " + data.insert(l1));
break;
case 2:
System.out.println("The student's info that's fetched: ");
System.out.print(data.fetch("Timothy"));
break;
case 5:
System.out.print("Output all the student's records: ");
data.showAll();
}
}while(choice!=6);
}
}
public class BinaryTreeArray
{
private Listing[] data;
private int size;
public BinaryTreeArray()
{
size = 100;
data = new Listing[size];
}
public void showAll()
{
for(int i=0; i<size; i++)
System.out.print(data[i] + " ");
}
public boolean insert(Listing newListing)
{
int i = 0;
while(i < size && data[i]!= null)
{
if(data[i].getKey().compareTo(newListing.getKey()) > 0)
i = 2 * i + 1;
else
i = 2 * i + 2;
}
if(i >= size)
return false;
else
{
data[i] = newListing.deepCopy();
return true;
}
}
public Listing fetch(String targetKey)
{
int i= 0;
while(i< size && data[i]!= null && data[i].getKey()!=targetKey)
{
if(data[i].getKey().compareTo(targetKey) > 0)
i = 2 * i + 1;
else
i = 2 * i + 2;
}
if(i >= size || data[i] == null)
return null;
else
return data[i].deepCopy();
}
}
public class Listing implements Comparable<Listing>
{ private String name; // key field
private int ID;
private double GPA;
public Listing(String n, int id, double gpa)
{ name = n;
ID = id;
GPA = gpa;
}
public String toString()
{ return("Name is " + " " + name +
"\nID is" + " " + ID +
"\nGPA is" + " " + GPA + "\n");
}
public Listing deepCopy()
{ Listing clone = new Listing(name, ID, GPA);
return clone;
}
public int compareTo(Listing other)
{
return this.name.compareTo(other.getKey());
}
public String getKey()
{
return name;
}
}// end of class Listing
Hello All,
My java program compiles fine, but I am having a terrible and miserable time with getting my program to stop printing all those nulls when I output all student records in my BinaryTreeArray. Here is complete program. Any suggestions? Please do give any advice. So to make what I am saying clear, I need help with understanding why when I print out student records it includes a whole bunch of extra nulls that really have no purpose and just make my program look crazy. Any solutions to this problem?
When you initialize the BinaryTreeArray(), you set the field variable "size" to 100 and use this to initialize the data Listing[] array. When you print out the data, the loop uses the same "size" variable so you get all 100 entries, including the null entries. A simple solution would be to filter the data for null when you show all.
public class BinaryTreeArray
{
...
public void showAll()
{
for(int i=0; i<size; i++)
{
if (data[i] != null)
System.out.print(data[i] + " ");
}
}
...
}
An alternate solution would be to change your use of size to maxSize and then create a variable size that is incremented as you insert listings.
import java.util.*;
/**
* Write a description of class TheaterApp here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class TheaterApp {
static int [][] seats = {
{10,10,10,10,10,10,10,10},
{10,10,10,10,10,10,10,10},
{10,10,20,20,20,20,10,10},
{20,20,30,30,30,30,20,20},
{30,30,40,40,40,40,30,30},
{30,40,40,50,50,40,40,40}};
/**
* Constructor for objects of class TheaterApp
*/
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String ans;
do {
System.out.print("Enter request, please (or 'help' or 'quit') ");
ans = input.next();
if (ans.equals("help")) {
System.out.println("Possible commands");
System.out.println("price <price>");
System.out.println("seat <row> <seat>");
System.out.println("left");
System.out.println("remaining <price>");
System.out.println("print");
System.out.println("quit");
System.out.println("help");
} else if (ans.equals("price")) {
int p = input.nextInt();
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[i].length; j++) {
if (seats[i][j] == 0) {
System.out.println("Next available seat at position: " + i + " " + j);
}
}
}
// Find the 'best' seat at the given price
} else if (ans.equals("seat")) {
int r = input.nextInt();
int c = input.nextInt();
int k;
int i;
int j;
for (int l = 0; l < 6; l++) {
k = 1;
for(i=0;i<6;i++) {
for(j=0;j<8;j++) {
if (k == input.nextInt()) {
// check if the seat has already been reserved
if (seats[i][j]== 0) {
System.out.println("That seat has already been reserved");
}
// if its not reserved then reserve it
else {
seats[i][j]= 0;
}
}
k++;
System.out.println(seats[i][j]);
}
}
}
// Reserve the given row and seat, if possible
} else if (ans.equals("left")) {
// Print the total available seats
} else if (ans.equals("remaining")) {
int p = input.nextInt();
// Print the total available seats at this price
} else if (ans.equals("print")) {
for (int r = 0; r < seats.length; ++r) {
for (int s = 0; s < seats[r].length; ++s) {
System.out.print(seats[r][s] + " ");
}
System.out.println();
}
} else if (!ans.equals("quit")) {
System.out.println("Come again?");
}
} while (!ans.equals("quit"));
System.out.println("Good bye");
}
}
This array represents theater seats and I have to mark sold seats by changing the price to 0. I also have to make sure seats are open when a user asks for a a certain spot, and when a user enters a price, find any seats that are open.
So I'm pretty sure I figured out the code for finding the best seat at any given price. I can't figure out how to do the remaining code.
I just need to find out how to print the total available seats and also how to print the total available seats when a certain price is entered.
Thanks.
You'd just use nested for loops, like you did before, except now you'd have some kind of a availableSeats counter you'll increment every time a seat meets a certain condition.
Like so:
int availableSeats = 0;
for(i=0;i<6;i++) {
for(j=0;j<8;j++) {
if(seats[i][j] == sometargetprice){
availableSeats++;
}
}
}
System.out.println("Total of " + availableSeats + " are available.");
Unless I'm not understanding the problem correctly.
This code is supposed to get check whether a number is a palindrome.
Whenever I run the method check Palindrome its comes up with a java.lang.StringOutOfBoundsException.
Please help.
import java.util.*;
/**
* Lab 1 .
* #author Kevin Rasquinha
* #version 30 July 2016
*/
public class Lab1
{
private Scanner scan = new Scanner(System.in);
/**
* count the number of digits in a number
* #param num the number to analyse
* #return the number of digits it has
*/
public int numDigits (int num)
{
int nDigits = 0;
int digit;
while (num>0)
{
digit = num % 10; // take off the last digit
num = num /10; // reduce the number
nDigits = nDigits + 1; // increment count of digits
}
return nDigits;
}
/**
* Read a number from the keyboard, and report how many digits it has.
* Ensure the number is within a desired range.
*/
public void countDigits ()
{
int num=0;
while (num<1 || num > 1000)
{
System.out.print("What number (1 to 1000)? ");
num = scan.nextInt();
scan.nextLine();
System.out.println("Num = " + num);
if (num<1 || num > 1000)
System.out.println("1 to 1000, please");
}
System.out.println (num + " has " + numDigits(num) + " digits");
}
/**
* method used to if a number is the sum of the cube of its digits
* #param args (not used)
*/
public void sumCubesDigits ()
{
for (int initial = 1; initial < 1000; initial ++)
{
int num = initial;
int thirddig = num%10;
num = num / 10;
int secdig = num%10;
num = num / 10;
int firstdig = num%10;
int sum = (thirddig*thirddig*thirddig) + (secdig*secdig*secdig) + (firstdig*firstdig*firstdig);
if (sum == initial)
{
System.out.println ("The number " + initial + " is equal to the sum of the cube of its digits.");
}
}
}
/**
* Recieves an int and writes the same int backwards
* #param args (not used)
*/
public int backwards(int num)
{
int rev = 0;
int value = num;
while (value != 0)
{
rev = rev*10;
rev = rev + value%10;
value /= 10;
}
return rev;
}
/**
* Receives digit from method backwards
* Asses whether backwards = the original number
* #param args (not used)
*/
public boolean palindrome (int num, int digit)
{
boolean a = false;
int normal = num;
int reversed = digit;
if( reversed == digit)
{
a = true;
}
return a;
}
/**
* Recieves int from user - num
* Sends num to backwards
* Sends num to palindrome
* Recieves boolean from palindrome
* Outputs message to user
*/
public void checkPalindrome ()
{
System.out.println ("Enter number to be see if it is a palindrome");
int num = scan.nextInt();
int digit = backwards(num);
boolean check = palindrome (num, digit);
if (check = true)
{
System.out.println("Your number is a palindrome");
}
}
/**
* Present a menu to the user, and obtain their selection. If they
* type an erroneous value, report it and try again. Either upper
* case or lower case input is accepted.
* #return an upper case character showing the user's choice
*/
public char menuChoice ()
{
System.out.println("");
System.out.println("What do you want to do?");
System.out.println("(c) Count the digits in a number");
System.out.println("(g) Find out the numbers where the the sum of the cube of its digits is equal to it");
System.out.println("(p) Find out if a number is a palindrome");
System.out.println("(q) Quit");
System.out.print("Your choice? ");
char answer = ' ';
boolean ok = false;
while (! ok)
{
answer = scan.nextLine().trim().toUpperCase().charAt(0);
ok = (answer == 'C' || answer == 'Q' || answer == 'G' || answer == 'P');
if (! ok)
{
System.out.println("Please type one of c,C,q,Q,g,G,p,P");
System.out.print("Your choice? ");
}
}
return answer;
}
/**
* test driver for the program
*/
public void test()
{
char answer = ' ';
while (answer != 'Q')
{
answer = menuChoice();
switch (answer)
{
case 'C': countDigits(); break;
case 'G': sumCubesDigits(); break;
case 'P': checkPalindrome();break;
case 'Q': break;
}
}
}
/**
* main program: create a test driver and let it loose
* #param args (not used)
*/
public static void main (String [] args)
{
Lab1 l1 = new Lab1();
l1.test();
}
}
A StringIndexOutOfBoundsException is mostly thrown when you use charAt to select a character from a string that isn't there.
I guess your issue is here:
answer = scan.nextLine().trim().toUpperCase().charAt(0);
because that is the only charAt in your code.
What would that line do if the user entered nothing? Throw an Exception of course!
You should change if (check = true) to if (check == true) and answer = scan.nextLine().trim().toUpperCase().charAt(0); to answer = scan.nextLine();
if(answer != null)
answer = answer.trim().toUpperCase().charAt(0);
So basically my program takes a text file and reads the file and splits it into a 2D array (Textfile: http://pastebin.com/6ACSUL20). I pass the name of the text file in the command line. However, when I run my program I get an ArrayIndexOutOfBoundsException which leads me to believe that the program did not split the text file correctly. Pointing me to every method that contains Integer.parseInt(titanic[i][1]) Any help would be appreciated.
package testtitanic;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
public class Titanic {
String[][] titanic;
public Titanic(String[] args){
try{
File text = new File(args[0]);
//turns the txt file into a string
String content = new Scanner(text).useDelimiter("\\Z").next();
//creates array and breaks up by new lines
String[] rows = content.split("\n");
// creates 2D array
this.titanic = new String[rows.length][];
// fills 2D array
for(int i = 0; i < rows.length; i++){
this.titanic[i] = rows[i].split("\\t");
}// end for loop
}// end try
catch(FileNotFoundException e){
System.out.println("Error" + e.getMessage());
}// end catch method
}// end fill method
public void menu(){
System.out.println("*******Welcome to the Titanic Statistical Application**************");
System.out.println("");
System.out.println("Enter the number of the question you want answered. Enter 'Q' to quit program:");
System.out.println("");
System.out.println("1. How many passengers were on the Titanic?");
System.out.println("2. What percent of passengers perished on the Titanic?");
System.out.println("3. What percent of passengers survived the sinking of the Titanic?");
System.out.println("4. What percentage of passengers survived for each of the three classes?");
System.out.println("5. What specific passengers who were less than 10 years old survived the sinking of the titanic?");
System.out.println("6. For each letter in the alphabet, how many passengers last names started with that letter?");
System.out.println("7. How many females and males were on the Titanic?");
System.out.println("Q. Quit the program");
}
public void getPassengerNumber(){
int num = titanic.length;
System.out.println("There were " + num + " passengers on the Titanic.");
}//end method
public void getPerishedPercent(){
int num = titanic.length;
int perished = 0;
for(int i = 0; i < num; i++){
int x = Integer.parseInt(titanic[i][1]);
if(x == 0){
++perished;
}// end if
}// end for
double percent = (perished / num) * 100;
System.out.println("The percentage perished on the Titanic is: " + percent);
}// end method
public void getPerishedSurvived(){
int num = titanic.length;
int survived = 0;
for(int i = 0; i < num; i++){
int x = Integer.parseInt(titanic[i][1]);
if(x == 1){
++survived;
}// end if
}// end for
double percent = (survived / num) * 100;
System.out.println("The percentage survived on the Titanic is: " + percent);
}// end method
public void getClassPercentage(){
int firstClass = 0;
int secondClass = 0;
int thirdClass = 0;
int num = titanic.length;
for(int i = 0; i < titanic.length; i++ ){
int x = Integer.parseInt(titanic[i][0]);
if(x == 1){
++firstClass;
}// end iff
if(x == 2){
++secondClass;
}
if(x == 3){
++thirdClass;
}
}// end for
double firstpercent = (firstClass / num) * 100;
double secondpercent = (secondClass / num) * 100;
double thirdpercent = (thirdClass / num) * 100;
System.out.println("Percent Survived for Firstclass is: " + firstpercent);
System.out.println("Percent Survived for Secondclass is: " + secondpercent);
System.out.println("Percent Survived for ThirdClass is: " + thirdpercent);
}// end method
public void getAge() {
int num = titanic.length;
int age = 0;
for(int i = 0; i < num; i++ ){
int x = Integer.parseInt(titanic[i][4]);
if(x < 10){
System.out.println(titanic[i][2]);
}
}// end for loop
}// end method
public void getLetters(){
for(char a = 'A'; 'Z' <= a; a++ ){
int temp = 0;
for(int i = 0; i < titanic.length; i++){
char x = titanic[i][2].charAt(0);
if(x == a){
++temp;
}// end if
System.out.println(a + ": There are " + temp + " passengers that have this letter to start as their last name.");
}// end inner
} // end outer
}// end method
public void getGender(){
int male = 0;
int female = 0;
int num = titanic.length;
for(int i = 0; i < num; i++){
if(titanic[i][3].equals("female")){
++female;
}// end if
if(titanic[i][3].equals("male")){
++male;
}// end if
}// end for
System.out.printf("There were %d females and %d males on the titanic \n", male, female);
}// end method
}//end class Titanic
Using this class to call
package testtitanic;
import java.time.LocalTime;
import java.time.Duration;
import java.util.Scanner;
/**
*
* #author Joe
*/
public class TestTitanic {
/**
* #param args the command line arguments
*/
public static void main(String[] argv) {
LocalTime startTime = LocalTime.now();
Scanner input = new Scanner(System.in);
int y = 1;
Titanic data = new Titanic(argv);
while(y == 1){
data.menu();
char x = input.next().charAt(0);
switch (x){
case '1':
data.getPassengerNumber();
break;
case '2':
data.getPerishedPercent();
break;
case '3':
data.getPerishedSurvived();
break;
case '4':
data.getClassPercentage();
break;
case '5':
data.getAge();
break;
case '6':
data.getLetters();
break;
case '7':
data.getGender();
break;
case 'Q':
y = 0;
break;
default:
System.out.println("Please enter a valid input to exit, be sure to input a capital Q.");
}// end switch
}// end while loop
LocalTime endTime = LocalTime.now();
Duration timeElapsed = Duration.between(startTime,endTime);
double time = timeElapsed.toMillis() * 1000;
System.out.println("Thanks for running this program the total time elapsed is: " + time + " seconds");
}
}
Worked for me, but I hardcoded the filename in the Titanic constructor. Are you sure you're passing it a filename?
Can you post the stack trace? Is the array index out of bounds on argv?
You don't need to guess where the index is out of bounds is. The stack trace will tell you the exact line.
I want to overwrite the first element of my transaction array when it gets full. So when I print the array, it is always showing the latest transactions.
I think the problem is in the moveTrans method or the findNr method but I'm not sure and I can't figure out what is wrong.
Code:
import java.util.Scanner;
import java.util.*;
public class BankoTest {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int amount = 0;
int choice = 0;
int [] trans = new int[4];
int sum;
int balance = 0;
while (choice != 4)
{
choice = menu();
switch(choice)
{
case 1://
System.out.print("Deposit. Amount? :");
amount = scan.nextInt();
balance = balance + amount;
makeTransactions(trans, amount);
break;
case 2://
System.out.print("Withdra. Amount?");
amount = scan.nextInt();
balance = balance - amount;
makeTransactions(trans, -amount);
break;
case 3:
showTransactions(trans, balance);
break;
case 4:
System.out.println("Thank you. ");
break;
}
}
}
public static int menu()
{
Scanner scan = new Scanner(System.in);
int choice = 0;
System.out.println("1. Deposit ");
System.out.println("2. Withdraw ");
System.out.println("3. Saldo ");
System.out.println("4. End ");
System.out.println();
System.out.println("Choice: ");
choice = scan.nextInt();
return choice;
}
public static void showTransactions(int [] trans, int balance)
{
System.out.println();
System.out.println("Transactions summary :");
System.out.println();
for(int i = 0; i < trans.length-1; i++)
{
if(trans[i] == 0)
{
System.out.print("");
}
else
{
System.out.print(trans[i] + "\n");
balance = balance + trans[i];
}
}
// Printing saldo.
System.out.println();
System.out.println("Current balance: " + balance + " kr" + "\n" );
System.out.println();
}
//Puts amount last among the transactions that are stored in the array. Using the findNr method to find the first available spot
//in the array. moveTrans is used to make room for the new transaction when the array is full.
public static void makeTransactions(int [] trans, int amount )
{
int position = findNr(trans);
if(position == -1)
{
moveTrans(trans);
position = findNr(trans);
trans[position] = amount;
}
else
{
trans[position] = amount;
}
}
public static int findNr(int [] trans)
{
int position = -1;
for(int i = 0; i <= trans.length-1; i++)
{
if(trans[i] == 0)
{
position = i;
break;
}
}
return position;
}
public static void moveTrans(int [] trans)
{
for(int i = 0; i < trans.length-1; i++)
trans[0] = trans[i + 1] ;
}
}
just modify the following method alone
public static void makeTransactions(int[] trans, int amount) {
int position = findNr(trans);
if (position == -1) {
moveTrans(trans);
position = findNr(trans);
trans[position] = amount;
} else {
if (position != 0 && position == trans.length - 1) {
// shift the elements back
for (int i = 0; i < position; i++)
trans[i] = trans[i] + 1;
trans[position - 1] = amount;
}else
trans[position] = amount;
}
}
Please check this it may help some thing to you
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int choice = 0;
int[] trans = new int[4];
int sum;
int balance = 0;
while (choice != 4) {
choice = menu();
switch (choice) {
case 1://
System.out.print("Deposit. Amount? :");
amount = scan.nextInt();
balance = balance + amount;
makeTransactions(trans, amount);
break;
case 2://
System.out.print("Withdra. Amount?");
amount = scan.nextInt();
balance = balance - amount;
makeTransactions(trans, -amount);
break;
case 3:
showTransactions(trans, balance);
break;
case 4:
System.out.println("Thank you. ");
break;
}
}
}
public static int menu() {
Scanner scan = new Scanner(System.in);
int choice = 0;
System.out.println("1. Deposit ");
System.out.println("2. Withdraw ");
System.out.println("3. Saldo ");
System.out.println("4. End ");
System.out.println();
System.out.println("Choice: ");
choice = scan.nextInt();
return choice;
}
public static void showTransactions(int[] trans, int balance) {
System.out.println();
System.out.println("Transactions summary :");
System.out.println();
for (int i = 0; i < trans.length - 1; i++) {
if (trans[i] == 0) {
System.out.print("");
}
else {
System.out.print(trans[i] + "\n");
// balance = trans[i];
}
}
// Printing saldo.
System.out.println();
System.out.println("Current balance: " + balance + " INR" + "\n");
System.out.println();
}
// Puts amount last among the transactions that are stored in the array.
// Using the findNr method to find the first available spot
// in the array. moveTrans is used to make room for the new transaction when
// the array is full.
public static void makeTransactions(int[] trans, int amount) {
int position = findNr(trans);
if (position == -1) {
moveTrans(trans);
System.out.println("Your transaction limit is over.");
// position = findNr(trans);
// System.out.println("Position -------> "+position);
// trans[position] = amount;
} else {
trans[position] = amount;
}
}
public static int findNr(int[] trans) {
int position = -1;
for (int i = 0; i <= trans.length - 1; i++) {
if (trans[i] == 0) {
position = i;
break;
}
}
return position;
}
public static void moveTrans(int[] trans) {
System.out.println("------Your Transaction Details----------");
for (int i = 0; i < trans.length; i++) {
System.out.println("Transation " + (i + 1) + " :: " + trans[i]);
trans[0] = trans[i];
}
System.out.println("----------------------------------------");
}