guys, am doing java programing and try to make a list, but i cannnot let it work as i expected, please help me find out where is wrong.
i have create the code on BlueJ and try to make main and method in different part, but when i try to add a variable in list, it seems added but wont present correctly, and remove method will call error and shut down the whole program
one is :
import java.util.ArrayList;
public class Plane
{
//Create 3 types of variables.
private String name;
private int safelength;
private short station;
private String passengername;
private static int seat;
private static int age;
private ArrayList<Passenger> Passengers;
public Plane(String psgname, int psgseat, int psgage)
{
psgname = passengername;
psgseat = seat;
psgage = age;
Passengers = new ArrayList<Passenger>();
}
public Plane(String planename, int maxlength, short astation)
{
name = planename;
safelength = maxlength;
station = astation;
}
public void addPassenger(Passenger Passenger)
{
Passengers.add(Passenger);
}
public void addPassenger(String passengernames, int pseat, int page)
{
Passengers.add(new Passenger(passengername, seat, page));
}
public Passenger findPassenger(String find)
{
for(Passenger ps : Passengers)
{
if(ps.getpname().contains(find))
{
return ps;
}
}
return null;
}
public int numberofPassenger()
{
return Passengers.size();
}
public void removePassenger(int number)
{
if (number >= 0 && number <numberofPassenger())
{
Passengers.remove(number);
}
}
public void listPassenger()
{
for(int index = 0; index < Passengers.size(); index++)
{
System.out.println(Passengers.get(index));
}
}
public void setname(String n)
{
name = n;
}
public String getname()
{
return name;
}
public void setsafelength(int s)
{
safelength = s;
}
public int getsafelength()
{
return safelength;
}
public void setstation(short a)
{
station = a;
}
public short getstation()
{
return station;
}
public String toString()
{
String text = "System checked, " + getname() + ", you can prepare yourself at station " + getstation() + " with the maxlength of " + getsafelength() + " metres.";
return text;
}
}
another one is :
import java.util.ArrayList;
import java.util.Scanner;
public class Passenger
{
// private varibales of the list.
private static String pname;
private static int seat;
private static int age;
public Passenger(String passengername, int pseat, int page)
{
// initialise instance variables
pname = passengername;
seat = pseat;
age = page;
}
public static void main(String[] args)
{
Plane p = new Plane("Joey", 45, 26);
String text = "Please select your option:\n" + "1.Add a passenger.\n" + "2.Find a passenger.\n" + "3.Total number of passengers.\n" + "4.Remove a passenger.\n" + "5.Print all passengers\n";;
System.out.println(text);
Scanner input = new Scanner(System.in);
int choice = input.nextInt();//waiting type the choice
if(choice > 5 || choice < 0)
{//if choice is wrong
System.out.println("Please select a vailable option!");
}
while(choice <=5 && choice >= 0)
{
if(choice == 1)
{
Scanner inputname = new Scanner(System.in);
System.out.println("Please enter the name of passenger");
String x = inputname.nextLine();
Scanner inputseat = new Scanner(System.in);
System.out.println("Please enter the number of seat.");
int y = inputseat.nextInt();
Scanner inputage = new Scanner(System.in);
System.out.println("Please enter the age of passenger.");
int z = inputage.nextInt();
Passenger padd = new Passenger(pname, seat, age);
p.addPassenger(padd);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 2)
{System.out.println("Please enter the name you want to find.");
String a = input.nextLine();
p.findPassenger(a);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 3)
{
p.numberofPassenger();
System.out.println(text);
choice = input.nextInt();
}
if (choice == 4)
{System.out.println("Please enter the number of list which one you want to remove.");
int b = input.nextInt();
p.removePassenger(b);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 5)
{System.out.println("Here are all the variables of the list.");
p.listPassenger();
System.out.println(text);
choice = input.nextInt();
}
}
}
public static void setpname(String pn)
{
pname = pn;
}
public static String getpname()
{
return pname;
}
}
Problem 1.
public void listPassenger()
{
for(int index = 0; index < Passengers.size(); index++)
{
System.out.println(Passengers.get(index));
}
}
Here you are printing the value of instance variable,not the passenger's name.To print it, do
System.out.println(Passengers.get(index).getpname());
but this will return null,because your pname is static and you have never initialized its value.For this,change all yor static varibales to non-static.
Problem 2.
Passenger padd = new Passenger(pname, seat, age);
you are storing passenger's name seat age in x y zvariables respectively,butduring the creation of Passenger ,you are using pname seat age variables, which are null.So here do
Passenger padd = new Passenger(x, y, z);
At last,change every static variable and methods to non-static.
Final Solution will look like this,
import java.util.ArrayList;
import java.util.Scanner;
public class Passenger
{
// private varibales of the list.
private String pname;
private int seat;
private int age;
public Passenger(String passengername, int pseat, int page)
{
// initialise instance variables
pname = passengername;
seat = pseat;
age = page;
}
public static void main(String[] args)
{
Plane p = new Plane("Joey", 45, 26);
String text = "Please select your option:\n" + "1.Add a passenger.\n" + "2.Find a passenger.\n" + "3.Total number of passengers.\n" + "4.Remove a passenger.\n" + "5.Print all passengers\n";;
System.out.println(text);
Scanner input = new Scanner(System.in);
int choice = input.nextInt();//waiting type the choice
if(choice > 5 || choice < 0)
{//if choice is wrong
System.out.println("Please select a vailable option!");
}
while(choice <=5 && choice >= 0)
{
if(choice == 1)
{
Scanner inputname = new Scanner(System.in);
System.out.println("Please enter the name of passenger");
String x = inputname.nextLine();
Scanner inputseat = new Scanner(System.in);
System.out.println("Please enter the number of seat.");
int y = inputseat.nextInt();
Scanner inputage = new Scanner(System.in);
System.out.println("Please enter the age of passenger.");
int z = inputage.nextInt();
Passenger padd = new Passenger(x, y, z);
p.addPassenger(padd);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 2)
{System.out.println("Please enter the name you want to find.");
String a = input.nextLine();
p.findPassenger(a);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 3)
{
p.numberofPassenger();
System.out.println(text);
choice = input.nextInt();
}
if (choice == 4)
{System.out.println("Please enter the number of list which one you want to remove.");
int b = input.nextInt();
p.removePassenger(b);
System.out.println(text);
choice = input.nextInt();
}
if (choice == 5)
{System.out.println("Here are all the variables of the list.");
p.listPassenger();
System.out.println(text);
choice = input.nextInt();
}
}
}
public void setpname(String pn)
{
pname = pn;
}
public String getpname()
{
return pname;
}
}
Related
When i pass the value to my quick sort method it intialls sets the pivot to the list size but after going through the loop every value gets reset to zero and throws an out of bounds exception.
This is the method in question
public ArrayList<Transaction> myQuickSort(ArrayList<Transaction> list){
ArrayList<Transaction> sorted = new ArrayList<Transaction>();
ArrayList<Transaction> lesser = new ArrayList<Transaction>();
ArrayList<Transaction> greater = new ArrayList<Transaction>();
Transaction pivot = list.get(list.size()-1);
for (int i = 0; i <= list.size()-1; i++){
if(list.get(i).compareTo(pivot) < 0){
lesser.add(list.get(i));
}else{
greater.add(list.get(i));
}
}
lesser = myQuickSort(lesser);
greater = myQuickSort(greater);
lesser.add(pivot);
lesser.addAll(greater);
sorted = lesser;
return sorted;
}
This is the rest of the program
import java.io.IOException;
import java.util.*;
import java.util.HashMap;
import java.time.LocalDate;
public class BankingSystem {
private int option = 0;
int key;
Double newAccBalance;
String transType;
Double transAmount;
ArrayList<Transaction> list = new ArrayList<>();
HashMap<Integer, Account> accounts = new HashMap<>();
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws IOException, InputMismatchException{
BankingSystem bankingSystem = new BankingSystem();
bankingSystem.mainLoop();
}
public void mainLoop() {
option = 0;
while (option != 6) {
display();
option = getKeyboardInteger(keyboard);
if (option == 1) {
createAccount();
} else if (option == 2) {
showAccounts();
} else if (option == 3) {
transaction();
} else if (option == 4) {
deleteAccount();
} else if (option == 5) {
showTransactions();
}
}
}
void display(){
option = 0;
System.out.print("""
---------------------------------------------------------------|
-----------------------Main Menu-------------------------------|
---------------------------------------------------------------|
Please select option |
1. Create Account |
2. Display Accounts |
3. Deposit/Withdraw |
4. Delete Account |
5. View Transactions |
6. Exit Program |
---------------------------------------------------------------|
>""");
}
public void createAccount() {
System.out.print("""
---------------------------------------------------------------|
------------------------Create Account Menu--------------------|
---------------------------------------------------------------|
1. Create Account |
2. Return to Main Menu |
""");
while (option == 1 && option !=2) {
System.out.print("Please enter the new account number > ");
int accNum = getKeyboardInteger(keyboard);
System.out.print("Please enter the name of the account holder > ");
String accName = getKeyboardString(keyboard);
System.out.print("Please enter the address of the account holder>> ");
String accAdd = getKeyboardString(keyboard);
System.out.print("Please enter the starting balance: ");
Double accOpBalance = getKeyboardDouble(keyboard);
LocalDate accOpDate = LocalDate.now();
System.out.print("Account open date: " + accOpDate);
Account newAccount = new Account(accNum, accName, accAdd, accOpDate, accOpBalance);
accounts.put(accNum, newAccount);
System.out.print("*Account " + accNum + " added to database* "+ "\n" + ">");
option = getKeyboardInteger(keyboard);
}
}
public void showAccounts() {
option = 0;
while (option == 1 || option != 2){
System.out.print("""
---------------------------------------------------------------|
-----------------------Show Account Menu-----------------------|
---------------------------------------------------------------|
1. View all Accounts |
2. Return to Main Menu |
>""");
option = getKeyboardInteger(keyboard);
for (Map.Entry<Integer, Account> accountEntry : accounts.entrySet()) {
System.out.println("Account key(number) = " + accountEntry.getKey() + accountEntry.getValue());
System.out.println("---------------------------------------------------------------|");
}
}
}
public void deleteAccount(){
int key;
option = 0;
System.out.print("""
---------------------------------------------------------------|
-----------------------Delete Menu-----------------------------|
---------------------------------------------------------------|
1. Delete Account |
2. Main Menu |
>""");
while(option != -1) {
System.out.print("""
Select Account Number
>""");
key = getKeyboardInteger(keyboard);
accounts.remove(key);
option = getKeyboardInteger(keyboard);
}
}
public void transaction(){
option = 0;
while(option != 3){
System.out.println("""
---------------------------------------------------------------|
-----------------------Transaction Menu------------------------|
---------------------------------------------------------------|
Please select the type of transaction:
1. Deposit
2. Withdraw
3. Main Menu""");
option = getKeyboardInteger(keyboard);
switch(option){
case 1 -> {
doDeposit();
break;
}
case 2 -> {
doWithdrawal();
break;
}
}
}
}
public void doWithdrawal(){
transType = "Withdrawal";
System.out.println("Select Account > ");
key = getKeyboardInteger(keyboard);
System.out.print("How Much would you like to withdraw > ");
transAmount = getKeyboardDouble(keyboard);
Double getBalance = accounts.get(key).getAccOpBalance();
if (transAmount > getBalance) {
System.out.println("Insufficient funds");
}else{
newAccBalance = getBalance - transAmount;
accounts.get(key).setAccOpBalance(newAccBalance);
accounts.get(key).transList.add(new Transaction(transAmount, transType));
}
}
public void doDeposit(){
System.out.println("Select Account > ");
key = getKeyboardInteger(keyboard);
transType = "Deposit";
System.out.print("How Much would you like to deposit? ");
transAmount = getKeyboardDouble(keyboard);
Double getBalance = accounts.get(key).getAccOpBalance();
if (transAmount <= 0) {
System.out.print("Please enter a positive value!");
}else {
newAccBalance = getBalance + transAmount;
accounts.get(key).setAccOpBalance(newAccBalance);
accounts.get(key).transList.add(new Transaction(transAmount, transType));
}
}
public void showTransactions() {
option = 0;
key = getKeyboardInteger(keyboard);
list = accounts.get(key).transList;
myQuickSort(list);
while(option != 2) {
System.out.print("""
---------------------------------------------------------------|
-------------------Show Transactions Menu----------------------|
---------------------------------------------------------------|
1.View Transactions
2.Main Menu
>""");
for(int i = 0; i < accounts.get(key).transList.size(); i++){
System.out.print(accounts.get(key).transList.get(i));
}
option = getKeyboardInteger(keyboard);
}
}
public String getKeyboardString(Scanner keyboard){
while (true){
try{
return keyboard.next();
}catch(Exception e){
keyboard.next();
System.out.print("Something went wrong! Please try again" + "\n> ");
}
}
}
public int getKeyboardInteger(Scanner keyboard){
while(true){
try{
return keyboard.nextInt();
}catch(Exception e){
keyboard.next();
System.out.print("Not an option! Please enter a valid option" + "\n> ");
}
}
}
public Double getKeyboardDouble(Scanner Double){
while(true){
try{
return keyboard.nextDouble();
}catch (Exception e){
keyboard.next();
System.out.print("Not an option! Enter an Integer or Decimal value" + "\n>");
}
}
}
public ArrayList<Transaction> myQuickSort(ArrayList<Transaction> list){
ArrayList<Transaction> sorted = new ArrayList<Transaction>();
ArrayList<Transaction> lesser = new ArrayList<Transaction>();
ArrayList<Transaction> greater = new ArrayList<Transaction>();
Transaction pivot = list.get(list.size()-1);
for (int i = 0; i <= list.size()-1; i++){
if(list.get(i).compareTo(pivot) < 0){
lesser.add(list.get(i));
}else{
greater.add(list.get(i));
}
}
lesser = myQuickSort(lesser);
greater = myQuickSort(greater);
lesser.add(pivot);
lesser.addAll(greater);
sorted = lesser;
return sorted;
}
}
import java.time.LocalDate;
import java.util.ArrayList;
public class Account{
private int accNum;
private String accName;
private String accAdd;
private LocalDate accOpDate;
private Double accOpBalance;
public ArrayList<Transaction> transList;
public Account(int accNum, String accName, String accAdd, LocalDate accOpDate, Double accOpBalance){
setAccNum(accNum);
setAccName(accName);
setAccAdd(accAdd);
setAccOpDate(accOpDate);
setAccOpBalance(accOpBalance);
transList = new ArrayList<Transaction>();
}
public void setAccNum(int accNum){
this.accNum = accNum;
}
public int getAccNum(){
return accNum;
}
public void setAccName(String accName){
this.accName = accName;
}
public void setAccAdd(String accAdd){
this.accAdd = accAdd;
}
public void setAccOpDate(LocalDate accOpDate){
this.accOpDate = accOpDate;
}
public void setAccOpBalance(Double accOpBalance){
this.accOpBalance = accOpBalance;
}
public Double getAccOpBalance(){
return accOpBalance;
}
#Override
public String toString() {
return "\n" + "Account Number: " + accNum + "\n" + "Name: " + accName +
"\n" + "Account Holder Address: " + accAdd + "\n" +"Account open date: "
+ accOpDate + "\n" + "Account balance: " + accOpBalance;
}
}
import java.util.ArrayList;
public class Transaction extends ArrayList implements Comparable<Transaction> {
private Double transAmount;
private String transType;
public Transaction(Double transAmount, String transType){
this.transAmount = transAmount;
this.transType = transType;
}
public void setTransAmount(Double transAmount){
this.transAmount = transAmount;
}
public String getTransType(){
return transType;
}
public void setTransType(String transType){
this.transType = transType;
}
public Double getTransAmount(){
return transAmount;
}
#Override
public int compareTo(Transaction compareAcc){
if(this.transAmount < compareAcc.transAmount)
return -1;
else if (compareAcc.transAmount < this.transAmount)
return 1;
return 0;
}
#Override
public String toString() {
return "\n" + "Transaction type: " + transType +
"\n" + "Amount: " + transAmount + "\n";
}
}
Ive tried running through the code step by step in intellij but cant quite figure it out.
Well, I'd like to make this quick and easy to understand. The problem here is that it recurses infinitely. Everytime it reaches the
lesser = myQuickSort(lesser);
line is recurses. And keep in mind that the list parameter this method receives shrinks in size every time it recurses. Because, for example, the first time you give it a list of size 100 then it gets sorted into lesser/greater and then lesser invokes the method again and it recurses again but this time the arraylist given as the parameter is less than the first. Until it reaches a point where the list has pivot = 0 in it and when it's done sorting that it recurses for one final time and attempts to run this line of code.
Transaction pivot = list.get(list.size()-1);
Which attempts to get the Transaction at the -1 index since the list at this point is empty so the size = 0. This causes an ArrayIndexOutOfBoundsException.
This is a very problematic method and also keep in mind that you probably need a base case to stop it from recurring infinitely and also a few improvements in general.
Hope this helps.
Edit: also due to the infinite recursion this method could cause a stackoverflow error
I am making a function that gets the students' Id, score, last name, and first name and compares them according to their Score, then the last name, and then the first name and prints the result in the descending format.
I have used a Comparator to compare the elements of the array. The problem is that when the user enters -1 as score or ID, the program needs to break and show the result but when I use break, it will add a null value to my array which prevents comparing.
This is my code:
import java.util.Arrays;
import java.util.Scanner;
import java.util.*;
public class Main {
private static class Student {
String fName;
String lName;
int id;
int score;
public Student(String fName, String lName, int id, int score) {
this.fName = fName;
this.lName = lName;
this.id = id;
this.score = score;
}
public int getScore() {
return score;
}
public String getFirstName() {
return fName;
}
public String getLastName() {
return lName;
}
public int getId() {
return id;
}
#Override
public String toString() {
return "id: " + this.id + " " + "fName: " + this.fName + " " + "lName: " + this.lName + " " + "score: " + this.score;
}
}
public static boolean alphabetic(String str) {
char[] charArray = str.toCharArray();
for (char c : charArray) {
if (!Character.isLetter(c)) {
if (c != ' ') {
return false;
}
}
}
return true;
}
static class Comparators implements Comparator<Student> {
#Override
public int compare(Student s1, Student s2) {
int n = Integer.compare(s2.getScore(), s1.getScore());
if (n == 0) {
int last = s1.getLastName().compareTo(s2.getLastName());
return last == 0 ? s1.getFirstName().compareTo(s2.getFirstName()) : last;
} else {
return n;
}
}
}
public static void main(String[] args) {
System.out.println("Enter the number of students");
Scanner input = new Scanner(System.in);
HashSet<Integer> used = new HashSet<>();
List<List<Object>> listData = new ArrayList<List<Object>>();
int k = input.nextInt();
Student[] students = new Student[k];
for (int i = 0; i < k; ) {
System.out.println("Enter id");
int id = input.nextInt();
if (id == -1) {
break;
}
input.nextLine();
System.out.println("Enter first name ");
String fName;
while (alphabetic(fName = input.nextLine()) == false) {
System.out.println("Wrong! please enter again");
}
fName = fName.replace(" ", "");
System.out.println("Enter last name ");
String lName;
while (alphabetic(lName = input.nextLine()) == false) {
System.out.println("Wrong! please enter again");
}
lName = lName.replace(" ", "");
System.out.println("Enter score ");
int score = input.nextInt();
if (score == -1) {
break;
}
if (used.contains(id)) {
listData.add(Arrays.asList(id, lName, fName, score));
continue;
}
used.add(id);
students[i++] = new Student(fName, lName, id, score);
}
Arrays.toString(students);
System.out.println(Arrays.toString(students));
Arrays.sort(students, new Comparators());
Arrays.toString(students);
System.out.println("Data without duplication:");
for (int i = 0; i < k; i++) {
System.out.println(students[i]);
}
if (listData.toArray().length == 0) {
System.out.println("No duplicated Data");
} else {
System.out.println("Data with duplication:");
System.out.println("ID/ LastName/Name/ Score");
System.out.println(Arrays.toString(listData.toArray()));
}
I have tried nullhandlingExpectation methods but I could not get the result I want.
Is there any method to avoid adding the null value to the array while breaking, or remove the null from the array before comparing?
you can put it inside a while loop and put all your code in it and put the condition of breaking it if the value is -1
Note, your array is of predefined size k:
Student[] students = new Student[k];
Therefore, if user needs to break input before entering all k values, you have to truncate the array. E.g.:
if (score == -1) {
students = Arrays.copyOf(students, i);
break;
}
But better consider using ArrayList instead of plain array
I am writing a code whereby I have to input people's name and money value. However I have used a scanner but it does not read the name that I input into the console. Whatever name I put, the code will tell me that no such name is found. I have tried for many hours trying to resolve this, assistance would be appreciated! (there are 6 total cases but I only posted the first one since its the only one I'm having problems with)
The code is as such:
import java.util.Scanner;
public class Client {
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
Change[] changeArray = new Change [10];
int numNames = 0;
System.out.println("Please enter at least 10 records to test the program");
String name = "";
int change = 0;
int flag = 0;
int[] totalNumberOfCoinsOf = {0,0,0,0,0};
for (int i = 0;i < changeArray.length;i++)
{
System.out.println("Enter name: ");
name = reader.nextLine();
do {
System.out.println("Enter coin value for the person");
change = Integer.parseInt(reader.nextLine());
if (change % 5 ==0) {
break;
}else if (change % 5 <2.5) {//round down to nearest 5 if change is less than 2.5
change = change - change %5;
break;
}
else if (change %5>=2.5)
{
change = Math.round(change * 100)/100; //round up to nearest 5 if change is more than 2.5
}
}while (true);
changeArray[i] = new Change(name, change);
numNames++;
do {System.out.println("Do you have another person to enter? (Y/N) ");
String choice = reader.nextLine();
if (i!=changeArray.length - 1) {
if(choice.toUpperCase().equals("Y")) {
break;
}else if (choice.toUpperCase().equals("N")) {
flag = 1;
break;
}
}
}while(true);
if (flag==1) {
break;
}
}
do {
System.out.println("\n[1] Search by name ");
System.out.println("\n[2] Search largest coin");
System.out.println("\n[3] Search smallest coin");
System.out.println("\n[4] Total coins");
System.out.println("\n[5] Sum of coins");
System.out.println("\n[6] Exit the program");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(reader.nextLine());
switch (choice) {
case 1:
System.out.print("Enter name to search: ");
name = reader.nextLine();
flag = 0;
for (int i = 0;i < numNames; i++) {
if (name.equals(changeArray[i].getName())) {
System.out.println("Customer: ");
System.out.println(changeArray[i].getName() + " " + changeArray[i].getCoinChangeAmount());
int[] coins = changeArray[i].getChange();
System.out.println("Change: ");
if(coins[0]!=0) {
System.out.println("Dollar coins: "+coins[0]);
}
if(coins[1]!=0) {
System.out.println("50 cents: "+coins[1]);
}
if(coins[2]!=0) {
System.out.println("25 cents: "+coins[2]);
}
if(coins[3]!=0) {
System.out.println("10 cents: "+coins[3]);
}
if(coins[4]!=0) {
System.out.println("5 cents: "+coins[4]);
}
flag++;
}
}
if (flag==0) {
System.out.println("Name: "+name);
System.out.println("Not found! ");
}
break;
//Change class
import java.util.Scanner;
public class Change {
private String name;
private int coinChangeAmount;
public Change() {
this.name = "no name";
this.coinChangeAmount = 0;
}
public Change(String name, int coinChangeAmount) {
this.name = "name";
this.coinChangeAmount = coinChangeAmount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCoinChangeAmount() {
return coinChangeAmount;
}
I was working on a Uni project for the end of the semester. The program is a simple bank system. My issue is that when the program first launches it creates a "Log" folder. Then when an account object is created using a Constructor a new txt file is created in the folder with the name of the account holder. Up until here I have managed to do it.
The issue is that when closing the program via the option menu but before closing the program, all the details from all the created objects (which are stored in a array) are written in their respective files following the order they are stored in the object array but on the first run the files are created but nothing is written in them.
Then on the 2nd run if I close the program again the details are written correctly. Can I have some suggestions please I could not find anything regarding this online?
import java.util.Scanner;
import java.io.*;
public class FileManagement {
static String pathnameFile = "src\\Log";
static File directory = new File(pathnameFile);
static String[] allFiles = directory.list();
public static void createFolder() {
File logFile = new File(pathnameFile);
if (!logFile.exists()) {
logFile.mkdir();
}
}
public static void writeFiles() throws IOException {
FileWriter writer;
for (int i = 0; i < allFiles.length; i++) {
writer = new FileWriter(pathnameFile + "\\" + allFiles[i]);
writer.write("accountName= " + eBanking.accounts[i].getAccountName() + "\n");
writer.write("PIN= " + eBanking.accounts[i].getPIN() + "\n");
writer.write("balance= " + Integer.toString(eBanking.accounts[i].getBalance()) + "\n");
writer.write("Object ID stored in RAM= " + eBanking.accounts[i].toString() + "\n");
writer.close();
}
}
//original method
/*public static void readFiles() {
Scanner reader;
for (int i = 0; i < allFiles.length; i++) {
reader = new Scanner(pathnameFile + allFiles[i]);
}
}*/
//My solution
public static void readFiles() throws IOException{
if(directory.exists() == false || allFiles == null) {
return;
}
Scanner reader;
File currentFile;
String[] data = new String[4];
for(int i = 0; i < allFiles.length; i++) {
currentFile = new File(pathnameFile + "\\" +allFiles[i]);
reader = new Scanner(currentFile);
int count = 0;
while(reader.hasNextLine()) {
if(!reader.hasNext()) {
break;
}
reader.next();
data[count] = reader.next();
count++;
}
reader.close();
String accountName = data[0];
String PIN = data[1];
int balance = Integer.parseInt(data[2]);
eBanking.accounts[i] = new eBanking(accountName, PIN, balance);
}
}
}
import java.util.Scanner;
import java.io.*;
public class App {
public static eBanking currentAccount;
public static void mainMenu() throws Exception{
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("""
--------------------------------------------------------
1. Log in
2. Register
0. Exit.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
System.out.println("Please enter your account name and PIN below.");
System.out.print("Account name: ");
String accountName = input.next();
System.out.print("PIN: ");
String PIN = input.next();
System.out.println();
for (int i = 0; i < eBanking.accounts.length; i++) {
if (accountName.equals(eBanking.accounts[i].getAccountName()) && PIN.equals(eBanking.accounts[i].getPIN())) {
eBanking.accounts[i].welcome();
currentAccount = eBanking.accounts[i];
break;
}
}
menu();
}
case 2 -> {
System.out.println("Please enter the account name, PIN and inital balance of your new account.");
System.out.print("Account name:");
String accountNameRegister = input.next();
System.out.print("PIN: ");
String registerPIN = input.next();
System.out.print("Initial balance: ");
int initialBalance = input.nextInt();
currentAccount = new eBanking(accountNameRegister, registerPIN, initialBalance);
menu();
}
default -> {
FileManagement.writeFiles();
System.exit(0);
}
}
}
}
public static void menu() {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("""
--------------------------------------------------------
1. Show your balance.
2. Withdraw money.
3. Deposit money.
4. Change your PIN.
5. Transfer money to another person.
0. Back.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
currentAccount.showBalance();
}
case 2 -> {
System.out.println("Please enter the amount you want to withdraw: ");
int withdrawAmount = input.nextInt();
currentAccount.withdraw(withdrawAmount);
}
case 3 -> {
System.out.println("Please enter the amount you want to deposit: ");
int depositAmount = input.nextInt();
currentAccount.deposit(depositAmount);
}
case 4 -> {
currentAccount.changePIN();
}
case 5 -> {
System.out.println("Please enter the amount you want to send: ");
int amount = input.nextInt();
System.out.println("Please enter the account number you want to send the money to: ");
String transferAccount = input.next();// Me nextLine(); duhet ta shkruaj 2 here qe ta marri, duke perdor next(); problemi evitohet (E kam hasur edhe tek c++ kete problem)
System.out.println("The amount of money is completed");
currentAccount.transfer(amount, transferAccount);
}
case 0 -> {
return;
}
default -> {
System.out.println("Please enter a number from the menu list!");
}
}
}
}
public static void main(String[] args) throws Exception {
FileManagement.createFolder();
FileManagement.readFiles();
mainMenu();
}
}
import java.util.Scanner;
import java.io.*;
public class eBanking extends BankAccount {
// Variable declaration
Scanner input = new Scanner(System.in);
private String accountName;
private String accountID;
public static eBanking[] accounts = new eBanking[100];
// Methods
public String getAccountName() {
return accountName;
}
public void welcome() {
System.out.println("---------------------------------------------------------------------------------------");
System.out.println("Hello " + accountName + ". Welcome to eBanking! Your account number is: " + this.accountID);
}
public void transfer(int x, String str) {
boolean foundID = false;
withdraw(x);
if (initialBalance == 0) {
System.out.println("Transaction failed!");
} else if (initialBalance < x) {
for(int i = 0; i < numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += initialBalance;
System.out.println("Transaction completed!");
foundID = true;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += initialBalance;
return;
}
} else {
for(int i = 0; i <= numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += x;
System.out.println("Transaction completed!");
foundID=true;
return;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += x;
return;
}
}
}
// Constructors
public eBanking(String name){
int firstDigit = (int)(Math.random() * 10);
int secondDigit = (int)(Math.random() * 10);
int thirdDigit = (int)(Math.random() * 10);
int forthDigit = (int)(Math.random() * 10);
accountID = this.toString();
PIN = Integer.toString(firstDigit) + secondDigit + thirdDigit + forthDigit; //Nuk e kuptova perse nese i jap Integer.toString te pares i merr te gjitha
balance = 0; //dhe nuk duhet ta perseris per the gjitha
accountName = name;
accounts[numberOfAccount] = this;
numberOfAccount++;
System.out.println("---------------------------------------------------------------------------------------");
System.out.println(accountName + ": Your balance is " + balance + ", your PIN is: " + PIN + " and your account number is: " + accountID);
}
public eBanking(String name, String pin, int x){
if (checkPIN(pin) == false) {
System.out.println("Incorrect PIN format!");
return;
}
accountID = this.toString();
accountName = name;
balance = x;
PIN = pin;
accounts[numberOfAccount] = this;
numberOfAccount++;
welcome();
}
}
import java.util.Scanner;
public abstract class BankAccount {
// Variable declaration
protected String PIN;
protected int balance;
public static int numberOfAccount = 0;
protected static int initialBalance; // E kam perdorur per te bere menune me dinamike sidomos per metoden transfer();
//Methods
//Balance
public int getBalance() {
return balance;
}
public void showBalance() {
System.out.println("The total balance of the account is " + balance);
}
public void withdraw(int x) {
initialBalance = balance;
if (balance == 0) {
System.out.println("The deduction has failed due to lack of balance!");
return;
}
if (balance < x) {
balance = 0;
System.out.println("The deduction of " + initialBalance + " from your balance is completed!");
} else {
balance -= x;
System.out.println("The deduction of " + x + " from your balance is completed!");
}
}
public void deposit(int x) {
balance += x;
System.out.println("You have made a deposit of " + x + " and your current balance is " + balance);
}
//PIN
public String getPIN() {
return PIN;
}
public void changePIN() {
Scanner input = new Scanner(System.in);
System.out.print("Please enter your previous PIN: ");
String tryPIN = input.nextLine();
if (tryPIN.equals(PIN)) {
System.out.print("Please enter your new PIN: ");
String newPIN = input.nextLine();
if (checkPIN(newPIN) == false) {
System.out.println("The PIN is not in the correct format!");
} else {
System.out.println("The PIN has been changed");
PIN = newPIN;
}
} else {
System.out.println("The PIN does not match!");
}
}
protected static boolean checkPIN(String str) {
boolean isValid;
if(str.length() != 4) {
isValid = false;
} else {
try {
int x = Integer.parseInt(str);
isValid = true;
} catch (NumberFormatException e) {
isValid = false;
}
}
return isValid;
}
//Kjo metode duhet per testim
public void getDetails() {
System.out.println(balance + " and PIN " + PIN);
}
}
I have updated the post showing how I fixed it and providing all my classes. Please do not mind the messy code as I am first trying it out with a switch and then will ditch that when the time comes and use GUI as soon as I learn how to use it. Also I know that the classes can be organized better but BankAccount and eBanking are 2 salvaged classes I used on a different exercise.
I think I have found a solution. I just remembered that when using FileWriter if a file does not exist it creates one automatically. So i have cancelled the method which creates a file whenever a new object is created and now whenever the program is closed the files are created if needed or overwritten if they already exist.
I have provided all the current code on my program and the fix I implemented on FileManagment class
I know it's a silly silly program. It's just to practice constructors.
public class PetRecord {
private String name = "Bob";
private int age;
private double weight;
public PetRecord(String initialName, int initialAge, double initialWeight) {
name = initialName;
if(initialAge < 0 || weight < 0) {
System.out.println("Error: Age or weight cannot be negative");
System.exit(0);
}
else {
age = initialAge;
weight = initialWeight;
}
}
public PetRecord(String initialName) {
name = initialName;
}
public void output() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Weight: " + weight);
}
public void setAll(String newName, int newAge, double newWeight) {
name = newName;
if ((newAge < 0) || (newWeight < 0)) {
System.out.println("Error: Negative age or weight.");
System.exit(0);
}
else {
age = newAge;
weight = newWeight;
}
}
public void review() {
if(age < 8 && weight < 8) {
System.out.println("Your pets weight and age are healthy.");
}
if(age >= 8 && weight >=8) {
System.out.println("Your pets weight and age are unhealthy.");
}
else {
System.out.println("Come to my office for a proper assessment.");
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
PetRecord d = new PetRecord("Bob");
System.out.println("Please check if our current records are correct.");
d.output();
System.out.println("Are they correct?");
String answer = input.nextLine();
String yes = "Yes";
String no = "No";
if((answer.equals(yes))) {
System.exit(0);
}
if(answer.equals(no)) {
System.out.println("Please enter your pets name.");
String correctName = input.nextLine();
System.out.println("Age?");
int correctAge = input.nextInt();
System.out.println("Weight?");
double correctWeight = input.nextDouble();
d.setAll(correctName, correctAge, correctWeight);
System.out.println("Your updated records say: ");
d.output();
System.out.println("Would you like a health review?");
String answer1 = input.nextLine();
String yes1 = "yes";
String no1 = "no";
if(answer1.equals(yes1)) {
d.review();
}
if(answer1.equals(no1)) {
System.out.println("Thank you for using PetSystem. Goodbye.");
System.exit(0);
}
}
}
}
My program accepts input for String answer, but my program will not accept String answer1. I can't even type anything in the console after the program asks you if you would like a health review.
The issue comes from here
System.out.println("Your updated records say: ");
d.output();
Because you have printed something out in the middle of accepting input, you most likely have an extra newline token you have not dealt with. Prior to asking the "health review" question place the following code.
while (input.hasNextLine()) {
input.nextLine();
}
This will make sure that you clear out any extra tokens before continuing to accept user input.
you can,t type anything in the console after "if you would like a health review." because you code only runs ones you should put it in a loop to make it run more than once