Household Accounts Java Exercise

Exercise

Household Accounts

Objetive

Create a program in java that can store up to 10000 costs and revenues, to create a small domestic accounting system. For each expense (or income), should be allowed to save the following information:

• Date (8 characters: YYYYMMDD format)
• Description of expenditure or revenue
• Category
• Amount (if positive income, negative if an expense)

The program should allow the user to perform the following operations:

1 - Add a new expense (the date should "look right": day 01 to 31 months from 01 to 12 years between 1000 and 3000). The description must not be empty. Needless to validate the other data.

2 - Show all expenses of a certain category (eg, "studies") between two certain dates (eg between "20110101" and "20111231"). Number is displayed, date (format DD / MM / YYYY), description, category in parentheses, and amount to two decimal places, all in the same line, separated by hyphens. At the end of all data show the total amount of data displayed.

3 - Search costs containing a certain text (in the description or category without distinguishing case sensitive). Number is displayed, the date and description (the description is displayed in the sixth truncated blank, if any spaces six or more).

4 - Modify a tab (tab number prompt the user, it will show the previous value of each field and press Enter to not be able to modify any of the data). Should be advised (but not re-order) if the user enters a wrong card number. Needless to validate any data.

5 - Delete some data, from the number that you enter. Should be advised (but not re-order) if you enter an incorrect number. It should show the card to be clear and prompt prior to deletion.

6 - Sort data alphabetically, by date and (if matched) description.

7 - Normalize descriptions: remove trailing spaces, spaces and mirror sites. If a description is all uppercase, will be converted to lowercase (except for the first letter, kept in uppercase).

T-End the use of the application (as we store the information, the data will be lost).

Example Code

import java.util.*;
public class Main
{
	private final static class accountData
	{
		public String date;
		public String description;
		public String category;
		public double amount;

		public accountData clone()
		{
			accountData varCopy = new accountData();

			varCopy.date = this.date;
			varCopy.description = this.description;
			varCopy.category = this.category;
			varCopy.amount = this.amount;

			return varCopy;
		}
	}

	public static void main()
	{
		int capacity = 10000;
		accountData[] data = new accountData[capacity];
		boolean repeat = true;
		String option;
		int amountOfData = 0;

		do
		{
			System.out.println();
			System.out.println("Household accounts");
			System.out.println();
			System.out.println("1.- Add data.");
			System.out.println("2.- View all data.");
			System.out.println("3.- Search data.");
			System.out.println("4.- Modify data.");
			System.out.println("5.- Delete data.");
			System.out.println("6.- Sort alphabetically");
			System.out.println("7.- Fix spaces");
			System.out.println("Q,T.-Quit.");
			System.out.print("Option: ");
			option = new Scanner(System.in).nextLine();

			switch (option)
			{
				case "1": //add
					if (amountOfData > capacity - 1)
					{
						System.out.println("Database full!");
					}
					else
					{
						do
						{
							System.out.print("Enter date (YYYYMMDD): ");
							data[amountOfData].date = new Scanner(System.in).nextLine();
							// TODO: Individual validation for the date
						} while (data[amountOfData].date.length() == 0);

						do
						{
							System.out.print("Enter Description: ");
							data[amountOfData].description = new Scanner(System.in).nextLine();
							if (data[amountOfData].description.length() == 0)
							{
								System.out.print("Cannot be empty");
							}
						} while (data[amountOfData].description.length() == 0);

						System.out.print("Enter category: ");
						data[amountOfData].category = new Scanner(System.in).nextLine();

						System.out.print("Enter the amount: ");
						data[amountOfData].amount = Double.parseDouble(new Scanner(System.in).nextLine());

						amountOfData++;
					}
					break;

				case "2": //view
					if (amountOfData == 0)
					{
						System.out.println("No data!");
					}
					else
					{
						System.out.print("Enter the category: ");
						String categ = new Scanner(System.in).nextLine();
						System.out.print("Enter the start date (YYYYMMDD): ");
						String startDate = new Scanner(System.in).nextLine();
						System.out.print("Enter the end date (YYYYMMDD): ");
						String endDate = new Scanner(System.in).nextLine();

						for (int i = 0; i < amountOfData; i++)
						{
							if ((data[i].category.equals(categ)) && (data[i].date.compareTo(startDate) >= 0) && (data[i].date.compareTo(endDate) <= 0))
							{
								System.out.printf("%1$s - %2$s/%3$s/%4$s - %5$s -(%6$s) - %7$s" + "\r\n", i + 1, data[i].date.substring(6, 8), data[i].date.substring(4, 6), data[i].date.substring(0, 4), data[i].description, data[i].category, (new Double(data[i].amount)).toString("N2")); // Year -  Month -  Day
							}
						}
					}
					break;

				case "3": //search
					System.out.print("Enter part of the description or category: ");
					String search = new Scanner(System.in).nextLine().toUpperCase();
					boolean found = false;
					for (int i = 0; i < amountOfData; i++)
					{
						if (data[i].description.toUpperCase().contains(search) || data[i].category.toUpperCase().contains(search))
						{
							System.out.printf("%1$s: %2$s - %3$s" + "\r\n", i + 1, data[i].date, data[i].description);
							// TODO: Split in sixth space
							found = true;
						}
					}
					if (!found)
					{
						System.out.println("Not found!");
					}
					break;

				case "4": // modify
					System.out.print("Enter the record number: ");
					int recNumber = Integer.parseInt(new Scanner(System.in).nextLine()) - 1;

					if ((recNumber > amountOfData) || (recNumber < 0))
					{
						System.out.print("Out of range!");
					}
					else
					{
						System.out.printf("Date (was %1$s; hit ENTER to leave as is): ", data[recNumber].date);
						String newText = new Scanner(System.in).nextLine();
						if (!newText.equals(""))
						{
							data[recNumber].date = newText;
						}

						System.out.printf("Description (was %1$s; hit ENTER to leave as is): ", data[recNumber].description);
						newText = new Scanner(System.in).nextLine();
						if (!newText.equals(""))
						{
							data[recNumber].description = newText;
						}

						System.out.printf("Category (was %1$s; hit ENTER to leave as is): ", data[recNumber].category);
						newText = new Scanner(System.in).nextLine();
						if (!newText.equals(""))
						{
							data[recNumber].category = newText;
						}

						System.out.printf("Amount (was %1$s; hit ENTER to leave as is): ", data[recNumber].amount);
						newText = new Scanner(System.in).nextLine();
						if (!newText.equals(""))
						{
							data[recNumber].amount = Double.parseDouble(newText);
						}
					}
					break;

				case "5": //delete
					int position = 0;
					System.out.print("Enter the position number to delete: ");
					position = Integer.parseInt(new Scanner(System.in).nextLine()) - 1;
					if (position > amountOfData)
					{
						System.out.println("Error: out of range");
					}
					else
					{
						// TODO: Ask for confirmation
						for (int i = position; i < amountOfData; i++)
						{
							data[i] = data[i + 1].clone();
						}
						amountOfData--;
					}
					break;

				case "6": // Sort
					accountData aux = new accountData();
					for (int i = 0; i < amountOfData - 1; i++)
					{
						for (int j = i + 1; j < amountOfData; j++)
						{
							String data1 = data[i].date + data[i].description;
							String data2 = data[j].date + data[j].description;
							if (data1.compareTo(data2) > 0)
							{
								aux = data[i].clone();
								data[i] = data[j].clone();
								data[j] = aux.clone();
							}
						}
					}
					System.out.println("Sorted.");
					break;

				case "7": //replace "  " x " "
					for (int i = 0; i < amountOfData; i++)
					{
						data[i].description = data[i].description.trim();
						while (data[i].description.contains("  "))
						{
							data[i].description = data[i].description.replace("  ", " ");
						}
						if (data[i].description.toUpperCase().equals(data[i].description))
						{
							data[i].description = data[i].description.substring(0, 1).toUpperCase() + data[i].description.substring(1).toLowerCase();
						}
					}
					break;

				case "T":
				case "t":
				case "Q":
				case "q":
					repeat = false;
					break;

				default:
					System.out.println("Wrong option!");
					break;
			}
		} while (repeat != false);
		System.out.println("Bye!");
	}
}

More Java Exercises of Arrays, Structures and Strings

Reverse Array
Create a Java program to ask the user for 5 numbers, store them in an array and show them in reverse order....
Search In Array
Create a Java program that says if a data belongs in a list that was previously created. The steps to take are: - Ask the user how many data will ...
Array Of Even Numbers
Write a Java program to ask the user for 10 integer numbers and display the even ones....
Array Of Positive And Negative Numbers
Create a Java program to ask the user for 10 real numbers and display the average of the positive ones and the average of the negative ones....
Many Numbers And Sum
Create a program which asks the user for several numbers (until he enters "end" and displays their sum). When the execution is going to end, it must d...
Two Dimensional Array
Write a Java program to ask the user for marks for 20 pupils (2 groups of 10, using a two-dimensional array), and display the average for each group....
Statistics V2
reate a statistical program which will allow the user to: - Add new data - See all data entered - Find an item, to see whether it has been entere...
Struct
Create a "struct" to store data of 2D points. The fields for each point will be: x coordinate (short) y coordinate (short) r (red colour, byte) ...
Array Of Struct
Expand the previous exercise (struct point), so that up to 1.000 points can be stored, using an "array of struct". Ask the user for data for the first...
Array Of Struct And Menu
Expand the previous exercise (array of points), so that it displays a menu, in which the user can choose to: - Add data for one point - Display al...
Books Database
Create a small database, which will be used to store data about books. For a certain book, we want to keep the following information: Title Author...
Triangle V2
Write a Java program to ask the user for his/her name and display a triangle with it, starting with 1 letter and growing until it has the full length:...
Rectangle V3
Write a Java program to ask the user for his/her name and a size, and display a hollow rectangle with it: Enter your name: Yo Enter size: 4 YoYoY...
Centered Triangle
Display a centered triangle from a string entered by the user: __a__ _uan_ Juan...
Cities Database
Create a database to store information about cities. In a first approach, we will store only the name of each city and the number of inhabitants, a...
Banner
Create a Java program to imitate the basic Unix SysV "banner" utility, able to display big texts....
Triangle Right Side
Create a Java program that asks the user for a string and displays a right-aligned triangle: ____n ___an __uan Juan...
Strings Manipulation
Create a Java program that asks the user for a string and: - Replace all lowercase A by uppercase A, except if they are preceded with a space - Di...
Nested Structs
Create a struct to store two data for a person: name and date of birth. The date of birth must be another struct consisting on day, month and ...
Sort Data
Create a Java program to ask the user for 10 integer numbers (from -1000 to 1000), sort them and display them sorted....
Two Dimensional Array As Buffer For Screen
Create a Java program that declares a 70x20 two-dimensional array of characters, "draws" 80 letters (X, for example) in random positions and displays ...
Two Dimensional Array 2: Circunference On Screen
Create a Java program that declares creates a 70x20 two-dimensional array of characters, "draws" a circumference or radius 8 inside it, and displays i...
Computer Programs
Create a Java program that can store up to 1000 records of computer programs. For each program, you must keep the following data: * Name * Categor...
Exercise Tasks
Create a Java program that can store up to 2000 "to-do tasks". For each task, it must keep the following data: • Date (a set of 3 data: day, month ...