Java system out println printing more than once - java

does anyone know why "Wrong!!!" is printing out 6 times? Is this something to do with my array list as it contains 6 person ticket details in it.
Thank-you in advance...
public class Method1 {
public static void main(String[] arg) {
Method1 sc = new Method1();
sc.run();
}
private void run() {
PersonData p = new PersonData();
List<PersonType> personDetailsList = (List<PersonType>) p.getList();
int input;
try {
do {
Scanner in = new Scanner(System.in);
System.out.println("Enter person ticket number");
input = in.nextInt();
for (PersonType q : personDetailsList) {
if (q.getPersonNumber() == input) {
System.out.println("Person Ticket Number: " + q.getPersonNumber() + "\n"
+ "Person Ticket Name: " + q.getPersonName() + "\n");
break;
}
else if (q.getPersonNumber() != input) {
System.out.println("Wrong!!!");
}
}
} while (input != -1);
System.out.println("Bye");
} catch (Exception e) {
System.out.println(e);
}
}
}

try this
private void run() {
PersonData p = new PersonData();
List<PersonType> personDetailsList = (List<PersonType>) p.getList();
int input;
boolean flag = false;
try {
do {
Scanner in = new Scanner(System.in);
System.out.println("Enter person ticket number");
input = in.nextInt();
for (PersonType q : personDetailsList) {
if (q.getPersonNumber() == input) {
System.out.println("Person Ticket Number: " + q.getPersonNumber() + "\n"
+ "Person Ticket Name: " + q.getPersonName() + "\n");
flag=true;
break;
}
}
if(!flag){
System.out.println("Wrong!!!");
}
} while (input != -1);
System.out.println("Bye");
} catch (Exception e) {
System.out.println(e);
}
}

Related

I want to store the user data on a notepad to find the mutual friend details and some more things but I'm struggling to store as a txt file

Main.java:
package face;
import java.util.Scanner;
public class Main
{
public static void main (String[]args) throws Exception
{
Scanner sc=new Scanner(System.in);
int choice;
SignUp m = new SignUp();
while (true) {
System.out.
println("1)Customer Sign-up\n2)Customer signin\n3)Stop Program");
choice = sc.nextInt();
switch (choice) {
case 1:
m.customerSignUp();
break;
case 2:
m.customerSignin();
break;
case 3:
System.exit(0);
}
}
}
}
signup.java:
package face;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Scanner;
public class SignUp implements Serializable {
Scanner sc = new Scanner(System.in);
ArrayList<User> customer = new ArrayList<User>();
Home home = new Home();
void customerSignUp() {
System.out.println("Enter the details to sign-up");
System.out.println("Enter the id");
int id = sc.nextInt();
System.out.println("enter the name");
String name = sc.next();
System.out.println("enter the pass");
String pass = sc.next();
System.out.println("Enter the age");
int age = sc.nextInt();
System.out.println("Enter the gender");
String gender = sc.next();
int d = 0;
if (customer.size() > 1) {
for (User c : customer) {
if (c.id == (id)) {
d++;
}
}
}
if (d== 0) {
customer.add(new User(id, name, pass, age, gender));
System.out.println("Back to home page");
} else {
System.out.println("User id already exist");
}
}
void customerSignin() {
System.out.println("Enter id: ");
int id = sc.nextInt();
System.out.println("password to Login:");
String pass = sc.next();
int f = 0;
User currcustomer = null;
for (User c : customer) {
if (c.id == (id) && c.password.equals(pass)) {
currcustomer = c;
f++;
break;
}
}
if (f == 0) {
System.out.println("Invalid Login or Password");
} else {
System.out.println("Logined Successfully...\nWelcome " + currcustomer.name + "\nage " + currcustomer.age
+ "\ngender " + currcustomer.gender);
home.enterHome(currcustomer);
}
}
public void view() {
System.out.println("Enter the user name");
String name = sc.next();
for (User c : customer) {
if (name.equals(c.name)) {
System.out.println("you found the user" + c.name + "\nage " + c.age + "\ngender " + c.gender);
break;
} else {
System.out.println("user name not found");
}
}
}
public void viewAll(User user) {
if (customer.size() > 1) {
for (User c : customer) {
if (c.id != user.id)
System.out.println("User: " + c.name + "\nId: " + c.id + "\nage " + c.age + "\ngender " + c.gender);
}
System.out.println("Do you like to raise a friend request to an account? \n1.Yes 2.No");
int yes = sc.nextInt();
if (yes == 1) {
System.out.println("Enter the account Id to whom you want to raise request:");
int requesterId = sc.nextInt();
raiseRequest(requesterId, user);
}
} else {
System.out.println("There are no users yet other than u");
}
}
public void viewParticularAccount(User user, int targetId) {
User targetUser = null;
for (User c : customer) {
if (c.id != user.id && c.id == targetId) {
System.out.println("You are visiting: " + c.name + "\nage " + c.age + "\ngender " + c.gender);
targetUser = c;
}
}
if (targetUser != null) {
System.out.println("Do you like to raise a friend request to an account? \n1.Yes 2.No");
int yes = sc.nextInt();
if (yes == 1) {
System.out.println("Enter the account Id to whom you want to raise request:");
int requesterId = sc.nextInt();
raiseRequest(requesterId, user);
}
if (yes == 2) {
System.out.println("Do you like to check the mutual friends list of this account? \n1.Yes 2.No");
int showMutualview = sc.nextInt();
if (showMutualview == 1) {
showMutualFriends(user, targetUser);
}
}
} else {
System.out.println("There are no users with the given Id :-) ");
}
}
public void raiseRequest(int requesterId, User user) {
for (User c : customer) {
if (c.id == requesterId) {
c.requesters.add(user);
}
}
}
public void showMutualFriends(User user, User targetUser) {
for (User u : customer) {
if (user.friends.contains(u) && targetUser.friends.contains(u)) {
System.out.println("User : " + u.name + "\nage " + u.age + "\ngender " + u.gender);
}
}
}
}
I created a signup program to get the user details and I stored temporarily, but I need to store it under text file in a notepad for the further programming purpose. But I don't know how to store the user details in a notepad as a txt file. I want to store the received user details in a notepad.
try {
FileWriter writer = new FileWriter(file);
writer.write(text);
writer.close;
catch (IOException e) {
e.printStackTrace();
}
this should write text to a file, given that the file inputted is a txt file

Is it possible to create a text file and then on the same run or runtime of the code also read and write in these files? Java

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

Error in NoSuchElementException

Can somebody help me: I get the following error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at I6Exc2.menuSelection(I6Exc2.java:28)
at I6Exc2.PersonsWrite(I6Exc2.java:120)
at I6Exc2.menuSelection(I6Exc2.java:43)
at I6Exc2.main(I6Exc2.java:19)
This happens when my first input is 3 en my next input is 5. It looks like I did something wrong with closing a scanner? Is somebody able to help me?
Thanks alot.
public class Abc {
public static Person[] names;
public static void main(String[] args) {
menuSelection();
}
public static void menuSelection() {
Scanner s = new Scanner(System.in);
System.out.println( "Choose menu item:" + "\n" + "1. Read File"
+ "\n" + "2. Creates nr objects" + "\n" + "3. Write a File"
+ "\n" + "4. Display nr objects" + "\n" + "5. Exit");
int menuSelection = s.nextInt();
switch (menuSelection) {
case 1: System.out.println("Input a name");
String filePerson = s.next();
PersonRead(filePerson);
break;
case 2: System.out.println("Input nbr of obj");
int p = s.nextInt();
PersonsCreate(p);
break;
case 3: System.out.println("Input a name");
String filePersonWrite = s.next();
PersonWrite(names, filePersonWrite);
break;
case 4: PersonsDisplay(names);
break;
case 5: System.out.println("Good Bye!");
s.close();
break;
default: System.out.println("Invalid choice");
menuSelection();
break;
}
}
public static Person[] PersonRead (String filePerson) {
Person[] names2 = names;
try (FileInputStream fi = new FileInputStream(filePerson)) {
ObjectInputStream os = new ObjectInputStream(fi);
names2 = (Person[])os.readObject();
os.close();
} catch (IOException e) {
System.out.println("Person file not found.");
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("File " + filePerson + " does not contains valid Person object");
}
names = names2;
if (names != null) {
System.out.println("p Person read successfully from file " + filePerson);
}
menuSelection();
return names;
}
public static Person[] PersonsCreate(int p) {
names = new Person[p];
for(int i=0; i < p; i++) {
names[i] = new Person("Mr. Tim" + i, 20 + i, 'M');
}
menuSelection();
return names;
}
public static void PersonWrite (Person[] Person, String filePerson) {
if (names != null) {
try (FileOutputStream fs = new FileOutputStream(filePerson)) {
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(names);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("p Person written successfully to " + filePerson);
} else {
System.out.println("Nothing to write.");
}
menuSelection();
}
public static void PersonsDisplay(Person[] Person) {
for(Person names: Person) {
System.out.println(names);
}
menuSelection();
}
}
NoSuchElementException Thrown by the nextElement, if no more tokens are available
NoSuchElementException
check using hasNextInt(),
if(input.hasNextInt() ){
int p = s.nextInt();
}

Not finding saleID for some reason. the class calls it though

Having problems now, i changed it to accept try and catch and now its not finding the sales ID to compare.
Is anyone able to see what is happening?
has it got something to do with how getSaleID is called?
private static void submitOffer() throws OfferException
{
int offerPrice;
boolean offerAccepted;
System.out.print("Enter sale ID: ");
String saleID = keyboard.nextLine();
try
{
for (int i = 0; i < salesCount; i++)
{
if ( sales[i].getSaleID().equalsIgnoreCase(saleID))
{
System.out.print("Enter offer price: ");
offerPrice = keyboard.nextInt();
keyboard.nextLine();
System.out.println();
//try!!!
offerAccepted = sales[i].makeOffer(offerPrice);
if (offerAccepted == true)
{
System.out.print("Offer was accepted");
if(offerPrice <= sales[i].getReservePrice())
{
System.out.print("Reserve Price was met");
}
else
{
System.out.print("Reserve Price was not met");
}
}
else
{
System.out.print("Offer was not accepted");
}
}
} // for
}
catch(OfferException e)
{
System.out.print("That property with the sale ID " + saleID + "Does not exist");
System.out.println();
}
}

Turning a program - which writes to a file - into a GUI

my program works great and next, I want to turn it into a GUI. I have a menu:
System.out.println("Menu: ");
System.out.println("1) Enter Student Grade(s)");
System.out.println("2) View Student Grade(s)");
System.out.println("3) Delete Student Grade(s)");
System.out.println("4) Exit");
I'm not sure how to implement this into a GUI. I could maybe have 4 text fields: First name, Last name, unit and mark. I could have a button to delete, and a button to open the 'GradeEnter.txt' file perhaps. Again, I am not sure how I would implement this into a separate GUI class. Could anyone help or get me started? Thanks
Code:
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class ExamGrades {
private static int menu = 0;
private static String firstName = "";
private static String firstNameDelete = "";
private static String lastName = "";
private static String lastNameDelete = "";
private static String unit = "";
private static int examMark = 0;
private static String entry = "";
private static String firstCap = "";
private static String surCap = "";
private static Scanner scan = new Scanner(System.in);
public static BufferedWriter bw;
public static BufferedReader reader;
public static PrintWriter out;
public static File deleteRecord;
public static void setup() {
reader = null;
File deleteRecord = new File("GradeEnter.txt");
try {
reader = new BufferedReader(new FileReader(deleteRecord));
} catch (FileNotFoundException e1) {
System.err.println("No file found");
}
FileWriter grades = null;
try {
grades = new FileWriter("GradeEnter.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(grades);
out = new PrintWriter(bw);
}
public static void menuActions()
{
System.out.println("Menu: ");
System.out.println("1) Enter Student Grade(s)");
System.out.println("2) View Student Grade(s)");
System.out.println("3) Delete Student Grade(s)");
System.out.println("4) Exit");
menu = scan.nextInt();
switch(menu) {
case 1:
enterGrades();
break;
case 2:
viewGrades();
break;
case 3:
deleteGrades();
break;
case 4:
exitProgram();
break;
default:
menuActions();
}
}
public static void enterGrades()
{
System.out.print("Please enter student first name: ");
firstName = scan.next();
while(!firstName.matches("[-a-zA-Z]*"))
{
System.out.print("Please enter a valid first name: ");
firstName = scan.next();
}
firstCap = firstName.substring(0,1).toUpperCase() + firstName.substring(1);
System.out.print("Please enter student surname: ");
lastName = scan.next();
while(!lastName.matches("[-a-zA-Z]*"))
{
System.out.print("Please enter a valid surname: ");
lastName = scan.next();
}
surCap = lastName.substring(0,1).toUpperCase() + lastName.substring(1);
System.out.print("Please select Subject Unit: ");
unit = scan.next();
System.out.print("Please enter student mark: ");
while (!scan.hasNextInt())
{
System.out.print("Please enter a valid mark: ");
scan.next();
}
examMark = scan.nextInt();
if (examMark < 40)
{
System.out.println("Failed");
}
else if (examMark >= 40 && examMark <= 49)
{
System.out.println("3rd");
}
else if (examMark >= 50 && examMark <= 59)
{
System.out.println("2/2");
}
else if (examMark >= 60 && examMark <= 69)
{
System.out.println("2/1");
}
else if (examMark >= 70 && examMark <= 100)
{
System.out.println("1st");
}
else
{
System.out.println("Invalid Mark");
}
entry = (firstCap + " " + surCap + ", " + unit + ", " + examMark);
out.println(entry);
menuActions();
}
public static void viewGrades() {
int i =1;
String line;
try {
while ((line = reader.readLine()) != null) {
System.out.println(i + ") " + line);
i++;
}
} catch (IOException e) {
System.err.println("Error, found IOException when searching for record " + e.getMessage());
}
menuActions();
}
public static void deleteGrades(){
int i = 1;
String line;
File tempFile = new File("MyTempFile.txt");
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e) {
System.err.println("Error, found IOException when using BufferedWriter " + e.getMessage());
}
System.out.println("Current Entries Stored: ");
i =1;
try {
while ((line = reader.readLine()) != null) {
System.out.println(i + ") " + line);
i++;
}
} catch (IOException e) {
System.err.println("Error, found IOException when searching for record to delete " + e.getMessage());
}
Scanner scanner = new Scanner(System.in);
System.out.print("To delete, please enter student's First Name: ");
firstNameDelete = scanner.nextLine();
System.out.print("Now, please enter student's Surname: ");
lastNameDelete = scanner.nextLine();
try {
reader.close();
} catch (IOException e) {
System.err.println("Error, found IOException when closing closing reader: " + e.getMessage());
}
try {
reader = new BufferedReader(new FileReader(deleteRecord));
} catch (FileNotFoundException e) {
System.err.println("No file found");
}
String currentLine = "";
try {
currentLine = reader.readLine();
} catch (IOException e) {
System.err.println("Error, found IOException when reading current line " + e.getMessage());
}
while(currentLine != null) {
if(!currentLine.contains(firstNameDelete) && !currentLine.contains(lastNameDelete)) {
try {
writer.write(currentLine);
} catch (IOException e) {
System.err.println("Error, found IOException when deleting line " + e.getMessage());
}
try {
writer.newLine();
} catch (IOException e) {
System.err.println("Error, found IOException when writing a new line " + e.getMessage());
}
}
try {
currentLine = reader.readLine();
} catch (IOException e) {
System.err.println("Error, found IOException when reading file " + e.getMessage());
}
}
System.out.print("if name matches, it will be deleted ");
try {
reader.close();
} catch (IOException e1) {
System.err.println("Error, found IOException when closing reader " + e1.getMessage());
}
try {
writer.close();
} catch (IOException e) {
System.err.println("Error, found IOException when closing writer " + e.getMessage());
}
deleteRecord.delete();
tempFile.renameTo(deleteRecord);
scanner.close();
}
public static void exitProgram(){
System.out.println("Thanks for using 'GradeEnter' ");
System.exit(0);
}
public static void main(String[] args) throws Exception {
System.out.println("Welcome to the 'GradeEnter' program! ");
setup();
menuActions();
out.close();
scan.close();
reader.close();
}
}
EDIT: GradeEnter.txt looks like:
Matt Well, Computing, 100
Adam Smith, Computing, 99
Above is made up of First Name, Last Name, Course and Mark

Categories