I have this code that involves task to do with the ArrayList names
that includes functions like adding elements in the ArrayList, displaying the elements of the ArrayList, deleting an element in an ArrayList, editing an element in an ArrayList.
My question is when I add a new name in the ArrayList, when the code loops back and I want to view the elements in the ArrayList, it turns out empty.
import java.util.ArrayList;
import java.util.Scanner;
public class mainRunner {
public static void main(String[] args) {
String con;
do {
menuCaller();
System.out.println("Do you want to continue[Y/N]");
Scanner confirm = new Scanner(System.in);
con = confirm.nextLine();
} while (con.equalsIgnoreCase("y"));
}
public static void menuCaller() {
int choice;
ArrayList names = new ArrayList();
int firstIndex =0;
Scanner scan = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
Scanner scaned = new Scanner(System.in);
System.out.println("Menu"
+"\n[1] Add Name"
+ "\n[2] Display All Record"
+ "\n[3] Delete a Record"
+ "\n[4] Edit a R1ecord "
+ "\n[5] Exit");
choice = scaned.nextInt();
if (choice == 1) {
System.out.println("***ADDING NAMES***");
System.out.println("Enter the name of the Student");
String addName = scan.next();
names.add(addName);
System.out.println("Record Added !!!");
}
else if (choice == 2) {
System.out.println("***Database Content**");
System.out.println("------------------------");
System.out.println("Record # | Name ");
for (int index = firstIndex; index < names.size(); ++index) {
System.out.println("--------------------");
System.out.println(" " + index + " | " +names.get(index));
}
}
else if (choice == 3) {
System.out.println("***Delete A Record***");
System.out.print("Enter a number to be deleted: ");
int numDelete = scan.nextInt();
names.remove(numDelete);
System.out.println("Record Deleted");
}
else if (choice == 4) {
System.out.println("***Edit Record***");
System.out.println("***Database Content**");
System.out.println("------------------------");
System.out.println("Record # | Name ");
for (int index = firstIndex; index < names.size(); ++index) {
System.out.println("--------------------");
System.out.println(" " + index + " | " +names.get(index));
}
System.out.println("Enter the Name to be Edited");
String nameEdited = scan.next();
if (names.indexOf(nameEdited) >= 0) {
System.out.print("Change to: ");
String nameChange = scan2.next();
names.set(names.indexOf(nameEdited), nameChange);
}
else {
System.out.println("Record Not Existing");
}
}
else if (choice == 5) {
System.out.println("Thank you for using the Program");
System.exit(choice);
}
else {
System.out.println("Wrong Choice");
}
}
}
Each time you call menuCaller, you're creating a new list.
Perhaps you should create it in the main method and pass the reference into menuCaller:
public static void main(String[] args) {
String con;
List<String> names = new ArrayList<>();
do{
menuCaller(names);
System.out.println("Do you want to continue[Y/N]");
Scanner confirm = new Scanner(System.in);
con = confirm.nextLine();
}while(con.equalsIgnoreCase("y"));
}
public static void menuCaller(List<String> names) {
...
// (No declaration of names here - it's a parameter now...)
...
}
Related
I just want to print the String "code", which the user enters in the method, but it is printing "null", but when i want to print int num, it prints what the user enters. The output should print all the details that the user entered; sort of like an ID thing. This should be very simple but for some reason I am not able to do it and Im starting to lose hope. Any help would be appreciated. Thanks
public class Lab2 {
static String code;
static String num;
int year;
static int sem;
public static void main(String[] args) {
info();
num();
sem();
System.out.println(num + " " + sem + " " + code);
}
public static void info() {
Scanner sc = new Scanner(System.in);
System.out.println("Course ID Generator\n--------------------------");
System.out.println("Please Enter Course Information:");
String message = "Initial";
String code = "";
while (!message.isEmpty()) {
if (!message.equals("Initial")) {
System.out.println(message);
}
System.out.print("Course Code (only capital letters " + "with a length between 2 and 4): ");
code = sc.nextLine();
message = checkLength(code);
if (message.isEmpty()) {
message = checkUpperCase(code);
}
}
}
private static String checkLength(String code) {
String output = "";
if (code.length() < 2 || code.length() > 4) {
output = "Course Code length was not between " + "2 and 4, Please try again";
}
return output;
}
private static String checkUpperCase(String code) {
String output = "";
for (int i = 0; i < code.length(); i++) {
char ch = code.charAt(i);
if (Character.isAlphabetic(ch) && Character.isUpperCase(ch)) {
} else {
output = "Course Code must only have capital " + "letters, please try again";
break;
}
}
return output;
}
public static void num() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Course Number (consists of only 3 digits): ");
num = sc.nextLine();
if (num.length() == 3) {
break;
} else {
System.out.println("Course Number length was not 3, please try again");
}
sc.close();
}
}
public static void sem() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Semester (Fall=01, Sprint=02, Summer=03):");
sem = sc.nextInt();
if (sem > 0 && sem < 4) {
break;
} else {
System.out.println("Please enter correct semester code, try again");
}
}
sc.close();
}
}
Remove the line
String code = "";
in your info Method
You are using the same variable code twice.
Read this for further information https://dzone.com/articles/variable-shadowing-and-hiding-in-java
I recenlty started to learn JAVA programming. I am using BlueJ compiler.
Can anyone tell me or give me a hint, how to make "System.out.println" not print out empty array values (I mean Null) values if array is not filled compleatly.
static String [] Country = new String [15];
static String [] City = new String [15];
static String [] Region = new String [15];
static Scanner sc = new Scanner(System.in);
static int x = 0, y = 0, z = 0;
static int a = 0, b=0,c=0, t=0;
public static void main (String [] args)
{
String entry = "-1";
while( !entry.equals ("4")){
menu();
entry = sc.nextLine();
if(!entry.equals("1") && (!entry.equals("2")) && (!entry.equals ("3")) && (!entry.equals ("4") && !entry.equals("-1")))
{ JOptionPane.showMessageDialog(null, "Please Enter Numbers as shown in 'MENU LIST'");
}
if (entry.equals ("1")) {
System.out.println("\f");
AddCity();
}
if (entry.equals("2")) {
System.out.println("\f");
Search();
}
if (entry.equals("3")) {
PrintAll();
}
}
JOptionPane.showMessageDialog(null, "Have a nice day");
}
public static void menu()
{
System.out.println(" ---------------- Menu-----------------");
System.out.println(" Please Use Numbers ONLY from 1 - 4 ");
System.out.println(" 1. Add new City");
System.out.println(" 2. Search for a City.");
System.out.println(" 3. Print All Cities.");
System.out.println(" 4. QUIT.");
}
public static void AddCity()
{
if(t >=13) {
JOptionPane.showMessageDialog(null, "Database capacity is almost full.");
PrintAll();
}
System.out.println("Please enter The name of Country.");
Country [x] = sc.nextLine();
x++;
System.out.println("Please enter the name of City.");
City [y] = sc.nextLine();
y++;
System.out.println("Please enter the Region where the city is located.");
Region [z] = sc.nextLine();
z++;
t++;
}
public static void Search()
{
}
public static void PrintAll()
{
while (a <14)
{
if (!Country.equals("Null") ) {
System.out.print("Country: ");
System.out.print(Country[a]+ " | ");
a++;
while(b <(a)) {
System.out.print("City: ");
System.out.print(City[b]+ " | ");
while(c<a) {
System.out.print("Region: ");
System.out.println(Region[c] + " | ");
c++;
}
b++;
}
}
System.out.println("");
}
}
}
Can anyone tell me or give me a hint, how to make "System.out.println"
not print out empty array values
You test, whether the value at the index position is null and only print, if not null. You need to consider, that the rest of your code, especially your counters a, b and c are outside of this condition.
while (a <14)
{
if (!Country.equals("Null") && country[a] != null) {
System.out.print("Country: ");
System.out.print(Country[a]+ " | ");
a++;
while(b <(a)) {
if(City[b]!=null) {
System.out.print("City: ");
System.out.print(City[b]+ " | ");
}
while(c<a) {
if(Region[c]!=null) {
System.out.print("Region: ");
System.out.println(Region[c] + " | ");
}
c++;
}
b++;
}
}
System.out.println("");
}
I am not sure where in your code you want to use this but is like this, in side you loop just check if you loop variable is not equal to null.
Ex:
if(variable != null) {
//do something
}
HI My prof said this about my code
Please Help me I do not get what he wanted me to do with my code
// The following code (mark by "-")can be replace by getEntryDetails(AddressBookEntry entry)
// you can just pass "addent" to the method
// always try to reuse as much methods/codes as possible
Please Help me I do not get what he wanted me to do with my code
This is an address book containing 3 classes and this is one of the class that i really had a problem with
import java.util.Scanner;
public class AddressBookApp {
private static Scanner dataReader;
private static AddressBook book;
// TODO Address Book App
public static void main(String[] args) {
book = new AddressBook(10);
dataReader = new Scanner(System.in);
boolean lContinue = true;
while (lContinue) {
switch (Character.toUpperCase(menu())) {
case '1': addBookEntry(); break;
case '2': deleteEntry(); break;
case '3': viewAllEntries(); break;
case '4': editEntry(); break;
case '5': searchEntryByName(); break;
case '6': searchEntryByRecord(); break;
case 'X':
lContinue = false;
break;
default:
System.out.println("\nInvalid Menu option");
}
}
System.out.println("\nEnd of program...");
}
public static char menu() {
char choice;
System.out.println("\nAddressBook Menu");
System.out.println("1. Add Entry");
System.out.println("2. Delete Entry");
System.out.println("3. View all Entries");
System.out.println("4. Update an Entry");
System.out.println("5. Search Entry By Name");
System.out.println("6. Search Entry By Record Number");
System.out.println("X. Exit Program");
System.out.print("\nSelect Menu Option: ");
choice = dataReader.nextLine().charAt(0);
return choice;
}
public static AddressBookEntry getEntryDetails(AddressBookEntry entry) {
if( entry == null ) {
entry = new AddressBookEntry();
}
System.out.print("\nName : "); entry.setName(dataReader.nextLine());
System.out.print("Address : "); entry.setAddress(dataReader.nextLine());
System.out.print("Phone No.: "); entry.setTelNo(dataReader.nextLine());
System.out.print("Email : "); entry.setEmailAdd(dataReader.nextLine());
return entry;
}
public static void addBookEntry() {
AddressBookEntry entry = getEntryDetails(null);
if( entry != null ) {
book.addAddressBookEntry(entry);
}
}
public static void editEntry() {
Scanner datainput = new Scanner(System.in);
System.out.println("Enter record number: ");
int recnumb = datainput.nextInt();
AddressBookEntry addent = new AddressBookEntry();
addent = book.findAddressBookEntryByRecordNo(recnumb);
// The following code (mark by "-")can be replace by getEntryDetails(AddressBookEntry entry)
// you can just pass "addent" to the method
// always try to reuse as much methods/codes as possible
getEntryDetails(AddressBookEntry)
- System.out.println("Name: " + addent.getName());
- System.out.println("Edit Name: ");
- String name = datainput.next();
- addent.setName(name);
- System.out.println("Edit Address: ");
- String address = datainput.next();
- addent.setAddress(address);
- System.out.println("Edit EmailAdd: ");
- String emailAdd = datainput.next();
- addent.setEmailAdd(emailAdd);
- System.out.println("Edit TelNo: ");
- String telNo = datainput.next();
- addent.setTelNo(telNo);
displayEntry(addent, recnumb);
// TODO: edit a single record entry
//System.out.println("\nUnder construction....");
}
public static void searchEntryByRecord() {
try {
Scanner datainput = new Scanner(System.in);
System.out.println("Enter record number: ");
int recnumb = datainput.nextInt();
AddressBookEntry addent = new AddressBookEntry();
addent = book.findAddressBookEntryByRecordNo(recnumb);
System.out.println("Name: " + addent.getName());
System.out.println("Address:" + addent.getAddress());
} catch (Exception NullPointerException) {
// TODO Auto-generated catch block
return;
}
// TODO: search an entry using its record no.
// display "record not found" if such record does not exist.
// Display all its entry.
// Hint: use the method "findAddressBookEntryByRecordNo()"
// from the AddressBook class
//System.out.println("\nUnder construction....");
}
public static void deleteEntry() {
Scanner datainput = new Scanner(System.in);
System.out.println("Enter record number to delete: ");
int recnumb = datainput.nextInt();
if (book.deleteAddressBookEntry(recnumb)) {
System.out.println("Deleted successfully.");
} else {
System.out.println("Record not found");
}
}
// TODO: delete an entry using its record no.
// display "record not found" if such record does not exist.
// Hint: use the method "deleteAddressBookEntry()"
// from the AddressBook class
// display a single record
public static void displayEntry(AddressBookEntry entry, int recNo) {
System.out.println("\nRecord No. " + recNo);
System.out.println("Name : " + entry.getName());
System.out.println("Address : " + entry.getAddress());
System.out.println("Phone No.: " + entry.getTelNo());
System.out.println("Email : " + entry.getEmailAdd());
}
// Search all entries containing name search criteria
public static void searchEntryByName() {
System.out.print("\nSearch[Name]: ");
// ensure no extraneous space and search criteria all in lowercase
String name = dataReader.nextLine().trim().toLowerCase();
// get a reference to the Addressbook list
AddressBookEntry[] list = book.getAllEntries();
for( int i = 0; i < list.length; i++ ) {
// compare search criteria with every entry
if(list[i]!=null && list[i].getName().toLowerCase().contains(name)) {
displayEntry(list[i],i+1);
}
}
System.out.println("No more records follow...");
}
public static void viewAllEntries() {
int validRecords = 0;
// get a reference to the Addressbook list
AddressBookEntry[] list = book.getAllEntries();
if( list.length == 0) {
System.out.println("\nList empty...");
}
for( int i = 0; i < list.length; i++ ) {
if( list[i] != null ) {
displayEntry(list[i],++validRecords);
}
}
System.out.println("No more entries to follow...");
}
}
Remove all lines which start with "-" and use this instead:
getEntryDetails( addent );
In my code below I am not sure what order to put it in to work properly.
I first want it to print out for the user to select an option which it does, then if they select 1 it asks them their name and verifies it with the loop etc.
When I enter a name it starts to just loop the question enter your name and I don't know how to fix it.
Do I need to add more statements to my program, if I do then can I still use if statements for the user to select an option?
import java.util.Scanner;
public class username {
public static void main(String[] args) {
{
int UseLift;
int AuditReport;
int ExitLift;
int a;
UseLift = 1;
AuditReport = 2;
ExitLift = 3;
}
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner d = new Scanner(System.in);
int a = d.nextInt();
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
if (a == 1) {
System.out.println(" Enter your name ");
}
String name1 = kb.nextLine();
boolean b = true;
int j = 0;// counter will start at 0
outerloop:
while (j < 3) {
System.out.println("Enter your name");
}
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift, calling lift ");
}
break;// to stop loop checking names
}
System.out.println("Username Invalid");
j++;
if (a == 2) {
System.out.println("");
}
if (a == 3) {
System.out.println(" Please Exit Lift ");
}
}
}
here you go:
public static void main(String... args) {
String[] verifiedNames = { "barry", "matty", "olly", "joey" };
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
scanner.nextLine(); // get '\n' symbol from previous input
int nameAttemptsLeft = 3;
while (nameAttemptsLeft-- > 0) {
System.out.println(" Enter your name ");
String name = scanner.nextLine();
if (Arrays.asList(verifiedNames).contains(name)) {
System.out.println("dear " + name + " you are verified " +
"you may use the lift, calling lift ");
break; // break out of loop
}
}
if (nameAttemptsLeft < 0) {
System.out.println("Username Invalid");
}
break;
case 2:
System.out.println("option 2");
break;
case 3:
System.out.println(" Please Exit Lift ");
break;
}
scanner.close();
}
Your while loop below:
while (j < 3) {
System.out.println("Enter your name");
}
will loop forever since j is not incrementing (j++). I believe you've mis-matched your curly braces at some point.
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