Updating arrays in Java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 10 days ago.
Improve this question
I am very new to Java and am getting lost! I am making a programme that checks the arrays to see what seats are available and if they are it will update them so they are no longer available.
it is updating them but once I print out all of my arrays using a separate method it just prints the default set variable.
I know my code may be a bit messy I am still new and would appreciate any help on how to get it working right.
import java.util.Scanner;
public class Theatre {
// creating the rows of seats
public int[] rowOne = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
public int[] rowTwo = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
public int[] rowThree = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
static void buy_ticket(){
//Allows you to use variables set in the class
Theatre myObjTheatre = new Theatre();
System.out.println("Please select a row (1-3):");
Scanner row = new Scanner(System.in);
int selectRow = row.nextInt();
if(selectRow == 1){
System.out.println("You have selected row 1.");
System.out.println("Please select a seat (1-12):");
Scanner seat = new Scanner(System.in);
int selectSeat = seat.nextInt();
if(selectSeat <= 12){
if(myObjTheatre.rowOne[selectSeat-1] == 0){
System.out.println("You bought a ticket");
myObjTheatre.rowOne[selectSeat-1] = 1;
for(int i: myObjTheatre.rowOne){
System.out.print(i);
}
}
else{
System.out.println("Seat is occupied");
}
}
else if(selectSeat >= 13){
System.out.println("The chosen seat does not exist.");
}
}
else if(selectRow == 2){
System.out.println("You have selected row 2.");
System.out.println("Please select a seat (1-16):");
Scanner seat2 = new Scanner(System.in);
int selectSeat2 = seat2.nextInt();
if(selectSeat2 <= 16){
if(myObjTheatre.rowTwo[selectSeat2-1] == 0){
System.out.println("You bought a ticket");
myObjTheatre.rowTwo[selectSeat2-1] = 1;
}
else{
System.out.println("Seat is occupied");
}
}
else if(selectSeat2 >= 17){
System.out.println("The chosen seat does not exist.");
}
}
else if(selectRow == 3){
System.out.println("You have selected row 3.");
System.out.println("Please select a seat (1-20):");
Scanner seat3 = new Scanner(System.in);
int selectSeat3 = seat3.nextInt();
if(selectSeat3 <= 20){
if(myObjTheatre.rowThree[selectSeat3-1] == 0){
System.out.println("You bought a ticket");
myObjTheatre.rowThree[selectSeat3-1] = 1;
}
else{
System.out.println("Seat is occupied");
}
}
else if(selectSeat3 >= 21){
System.out.println("The chosen seat does not exist.");
}
}
}
public static void print_seating_area() {
Theatre myObjTheatre = new Theatre();
// prints the rows
for (int i = 0; i < myObjTheatre.rowOne.length; i++) {
System.out.print(myObjTheatre.rowOne[i]);
}
System.out.println();
for (int i = 0; i < myObjTheatre.rowTwo.length; i++) {
System.out.print(myObjTheatre.rowTwo[i]);
}
System.out.println();
for (int i = 0; i < myObjTheatre.rowThree.length; i++) {
System.out.print(myObjTheatre.rowThree[i]);
}
}
public static void main(String[] args) {
System.out.println("Welcome to the New Theatre");
while(true){
System.out.println();
System.out.println("------------------------------------");
System.out.println("Please select an option:");
System.out.println(" 1) Buy a ticket");
System.out.println(" 2) Print seating area");
System.out.println(" 3) Cancel a ticket");
System.out.println(" 4) List available seats");
System.out.println(" 5) Save to file");
System.out.println(" 6) Load from file");
System.out.println(" 7) Print ticket information and total price");
System.out.println(" 8) Sort tickets by price");
System.out.println(" 0) Quit");
System.out.println("------------------------------------");
System.out.println("Enter option:");
//takes the user input to select an option
Scanner menuOption = new Scanner(System.in);
int option = menuOption.nextInt();
if(option == 1){
buy_ticket();
}
else if(option == 2){
print_seating_area();
}
}
}
}

This prints out the seating from a new theater object that you just created. Of course the seats are all empty.
public static void print_seating_area() {
Theatre myObjTheatre = new Theatre();
To fix this, you should really make buyTicket() and printSeating() non-static, so they operate on the Theater object directly. Then call those methods from main on an object you create once.
public static void main(String[] args) {
Theatre myObjTheatre = new Theatre();
System.out.println("Welcome to the New Theatre");
while(true){
// etc.
if(option == 1){
myObjTheatre.buy_ticket();
}
else if(option == 2){
myObjTheatre.print_seating_area();
}
}
}

Related

JAVA - Modify Employee

Be kind, learning.
These are the classes I have: Employee, salaryworker, hourlyworker, PayrollTest
I need to be able to modify existing employee, but I need it to be able to tell the difference if its an hourly or salary worker as they have different inputs. I can find the employee by its id, but not how to modify it correctly. I'm lost on how to do this.
import java.util.*;
import java.lang.*;
public class PayrollTest {
//Array Lists for Hourly and Salary Workers.
public static hourlyworker hourlyEmp = new hourlyworker(null, 0, 0.0, 0.0, 0.0, 0, 0, 0);
public static ArrayList<hourlyworker> hourlyList = new ArrayList<hourlyworker>();
//(String name, int dependents, double annualSalary, int month, int day, int year) {
public static salaryworker salaryEmp = new salaryworker(null, 0, 0.0, 0, 0, 0);
public static ArrayList<salaryworker> salaryList = new ArrayList<salaryworker>();
//Arraylist Initializing
public static ArrayList emps = new ArrayList(); //<Employee>
//Initializing scanner for user input
public static Scanner scan = new Scanner(System.in);
//Fields needed for PayrollTest
private static char choice;
private static char typeChoice;
private static boolean switcher = true;
#SuppressWarnings("resource")
public static void main(String[] args) {
menuSelection();
System.out.println();
}
#SuppressWarnings("unchecked")
private static void loadHourlyEmployee() {
System.out.println("\nEnter full name, number of dependents, hourly rate, regular hours worked, overtime worked, and date hired (yyyy mm dd)");
System.out.println("[one field per line, except date hired]: ");
hourlyEmp = new hourlyworker(null, 0, 0.0, 0.0, 0.0, 0, 0, 0);
hourlyEmp.setName(scan.nextLine());
hourlyEmp.setDependents(scan.nextInt());
hourlyEmp.setPayrate(scan.nextDouble());
hourlyEmp.setHours(scan.nextDouble());
hourlyEmp.setOvertimeHours(scan.nextDouble());
hourlyEmp.setHireDay(scan.nextInt());
emps.add(hourlyEmp);
System.out.println("\nYou entered an employee type for non-exempt: hourly.");
}
#SuppressWarnings("unchecked")
private static void loadSalaryEmployee() {
System.out.println("\nEnter full name, number of dependents, annual salary, and date hired (yyyy mm dd)");
System.out.println("[one field per line, except date hired]: ");
salaryEmp = new salaryworker(null, 0, 0.0, 0, 0, 0);
salaryEmp.setName(scan.nextLine());
salaryEmp.setDependents(scan.nextInt());
salaryEmp.setAnnualSalary(scan.nextDouble());
salaryEmp.setHireDay(scan.nextInt());
emps.add(salaryEmp);
System.out.println("\nYou entered an employee type for exempt: salary.");
}
private static void menuSelection() {
do {
System.out.println("\n\n\tEmployee Database");
System.out.println("\nEmployee Info Menu");
System.out.println("\tEnter L to (L)oad Employee info");
System.out.println("\tEnter M to (M)odify Employee info");
System.out.println("\tEnter P to (P)rint Employee info");
System.out.println("\tEnter Q to quit");
System.out.print("Please enter your choice: ");
choice = scan.nextLine().toUpperCase().charAt(0);
//Choice validation
while ((choice != 'L') && (choice != 'M') && (choice != 'P') && (choice != 'Q')) {
System.out.println("Invalid choice! Please select (L)oad, (M)odify, (P)rint, or (Q)uit: ");
choice = scan.nextLine().toUpperCase().charAt(0);
}
//Switch Statement
switch (choice) {
case 'L' :
System.out.println("What is the employee type? S = salary H = hourly ");
System.out.print("\n[Please enter letter] : ");
typeChoice = scan.nextLine().toUpperCase().charAt(0);
//typeChoice validation
while ((typeChoice != 'S') && (typeChoice != 'H')) {
System.out.println("Invalid choice! Please select (S)alary, (H)ourly: ");
typeChoice = scan.nextLine().toUpperCase().charAt(0);
}
if (typeChoice == 'H') {
loadHourlyEmployee();}
else if (typeChoice == 'S') {
loadSalaryEmployee();
}
break;
case 'M' :
modifyEmployee();
break;
case 'P' :
printEmployees();
break;
case 'Q' :
switcher = false;
System.out.println("\nProgram Terminated.");
break;
}
}
while (switcher != false);
}
private static void printEmployees() {
System.out.println("\nThere are " + emps.size() + " people in this database.\n");
for (int i = 0; i < emps.size(); i++) {
System.out.println(emps.get(i));
}
System.out.println("\nTotal = " + emps.size());
}
private static void modifyEmployee() {
System.out.print("Employee id#? ");
int findID = scan.nextInt();
boolean found = false;
int index = 0;
boolean deleteMod = false;
int index1 = 0;
while (index < emps.size() && !found) {
if (emps.get(index) != null) {
found = true;
}
deleteMod = true;
System.out.println("\nCurrent Info: ");
}
}
}
Use instanceof to determine if it is the class you want or not.
if (emps.get(index) instanceof hourlyworker) {
// code for hourlyworker
} else {
// code for salaryworker
}
The instanceof operator in java will help you here. As you are in learning mode, I will prefer you find out about it, rather than me explaining here.

Counter in while loop does not increase

I need to develop a scholarship application in Java. I need to print the successful application in output.
Why a counter in this code does not increase if I for a second person?
import java.util.Scanner;
import java.util.LinkedList;
public class Main
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
Application a = new Application();
LinkedList lList = new LinkedList();
boolean bEligible = false;
int scholarship;
int scholarshipAmount = 500000;
int setiStudyLevel;
int counter;
while(scholarshipAmount != 0)
{
counter = 1;
System.out.println("");
System.out.println("**Welcome to scholarship applications offered by Smart Foundation**");
System.out.println("");
System.out.println("");
System.out.println("Please Enter Your Name");
a.setsName(input.next());
System.out.println("1–Pre Diploma, 2–Diploma, 3–Degree");
System.out.println("Please Enter Your Study Level");
a.setiStudyLevel(input.nextInt());
System.out.println("Please Enter Your Personality Score");
a.setiPersonalityScore(input.nextInt());
System.out.println("Please Enter Your Parents Income");
a.setdParentsIncome(input.nextDouble());
String sName = a.getsName();
int iStudyLevel = a.getiStudyLevel();
int iPersonalityScore = a.getiPersonalityScore();
double dParentsIncome = a.getdParentsIncome();
if (iStudyLevel == 1)
{
scholarship = 15000;
scholarshipAmount = scholarshipAmount - scholarship;
}
else if (iStudyLevel == 2)
{
scholarship = 50000;
scholarshipAmount = scholarshipAmount - scholarship;
}
else if (iStudyLevel == 3)
{
scholarship = 500000;
scholarshipAmount = scholarshipAmount - scholarship;
}
System.out.println("");
System.out.println("");
System.out.println("*****Result*****");
System.out.println("Name:"+sName);
System.out.println("1–Pre Diploma, 2–Diploma, 3–Degree");
System.out.println("Study Level:"+iStudyLevel);
System.out.println("Personality Score:"+iPersonalityScore);
System.out.println("Parents Income:"+dParentsIncome);
if(iPersonalityScore <=90)
{
if(dParentsIncome >=3000)
{
System.out.println("YOU ARE NOT ELIGIBLE FOR SCHOLARSHIP ");
}
else
{
System.out.println("YOU ARE ELIGIBLE FOR SCHOLARSHIP ");
bEligible = true;
}
}
else
{
System.out.println("YOU ARE ELIGIBLE FOR SCHOLARSHIP ");
}
System.out.println("");
System.out.println( "RM"+(scholarshipAmount)+" left!!");
System.out.println("");
if (scholarshipAmount <= 0)
{
System.out.println(" Scholarship Quota is Full!");
}
counter++;
System.out.println(counter);
}
}
}
The problem is that you reset your counter to 1 on each loop
Change this:
while(scholarshipAmount != 0)
{
counter = 1;
to this
int counter = 1;//or maybe 0
while(scholarshipAmount != 0)
{
Your loop should be,
while(scholarshipAmount > 0)
{
//remaining code

Adding two loops to an elevator system?

So I'm creating an elevator system to go with another piece of code. The system currently works fine, however I would like to add a while loop, so that when an invalid floor is selected, I am given the chance to retry another floor at this point in the code;
public static void selectFloor() {
Scanner scnr = new Scanner(System.in);
int newFloor;
System.out.println("Enter your destination floor >>> ");
newFloor = scnr.nextInt();
if (newFloor > 7 || newFloor < 0) {
System.out.println("Invalid floor entry");
}
I also wanted to add another loop to the system so that once a floor has been selected and the elevator arrives at the destination floor, the cycle will allow the user to select another destination from the current floor in a never ending cycle. Here is the remainder of the code;
else {
int direction = 0;
if(currentFloor < newFloor){
direction = 1;
} else if (currentFloor > newFloor) {
direction = -1; ;
} else {
direction = 0;
}
for (; currentFloor != newFloor; currentFloor += direction)
System.out.println("..." + currentFloor);
System.out.println("Elevator has arrived!");
}
}
public void fireAlarm() {
System.out.println("***FIRE ALARM*** Please exit the building safely.");
}
}
Due to the structure of my code, I can't figure out how to do this. How could I add these two loops?
You obviously need one loop that will loop forever until a break signal from keyboard input is sent (let's say that is number -1)
public static void selectFloor() {
Scanner scnr = new Scanner(System.in);
int newFloor= 0; //initalize to 0
while (newFloor != -1) { //loop forever until user gives -1 as input
System.out.println("Enter your destination floor >>> ");
System.out.println("To exit the programm enter: -1"); //tell the user how to exit
newFloor = scnr.nextInt();
if (newFloor > 7 || newFloor < 0) {
//if logic
} else {
//else logic
}
}
}
You may try it this way:
Scanner scnr = new Scanner(System.in);
int newFloor;
while (true) {
System.out.print("Enter your destination floor >>> ");
newFloor = scnr.nextInt();
if (newFloor >= 0 && newFloor <= 7) break;
System.out.println("Invalid floor entry");
};
int direction = Math.signum(newFloor - currentFloor);
while (currentFloor != newFloor) {
currentFloor += direction;
System.out.println("..." + currentFloor);
}
System.out.println("Elevator has arrived!"); }
This is my approach. I broke the whole interaction up into three methods: The first "tells the story". The second handles the input of the new floor and the third takes the elevator to the destination floor. Thus each method has a clear responsibility and can be altered at a later stage if needs be.
// Handles the whole thing
public static void elevatorAction() {
int currentFloor = 1;
int destinationFloor;
while(true) {
destinationFloor = selectNewFloor();
goToDestinationFloor(currentFloor, destinationFloor);
System.out.println("The elevator has arrived");
currentFloor = destinationFloor;
}
}
// Handles the traveling
public static void goToDestinationFloor(int currentFloor, int destinationFloor) {
int increment;
if(currentFloor == destinationFloor) {
return;
}
increment = (currentFloor < destinationFloor? 1: -1);
while(currentFloor != destinationFloor) {
currentFloor += increment;
System.out.println("..." + currentFloor);
}
}
// Lets the user select a new destination floor for the elevator
public static int selectNewFloor() {
Scanner scnr = new Scanner(System.in);
int tempNewFloor;
System.out.println("Please choose your destination floor.");
while((true) {
tempNewFloor = scnr.nextInt();
if(tempNewFloor < 0 || tempNewFloor > 7) {
System.out.println("Next floor: " + tempNewFloor);
break;
} else {
System.out.println("Invalid input: Please choose a floor between 1 and 7");
}
}
}

int variable remains at 0, while loop not running properly as a result

What I really am stuck with is the second to last variable userGuessDifference. It remains at zero making my second while loop not run properly as it just keeps going back to the first else if statement.
public class GuessingGame {
/**
* #param args
*/
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
Random generator = new Random();
int difficulty = 0;
int guesses = 0;
int userGuess = 0;
int correctAnswer = 0;
int counter = 0;
int userGuessDifference = (Math.abs(correctAnswer) - Math.abs(userGuess));
boolean flag = false;
System.out.println("We are going to play a number guessing game.");
System.out.println(" ");
System.out.println("Choose your difficulty:");
System.out.println("Pick a number - 10 is easy, 25 is medium, 50 is hard.");
difficulty = keyboard.nextInt();
if (difficulty == 10)
{
guesses = 3;
System.out.println("You have 3 guesses, make them count!");
}
else if (difficulty == 25)
{
guesses = 5;
System.out.println("You have 5 guesses, make them count!");
}
else if (difficulty == 50)
{
guesses = 6;
System.out.println("You have 6 guesses, make them count!");
}
else
{
System.out.println("If you can't follow instructions, I'm going to make this very difficult for you!");
difficulty = (difficulty * 100);
guesses = 1;
}
System.out.println(" ");
System.out.println("Ok, I have my number. Time to play.");
correctAnswer = generator.nextInt(difficulty) + 1;
System.out.println("Pick a whole number between 1 and " + difficulty + ":");
userGuess = keyboard.nextInt();
while (!flag || (counter <= guesses))
{
if (userGuess == correctAnswer)
{
System.out.println("CONGRATS YOU WIN!");
flag = true;
}
else if ((userGuessDifference <= (difficulty * .10)))
{
System.out.println("HOT!");
userGuess = keyboard.nextInt();
counter++;
}
else if ((userGuessDifference < (difficulty * .25)) && (userGuessDifference > (difficulty * .10)))
{
System.out.println("Warm...");
userGuess = keyboard.nextInt();
counter++;
}
else
{
System.out.println("Ice cold.");
userGuess = keyboard.nextInt();
counter++;
}
}
}
}
As #SotiriosDelimanolis wrote, you never reassign userGuessDifference. This should be done inside the while loop.
Moreover, there is another problem with your code: if you guess the number, the program just prints "CONGRATS YOU WIN!" forever, but it seems to me that you wanted to quit from the while loop once the user guesses the number (I guess the flag variable was introduced for this reason).
I slightly changed your code in order to meet this requirement:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random generator = new Random();
int difficulty = 0;
int guesses = 0;
int userGuess = 0;
int correctAnswer = 0;
int counter = 0;
System.out.println("We are going to play a number guessing game.");
System.out.println(" ");
System.out.println("Choose your difficulty:");
System.out.println("Pick a number - 10 is easy, 25 is medium, 50 is hard.");
difficulty = keyboard.nextInt();
if (difficulty == 10) {
guesses = 3;
System.out.println("You have 3 guesses, make them count!");
} else if (difficulty == 25) {
guesses = 5;
System.out.println("You have 5 guesses, make them count!");
} else if (difficulty == 50) {
guesses = 6;
System.out.println("You have 6 guesses, make them count!");
} else {
System.out.println("If you can't follow instructions, I'm going to make this very difficult for you!");
difficulty = (difficulty * 100);
guesses = 1;
}
System.out.println(" ");
System.out.println("Ok, I have my number. Time to play.");
correctAnswer = generator.nextInt(difficulty) + 1;
System.out.println("Pick a whole number between 1 and " + difficulty + ":");
userGuess = keyboard.nextInt();
while (counter <= guesses) {
// int userGuessDifference = (Math.abs(correctAnswer) - Math
// .abs(userGuess));
int userGuessDifference = Math.abs(correctAnswer - userGuess);
if (userGuess == correctAnswer) {
System.out.println("CONGRATS YOU WIN!");
break;
}
else if ((userGuessDifference <= (difficulty * .10))) {
System.out.println("HOT!");
}
else if ((userGuessDifference < (difficulty * .25))
&& (userGuessDifference > (difficulty * .10))) {
System.out.println("Warm...");
}
else {
System.out.println("Ice cold.");
}
userGuess = keyboard.nextInt();
counter++;
}
}
}

Getting incorrect value reading from arrray

The problem is when I create three accounts for example 1, 2 and 3. Then delete 2 and add a new one the result is 1, 3 and 2, everything ok. When I add another account the results is 1, 3, 2, 3. Adding yet another one gets me 1, 3, 2, 3, 4.
The values are stored in a text file from where the array reads and writes them to.
The problem is I get the same account number twice. Also just making it always increment by one isn't ok, because I need it to fill the gaps from the deleted accounts.
Can't figure out the problem and would really appreciate some help!
The code responsible:
private int choice;
public String name;
public int accountNr = 1;
public int cash;
public int funds;
private boolean run = true;
private int index = 0;
private int index1 = 0;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
ArrayList<Account> acc = new ArrayList<Account>();
ArrayList<TransferHistory> transferHistory = new ArrayList<TransferHistory>();
public int c;
public int amount;
private int c1;
private int size;
ReaderWriter io = new ReaderWriter();
private int account0;
private Account ac;
private int account1;
private int account3;
private int account2;
private int viewAnswer;
private int deleteAnswer;
private String s = "";
public void startMessage() {
System.out.println("***** Welcome to our bank system *****");
}
public void mainMenu() {
while (run == true) {
acc = io.readFromFile();
Scanner scan = new Scanner(System.in);
System.out.println("**** Main menu ****");
System.out.println("1. Create a new account");
System.out.println("2. Deposit/Withdraw from account");
System.out.println("3. Transfer money");
System.out.println("4. View the account properties");
System.out.println("5. View one account properties");
System.out.println("6. Delete account");
System.out.println("7. Show transfer history");
System.out.println("8. Show transfer history for one account");
System.out.println("9. Quit");
try {
choice = scan.nextInt();
} catch (InputMismatchException e) {
System.out.println("Please enter valid choice");
}
if (choice == 1) {
addAccount();
}
if (choice == 2) {
transfer();
}
if (choice == 3) {
transferWithin();
}
if (choice == 4) {
view();
}
if (choice == 5) {
viewOne();
}
if (choice == 6) {
delete();
}
if (choice == 7) {
showTransfers();
}
if (choice == 8) {
showOneTransfer();
}
if (choice == 9) {
quit();
}
}
}
public void addAccount() {
System.out.print("Enter your name: ");
name = scan.next();
for (int i = 0; i < acc.size(); i++) {
if(acc.get(i).getAcc() == accountNr) {
accountNr++;
}
}
System.out.println("Your account nr is: " + accountNr);
System.out.print("Enter your starting funds: ");
try {
cash = scan.nextInt();
if(cash < 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
index = acc.size();
acc.add(index, new Account(name, accountNr, cash)); //Add new account object to specified element in acc arraylist
index = acc.size();
io.writeToFile(acc);
} catch (InputMismatchException e) {
System.out.println("The scanner couldn´t read your input, use digits next time.");
System.out.println("The funds for this account has been set to zero, use transfers to adjust");
scan.reset();
}
}
public void transfer() {
System.out.print("Enter account number to withdraw/deposit to: ");
try {
account1 = Integer.parseInt(scan.nextLine());
if(account1 > acc.size() || account1 <= 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.println("Enter a number!");
scan.reset();
return;
}
System.out.print("Enter a positive number to deposit and negative to withdraw: ");
try {
funds = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
System.out.println("Enter a number!");
scan.reset();
return;
}
for (int i = 0; i < acc.size() + 1; i++) {
if (account1 == i) {
if (funds > 0) {
acc.get(account1 - 1).setCash(funds + acc.get(account1 - 1).getCash());
System.out.println("The amount is changed to " + acc.get(account1 - 1).getCash());
index1 = transferHistory.size();
transferHistory.add(index1, new TransferHistory(account1, funds, account1));
io.writeTransferedToFile(transferHistory);
index1 = transferHistory.size();
}
if (funds < 0 && funds + acc.get(account1 - 1).getCash() > 0) {
acc.get(account1 - 1).setCash(funds + acc.get(account1 - 1).getCash());
System.out.println("The amount is changed to " + acc.get(account1 - 1).getCash());
index1 = transferHistory.size();
transferHistory.add(index1, new TransferHistory(account1, funds, account1));
io.writeTransferedToFile(transferHistory);
index1 = transferHistory.size();
} else if (acc.get(account1 - 1).getCash() + funds < 0) {
System.out.println("This transaction is not allowed since the balance will be negative");
}
}
}
io.writeToFile(acc);
}
public void view() {
acc = io.readFromFile();
for (int i = 0; i < acc.size(); i++) {
System.out.println(s);
System.out.println("Account name: " + acc.get(i).tempName);
System.out.println("Account number: " + acc.get(i).tempAccNr);
System.out.println("Funds: " + acc.get(i).tempCash);
}
if (acc.isEmpty()) {
System.out.println("No accounts to show");
}
}
public void quit() {
System.exit(0);
}
private void transferWithin() {
System.out.print("Enter account you want to transfer from: ");
try {
account3 = Integer.parseInt(scan.nextLine());
if(account3 > acc.size() || account3 <= 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.print("Enter a account number: ");
scan.reset();
return;
}
System.out.print("Enter amount you want to transfer: ");
try {
amount = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
System.out.print("Enter a number: ");
scan.reset();
return;
}
System.out.print("Enter account you want to transfer to: ");
try {
account2 = Integer.parseInt(scan.nextLine());
if(account2 > acc.size() || account2 <= 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.print("Enter a account number:");
scan.reset();
return;
}
for (int i = 0; i < acc.size() + 1; i++) {
if (i == account3) {
c = acc.get(i - 1).getCash();
if (c - amount >= 0) {
acc.get(i - 1).setCash(c - amount);
System.out.println("Funds in account: " + acc.get(i - 1).getAcc() + " " + acc.get(i - 1).getCash());
index1 = transferHistory.size();
transferHistory.add(index1, new TransferHistory(account3, amount, account2));
io.writeTransferedToFile(transferHistory);
index1 = transferHistory.size();
} else if (c - amount < 0) {
System.out.println("Not enough funds in account");
mainMenu();
}
}
}
for (int j = 0; j < acc.size() + 1; j++) {
if (j == account2) {
c1 = acc.get(j - 1).getCash();
acc.get(j - 1).setCash(c1 + amount);
System.out.println("Funds in account " + acc.get(j - 1).getAcc() + " " + acc.get(j - 1).getCash());
}
}
io.writeToFile(acc);
}
private void viewOne() {
System.out.println("Enter account number you want to look at");
try {
viewAnswer = Integer.parseInt(scan.nextLine());
if(viewAnswer > acc.size() || viewAnswer <= 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.println("Enter a account number!");
scan.reset();
return;
}
for (int i = 0; i < acc.size() + 1; i++) {
if (i == viewAnswer) {
System.out.println("Account name: " + acc.get(i - 1).getName());
System.out.println("Account nr: " + acc.get(i - 1).getAcc());
System.out.println("Funds: " + acc.get(i - 1).getCash());
}
}
}
private void delete() {
System.out.print("Enter account you want to delete: ");
try {
deleteAnswer = Integer.parseInt(scan.nextLine());
if(deleteAnswer > acc.size() || deleteAnswer < 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.println("Enter a account number!");
scan.reset();
return;
}
for (int i = 0; i < acc.size(); i++) {
if (acc.get(i).getAcc() == deleteAnswer) {
acc.remove(i);
io.writeToFile(acc);
}
}
}
private void showTransfers() {
transferHistory = io.readTransferedFromFile();
System.out.println(s);
System.out.println("***Transactions***");
System.out.println(s);
for (int i = 0; i < transferHistory.size(); i++) {
int t = transferHistory.get(i).tempFromAccount;
int t1 = transferHistory.get(i).temptransfered;
int t2 = transferHistory.get(i).tempToAccount;
System.out.println("Transfer from: " + t);
System.out.println("Transfered amount: " + t1);
System.out.println("Transfered to: " + t2);
System.out.println(s);
}
}
private void showOneTransfer() {
transferHistory = io.readTransferedFromFile();
System.out.println(s);
System.out.println("***Transactions***");
System.out.println(s);
System.out.print("Enter account nr: ");
int z = scan.nextInt();
System.out.println("Transactions made my account nr "+z+":");
for (int i = 0; i < transferHistory.size(); i++) {
if(transferHistory.get(i).tempFromAccount == z){
int t = transferHistory.get(i).tempFromAccount;
int t1 = transferHistory.get(i).temptransfered;
int t2 = transferHistory.get(i).tempToAccount;
System.out.println("Transfer from: " + t);
System.out.println("Transfered amount: " + t1);
System.out.println("Transfered to: " + t2);
System.out.println(s);
}
}
}
}
Here I populate the array from the file:
public ArrayList<Account> readFromFile() {
FileReader reader = null;
ArrayList<Account> result = new ArrayList<Account>();
try {
reader = new FileReader(new File(text));
BufferedReader br = new BufferedReader(reader);
String row = br.readLine();
while (row != null) {
String[] splits = row.split(":");
if (splits.length == 3) {
int saveNR = Integer.valueOf(splits[1]);
int saveAmount = Integer.valueOf(splits[2]);
String saveName = splits[0];
result.add(new Account(saveName,saveNR,saveAmount));
} else {
System.out.println("Error in file format");
}
row = br.readLine();
}
} catch (Exception e) {
System.out.println("Error while reading from file");
} finally {
try {
reader.close();
} catch (IOException ex) {
System.out.println("Ignore");
}
return result;
}
}
private void delete() {
System.out.print("Enter account you want to delete: ");
try {
deleteAnswer = Integer.parseInt(scan.nextLine());
if(deleteAnswer > acc.size() || deleteAnswer < 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.println("Enter a account number!");
scan.reset();
return;
}
for (int i = 0; i < acc.size(); i++) {
if (acc.get(i).getAcc() == deleteAnswer) {
acc.remove(i);
io.writeToFile(acc);
}
}
}
If you want a counter, have it be a static variable on the class and increment it when you need a new value. Something like:
private static int counter = 0;
private static int nextCounter() {
return ++counter;
}
Or, for synchronization reasons, use
private static AtomicInteger counter = new AtomicInteger();
private static int nextCounter() {
return counter.incrementAndGet();
}
However, I suggest you stop thinking that you need to fill in all the gaps in the account numbers. Typically in database work, account numbers are never reused. You aren't formally using a database, but you should work the same way. Reuse buys you nothing, and there is always a chance your code may confuse a new user 17 with the an old user 17. Just imagine what would happen were the US Social Security Administration were to reuse social security numbers.
Here's the reason for your error, by the way. In the code:
for (int i = 0; i < acc.size(); i++) {
if(acc.get(i).getAcc() == accountNr) {
accountNr++;
}
}
Suppose accountNr starts as 1, there are 3 accounts, and they have account numbers 2, 1, 3. After each runthrough of the loop, accountNr changes to:
1 ⇢ 1⇢ 2 ⇢ 2.
2 is an existing accont number, but your code sets account number to 2 after the last time it would be checked.
Getting the first unused integer
You want a way to get the first unused integer in acc. Here goes:
private int firstUnusedId(List<Account> accounts) {
List<Integer> ids = new ArrayList<>();
// Foreach loop.
for(Account account: accounts) {
ids.add(account.getAcc());
}
Collections.sort(ids);
for (int index = 0; index < ids.size(); ++index) {
if (ids.get(index) != index + 1) {
return index + 1;
}
}
return ids.size() + 1;
}
If the ids are 2, 1, 5 then they sort to 1, 2, 5. Then the loop compares:
index = 0, index + 1 = 1, compare to 1, equal.
index = 1, index + 1 = 2, compare to 2, equal.
index = 2, index + 1 = 3, compare to 5, not equal, return 3.
If the ids were 3, 2, 1, they would sort to 1, 2, 3, and the only difference would be the last comparison:
index = 2, index + 1 = 3, compare to 3, equal.
return size + 1 = 4.
You must share more of you code but from what i have seen and predict that you are creating the new account from the last accountNr +1 so if your last account in the list is 2 then 3 will be created ...4 etc..so review your new account and set your accountNr = acc.size+1

Categories