how to make fuction to allow me to delete a specific student - java

i want to add a function that allow me to delete a students
first this is the this the file student.java that contain the class student
, then the file called vstudent contain the ittrator and the array list to loop on the all students,then there is a file called Mainsystem contain the files handilling and functions to add students ,so i want to add fuction that allow me to delete a student.
import java.io.*;
import java.util.Scanner;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class student implements Serializable {
private int id;
private String name, email;
private int mobilenumber;
public student(int id, String name, String email, int mobilenumber) {
this.id = id;
this.name=name;
this.email = email;
this.mobilenumber = mobilenumber;
}
public int getId() {
return id;
}
#Override
public String toString() {
return "student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", mobilenumber=" + mobilenumber +
'}';
}
}
import java.io.*;
import java.io.File.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.io.Serializable;
import java.util.Scanner;
public class vstudent extends Object implements Serializable {
private List<student> coll;
public vstudent() {
coll = new ArrayList<student>();
}
public void addstudent(student stu){
coll.add(stu);
}
#Override
public String toString() {
String total = "\n";
Iterator<student> i = coll.iterator();
while (i.hasNext()){
student s = (student) i.next();
total= total+s.toString();
}
return total;
}
}
import java.util.List;
import java.util.Scanner;
import java.io.Serializable;
import java.io.*;
import java.util.Iterator;
class librarianmenu {
public static void librarianMenu() {
System.out.println("---------------(Librarian) - Library Management System-----------");
System.out.println("\nEnter 0 for load a library" + "\nEnter 1 for save and quit" + "\nEnter 2 to add book"
+ "\nEnter 3 to list all books in library" + "\nEnter 4 to list all librarians");
}
}
public class Mainsystem {
static String fileName = null;
static library lib = new library();
static vstudent stu = new vstudent();
static librs librs = new librs();
static Scanner in = new Scanner(System.in);
static Boolean running = true;
public static void DisplayMainMenu() {
System.out.println("------------ Library Management System ------------");
System.out.println("Enter #: Switch to Admin Mode");
System.out.println("Enter $: Switch to Student Mode");
System.out.println("Enter <: Exit");
}
public static void main(String[] args) {
DisplayMainMenu();
Scanner in = new Scanner(System.in);
boolean shouldContinue = true;
while (true) {
String optionSelected = in.next();
if (!optionSelected.equals("<")) {
if (optionSelected.equals("#")) {
Admin admin = new Admin();
System.out.print("Enter Password: ");
String tempPassword = in.next();
System.out.println(tempPassword);
if (tempPassword.equals(admin.getPassword())) {
boolean isCorrectPassword = true;
while (isCorrectPassword) {
admin.displayMenu();
int adminInput = in.nextInt();
switch (adminInput) {
case 0: {
System.out.println("Enter the file name to load");
loadScript(in.next());
break;
}
case 1: {
addstudent();
break;
}
case 2: {
addlibrarians();
break;
}
case 3: {
System.out.println(stu.toString());
break;
}
case 4: {
saveandquit();
break;
}
case 5: {
System.out.print("Enter new password:");
String pass = in.next();
admin.setPassword(pass);
break;
}
case 6: {
isCorrectPassword = false;
DisplayMainMenu();
}
}
}
} else {
DisplayMainMenu();
}
} else if (optionSelected.equals("$")) {
librarianmenu menu = new librarianmenu();
while (running) {
librarianmenu.librarianMenu();
int studentInput = in.nextInt();
switch (studentInput) {
case 0: {
System.out.println("Enter the file name to load");
loadScript(in.next());
break;
}
case 1: {
saveandquit();
break;
}
case 2: {
addBook();
break;
}
case 3: {
System.out.println(lib.toString());
break;
}
case 4: {
System.out.println(librs.toString());
}
}
}
} else { //User chooses to Exit
break;
}
}
}
}
private static void addBook () {
int id;
String title, author;
int Available_quantity;
int issued_quantity;
System.out.println("\nEnter book name");
title = in.next();
System.out.println("\nEnter book Author");
author = in.next();
System.out.println("\nEnter book id");
id = in.nextInt();
System.out.println("\nEnter Available quantity");
Available_quantity = in.nextInt();
System.out.println("\nEnter issued_quantity");
issued_quantity = in.nextInt();
Book b = new Book(id, title, author, Available_quantity, issued_quantity);
lib.addBook(b);
}
private static void addstudent () {
int id;
String name, email;
int mobilenumber;
System.out.println("\nEnter student name");
name = in.next();
System.out.println("\nEnter student email");
email = in.next();
System.out.println("\nEnter student id");
id = in.nextInt();
System.out.println("\nEnter mobile number ");
mobilenumber = in.nextInt();
student s = new student(id, name, email, mobilenumber);
stu.addstudent(s);
}
private static void addlibrarians () {
int id;
String name;
int password;
System.out.println("\nEnter librarian name");
name = in.next();
System.out.println("\nEnter librarian id");
id = in.nextInt();
System.out.println("\nEnter password ");
password = in.nextInt();
librarians libras = new librarians(id, name, password);
librs.addlibrs(libras);
}
private static void saveandquit () {
System.out.println("Enter file name:");
fileName = in.next() + ".ser";
running = false;
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(fileName);
out = new ObjectOutputStream(fos);
out.writeObject(lib);
out.writeObject(stu);
fos.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void loadScript (String name){
FileInputStream fis = null;
ObjectInputStream in = null;
File file = new File(name + ".ser");
if (file.exists()) {
try {
fis = new FileInputStream(file);
in = new ObjectInputStream(fis);
try {
lib = (library) in.readObject();
stu = (vstudent) in.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
fis.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("\nThe file does not exist!");
}
}
}

As I can see , You use List from which you want to delete element,
In Java if you want to delete element you need to provide its id ,
Syntax :
StudentList.remove(idStudent)
for you i think you want to find a way to get the ID of the student you want to delete this is a way:
private static void deleteStudent () {
System.out.println("\nEnter ID of the student you want to delete ");
idStudent = in.nextInt();
for( Student st : stu){
if(st.getID()==idStudent){
stu.remove(idStudent);
}
}
}

Related

Serialization of Custom object from an ArrayList to a txt file

I have a base abstract class Contact and two sub classes Person and Organization.
I'm doing an exercise where i have to serialize the objects that i'm storing inside
ArrayList contactsArray = new ArrayList<>();
as long i add Person object and Organization object to it i have no problem, cause, correct me if i'm wrong even if i declared the ArrayList it can store subclasses type objects. So till then it worked, but if i try now
to serialize it i get the error. I read that all sub classes of a super class that implement the serialize interface don't need to implement it themself because they are already inheriting it.
Once i initialize the object i choose between Person or Organization i store it in the
ArrayList contactsArray = new ArrayList<>();
after that i get the error exactly when it tries to execute this line.
oos.writeObject(obj);
my question is:
in my situation, with a direct inheritance, am i doing wrong implementing the Serialization interface only in the Superclass Contact? Is the error coming from my bad implementation of it? Or it's just because i'm doing something wrong with the classes types and the ArrayList i use? To be more precise when i pass it as parameter to the method:
serializeContact(ArrayList<Contact> obj)
Could it be because i didn't define well the file path? The txt file is in the same folder of the class java files, maybe it can't be written and it needs some kind of writing permission?
This is the error i get:
java.io.NotSerializableException: java.util.Scanner
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1185)
at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:349)
at java.base/java.util.ArrayList.writeObject(ArrayList.java:897)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at java.base/java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1145)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1497)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:349)
at contacts.App.serializeContact(App.java:76)
at contacts.App.addRecord(App.java:61)
at contacts.App.menu(App.java:167)
at contacts.Main.main(Main.java:5)
Something went wrong
[menu] Enter action (add, list, search, count, exit):
Below my full code:
contacts/Main.java
package contacts;
public class Main {
public static void main(String[] args) {
App application = new App();
application.menu();
}
}
contacts/App.java
package contacts;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Scanner;
class App {
ArrayList<Contact> contactsArray = new ArrayList<>();
Scanner sc = new Scanner(System.in);
public void countRecords() {
System.out.println("The Phone Book has " + this.contactsArray.size() + "
records.\n");
}
public void listRecords() {
if(this.contactsArray.size() == 0) {
System.out.println("No records to list!\n");
menu();
} else {
showRecordFields();
}
System.out.println("Enter index to show info: ");
int choiceRecord = Integer.valueOf(sc.nextLine()) - 1;
if(this.contactsArray.get(choiceRecord).isPerson()) {
Person selection = (Person) this.contactsArray.get(choiceRecord);
selection.showInfo();
} else {
Organization selection = (Organization) this.contactsArray.get(choiceRecord);
selection.showInfo();
}
}
public void showRecordFields() {
if(this.contactsArray.size() == 0) {
System.out.println("No records to list!\n");
} else {
for (int i = 0; i < this.contactsArray.size(); i++) {
if(this.contactsArray.get(i).isPerson()) {
Person selection = (Person) this.contactsArray.get(i);
System.out.println((i + 1) + "." + " " + selection.getName() + " " +
selection.getSurname());
} else {
Organization selection = (Organization) this.contactsArray.get(i);
System.out.println((i + 1) + "." + " " + selection.nameOganization);
}
}
}
}
public void addRecord() {
System.out.println("Enter the type (person, organization): ");
String typeofcontact = sc.nextLine();
switch (typeofcontact) {
case "person":
Person person = new Person();
this.contactsArray.add(person);
serializeContact(contactsArray);
break;
case "organization":
Organization organization = new Organization();
this.contactsArray.add(organization);
serializeContact(contactsArray);
break;
}
}
public void serializeContact(ArrayList<Contact> obj) {
try
{
FileOutputStream fos = new FileOutputStream("./contacts/contactsdata.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close();
fos.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
System.out.println("Something went wrong");
}
}
public void removeRecord() {
if(this.contactsArray.size() == 0) {
System.out.println("No records to remove!\n");
} else {
System.out.println("Select a record: ");
this.showRecordFields();
int choiceRecord = Integer.valueOf(sc.nextLine()) - 1;
this.contactsArray.remove(choiceRecord);
System.out.println("The record removed!\n");
}
}
public void editRecord() {
if(this.contactsArray.size() == 0) {
System.out.println("No records to edit!\n");
} else {
this.showRecordFields();
System.out.println("Select a record: ");
int choiceRecord = Integer.valueOf(sc.nextLine()) - 1;
if(this.contactsArray.get(choiceRecord).isPerson()) {
Person selection = (Person) this.contactsArray.get(choiceRecord);
selection.editContact();
selection.setDateLastEdit();
} else {
Organization selection = (Organization) this.contactsArray.get(choiceRecord);
selection.editContact();
selection.setDateLastEdit();
}
System.out.println("The record updated!\n");
}
}
public String menuOptionsSearch(Scanner sc) {
System.out.println("[search] Enter action ([number], back, again): ");
return sc.nextLine();
}
public void menuSearch() {
switch (this.menuOptionsSearch(sc)) {
case "back":
this.countRecords();
menu();
case "again":
this.editRecord();
menu();
case "":
this.removeRecord();
menu();
}
}
public String menuOptions(Scanner sc) {
System.out.println("[menu] Enter action (add, list, search, count, exit): ");
return sc.nextLine();
}
public void search() {
if(this.contactsArray.size() == 0) {
System.out.println("No records to search!\n");
menu();
}
String choiceSearch = sc.nextLine();
}
public void menu() {
switch (this.menuOptions(sc)) {
case "count":
this.countRecords();
menu();
case "edit":
this.editRecord();
menu();
// case "remove":
// this.removeRecord();
// menu();
// case "search":
// this.search();
// menu();
case "add":
this.addRecord();
menu();
case "list":
this.listRecords();
menu();
case "exit":
System.exit(0);
default:
System.out.println("Wrong field name");
menu();
}
}
}
contacts/Contact.java
package contacts;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Scanner;
import java.time.LocalDateTime;
abstract class Contact implements Serializable {
private static final long serialVersionUID = 7L;
Scanner sc = new Scanner(System.in);
String number;
LocalDateTime dateCreation;
LocalDateTime dateLastEdit;
abstract void showInfo();
abstract void editContact();
public String getNumber() {
return this.number;
}
public void setNumber() {
System.out.println("Enter the number: ");
checkNumber(sc.nextLine());
}
public void checkNumber(String number) {
String regex = "^\\+?(\\(\\w+\\)|\\w+[ -]\\(\\w{2,}\\)|\\w+)([ -]\\w{2,})*";
if(number.matches(regex)) {
this.number = number;
} else {
System.out.println("Wrong number format!");
this.number = "[no number]";
}
}
public boolean isPerson() {
return this.getClass() == Person.class;
}
public void setDateCreation() {
this.dateCreation = LocalDateTime.now().withSecond(0).withNano(0);
}
public void setDateLastEdit() {
this.dateLastEdit = LocalDateTime.now().withSecond(0).withNano(0);
}
}
contacts/Person.java
package contacts;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.io.Serializable;
public class Person extends Contact {
String name;
String surname;
String birthdate;
String gender;
public Person() {
setName();
setSurname();
setBirthdate();
setGender();
setNumber();
setDateCreation();
setDateLastEdit();
System.out.println("The record added.\n");
}
public void showInfo() {
System.out.println("Name: " + this.name +
"\nSurname: " + this.surname +
"\nBirth date: " + this.birthdate +
"\nGender: " + this.gender +
"\nNumber: " + this.number +
"\nTime created: " + this.dateCreation +
"\nTime last edit: " + this.dateLastEdit + "\n");
}
public void setName() {
System.out.println("Enter the name: ");
this.name = sc.nextLine();
}
public void setSurname() {
System.out.println("Enter the surname: ");
this.surname = sc.nextLine();
}
public String getName() {
return this.name;
}
public String getSurname() {
return this.surname;
}
public void setGender() {
System.out.println("Enter the gender (M, F): ");
String choice = sc.nextLine();
if(choice.equals("M")){
this.gender = choice;
} else if (choice.equals("F")) {
this.gender = choice;
} else {
System.out.println("Bad gender!");
this.gender = "[no data]";
}
}
public String getGender() {
return this.gender;
}
public void setBirthdate() {
try {
System.out.println("Enter the birth date: ");
String choice;
choice = sc.nextLine();
this.birthdate = LocalDate.parse(choice).toString();
} catch (DateTimeException dateTimeException) {
System.out.println("Bad birth date!");
this.birthdate = "[no data]";
}
}
public String getBirthdate() {
return this.birthdate;
}
public void editContact() {
String choiceField;
System.out.println("Select a field (name, surname, birth, gender, number): ");
choiceField = sc.nextLine();
switch (choiceField) {
case "name":
this.setName();
break;
case "surname":
this.setSurname();
break;
case "birth":
this.setBirthdate();
break;
case "gender":
this.setGender();
break;
case "number":
this.setNumber();
break;
default:
System.out.println("Wrong field name");
break;
}
}
}
contacts/Organization.java
package contacts;
import java.io.Serializable;
public class Organization extends Contact {
String nameOganization;
String address;
public Organization() {
setOraganizationName();
setOrganizationAdress();
setNumber();
setDateCreation();
setDateLastEdit();
System.out.println("The record added.\n");
}
public void showInfo() {
System.out.println("Organization name: " + this.nameOganization +
"\nAddress: " + this.address +
"\nNumber: " + this.number +
"\nTime created: " + this.dateCreation +
"\nTime last edit: " + this.dateLastEdit + "\n");
}
public void setOraganizationName() {
System.out.println("Enter the organization name: ");
this.nameOganization = sc.nextLine();
}
public void setOrganizationAdress() {
System.out.println("Enter the address: ");
this.address = sc.nextLine();
}
public void editContact() {
String choiceField;
System.out.println("Select a field (organization name, address, number): ");
choiceField = sc.nextLine();
switch (choiceField) {
case "name":
this.setOraganizationName();
break;
case "address":
this.setOrganizationAdress();
break;
case "number":
this.setNumber();
break;
default:
System.out.println("Wrong field name");
break;
}
}
}

Error of "variable might not initialized" while trying to use a class object as a parameter of a method, tried to use a IF to avoid the problem (JAVA)

I'm learning JAVA and I was making the code for a product sales system in a store as an example. So I created the Product, Customer and Sale classes.
In my menu I check if there is a registered product or customer, if yes I call my sales method that has both parameters. However, NetBeans notifies an error that the variable has not been initialized even with the logic not to start the sale if the registration has not been done before.
My basic code:
"variable product might not have been initialized"
"variable customer might not have been initialized"
//Main
//Reg a client and a product, then perform a sale.
package store;
import java.util.Random;
import java.util.Scanner;
public class Store {
static boolean flagProduct=false, flagCustomer=false;
public static void main(String[] args) {
menu();
}
public static void menu() {
System.out.println("\n Choose option:\n"
+ "1 - Product Registration\n"
+ "2 - Customer Registration\n"
+ "3 - Sell\n"
+ "4 - End\n"
);
Scanner scanner = new Scanner(System.in);
int select = scanner.nextInt();
switch (select) {
case 1:
Product product = RegistProduct();
System.out.print("\n Cod product : " + product.getCodProduct());
System.out.print("\n Price product : " + product.getPriceProduct());
System.out.print("\n Quantity product : " + product.getQuantProduct());
menu();break;
case 2:
Customer customer = RegistCustomer();
System.out.print("\n Cod Customer : " + customer.getCodCustomer());
System.out.print("\n Customer name: " + customer.getName());
menu();break;
case 3:
if(flagProduct == true && flagCustomer==true){
Sale sale = sell(product, customer); // *****where the error happens*****
System.out.print("\n Sale code : " + sale.getCodSale());
System.out.print("\n Customer name: " + customer.getName());
System.out.print("\n Cod product : " + product.getCodProduct()+ " -- Quantity:" + sale.getQuantSale()+ " -- Total:" + sale.getValueSale());
} else if(flagProduct == true && flagCustomer==false){
System.out.println("First register the customer ");
menu();break;
} else if(flagProduct == false && flagCustomer==true){
System.out.println("First register the product");
menu();break;
} else
System.out.println("First register the customer and product");
menu();break;
case 4:
break;
default:
System.out.println("Error");
menu();
}
}
public static Product RegistProduct(){
Product product = new Product();
java.util.Scanner scanner = new Scanner(System.in);
System.out.print("Product code:\n");
product.setCodProduct(scanner.nextInt());
System.out.print("Product price:\n");
product.setPriceProduct(scanner.nextFloat());
System.out.print("Product quantity:\n");
product.setQuantProduct(scanner.nextInt());
flagProduct = true;
return product;
}
public static Customer RegistCustomer(){
Customer customer = new Customer();
java.util.Scanner scanner = new Scanner(System.in);
System.out.print("Customer name:\n");
customer.setName(scanner.nextLine());
System.out.print("Customer code:\n");
customer.setCodCustomer(scanner.nextInt());
flagCustomer=true;
return customer;
}
public static Sale Sell(Product product, Customer customer){
java.util.Scanner scanner = new Scanner(System.in);
Random num = new Random();
int codSale = num.nextInt(9999);
Sale sale = new Sale();
sale.setCodSale(codSale);
System.out.print("Customer code:");
int codSaleCustomer = scanner.nextInt();
while (codSaleCustomer != customer.getCodCustomer()){
System.out.print("Non-existent code. Please enter a valid code:\n");
codSaleCustomer = scanner.nextInt();
}
System.out.print("Product code:");
int codSaleProduct = scanner.nextInt();
while (codSaleProduct != product.getCodProduct()){
System.out.print("Non-existent code. Please enter a valid code:\n");
codSaleProduct = scanner.nextInt();
}
System.out.print("Quantity of products purchased:\n");
sale.setQuantSale(scanner.nextInt());
sale.setValueSale(sale.getQuantSale()*product.getPriceProduct());
product.setQuantProduct(product.getQuantProduct() - sale.getQuantSale());
System.out.print("Remaining quantity in stock: "+ product.getQuantProduct());
return sale;
}
}
//Class Product
package store;
public class Product {
private int codProduct;
private float priceProduct;
private int quantProduct;
public int getCodProduct() {
return codProduct;
}
public void setCodProduct(int codProduct) {
this.codProduct = codProduct;
}
public float getPriceProduct() {
return priceProduct;
}
public void setPriceProduct(float priceProduct) {
this.priceProduct = priceProduct;
}
public int getQuantProduct() {
return quantProduct;
}
public void setQuantProduct(int quantProduct) {
this.quantProduct = quantProduct;
}
}
//Class customer
package store;
public class Customer {
private int codCustomer;
private String name;
public int getCodCustomer() {
return codCustomer;
}
public void setCodCustomer(int codCustomer) {
this.codCustomer = codCustomer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//Class sale
package store;
public class Sale extends Product{ //I dnno if extends is necessary
private int codSale;
private int quantSale;
private float valueSale;
public int getCodSale() {
return codSale;
}
public void setCodSale(int codSale) {
this.codSale = codSale;
}
public int getQuantSale() {
return quantSale;
}
public void setQuantSale(int quantSale) {
this.quantSale = quantSale;
}
public float getValueSale() {
return valueSale;
}
public void setValueSale(float valueSale) {
this.valueSale = valueSale;
}
}

Solving Exception in thread "main" java.util.InputMismatchException

I'm working on a shop program and i'm trying to find the total value of the products in stock. The data related to each item is present in a row of the file named "SHOP.txt", like : "H;L;10;€10,50;83259875;YellowPaint"(that is the first line of the file where all the products are saved in this format, separated by ";" : department,unityOfmeasure,quantity,price,code,name).To calculate the total value, the program read each token from the aforementioned line and calculate the value by multiplying quantity for price.
I already saved in the file about 10 products but when i try to compile my code, I keep getting an error and it calculate the value only of the first product.
public static void main(String[] args) throws IOException {
while (running) {
System.out.println("\nPress 0 to load the inventory. " + "\nPress 1 to save and close"
+ "\nPress 2 to add products to the inventory" + "\nPress 3 to find products"
+ "\nPress 4 for the total value of the inventory");
int answer = in.nextInt();
switch (answer) {
case 0:
System.out.println("insert the name of the file to load");
Loading(in.next());
break;
case 1:
saveAndQuit();
break;
case 2:
addProduct();
break;
case 3:
inputCode();
break;
case 4:
inventoryValue();
break;
}
}
System.exit(0);
}
private static void inventoryValue() throws FileNotFoundException {
Scanner scanner = new Scanner(new File("SHOP.txt"));
scanner.useDelimiter(";|\n");
Product[] products = new Product[0];
while (scanner.hasNext()) {
String department = scanner.next();
String unityOfMeasure = scanner.next();
int quantity = scanner.nextInt();
double price = scanner.nextDouble();
String code = scanner.next();
String name = scanner.next();
Product newProduct = new Product(department, unityOfMeasure, quantity, price, code, name);
products = newProduct(products, newProduct);
double totalValue = Arrays.stream(products).mapToDouble(p -> p.quantity * p.price).sum();
System.out.println("Total Value: " + totalValue + "\n\n");
for (Product product : products) {
System.out.println(product);
}
}
}
private static Product[] newProduct(Product[] products, Product productToAdd) {
Product[] newProducts = new Product[products.length + 1];
System.arraycopy(products, 0, newProducts, 0, products.length);
newProducts[newProducts.length - 1] = productToAdd;
return newProduct;
}
This is the complete code as requested.
Product Class:
public class Product implements Serializable {
protected String department;
protected String unityOfMeasure;
protected int quantity;
protected double price;
protected String code;
protected String name;
private static NumberFormat formatter = new DecimalFormat("#0.00");
public Product(String dep, String uom, int qnt, double prz, String cod, String nm) {
reparto = dep;
unitaDiMisura = uom;
quantità = qnt;
prezzo = prz;
codice = cod;
nome = nm;
}
// setters
public void setDep(String rep) {
this.department = department;
}
public void setPrz(double prz) {
this.price = price;
}
public void setUdm(String udm) {
this.unityOfMeasure = unityOfMeasure;
}
public void setQnt(int qnt) {
this.quantity = quantity;
}
public void setCod(String cod) {
this.code = code;
}
public void setNm(String nm) {
this.name = name;
}
// getters
public String getDep() {
return department;
}
public String getUom() {
return unityOfMeasure;
}
public double getPrz() {
return price;
}
public int getQnt() {
return quantity;
}
public String getCod() {
return code;
}
public String getNm() {
return name;
}
public double getTotal() {
return quantity * price;
}
public void remove() {
this.quantity--;
}
public String toString() {
// ----quantity not less than 0 ----
if (quantity < 0) {
System.out.println(quantity = 0);
}
return String.format(department + ";" + unityOfMeasure + ";" + quantity + ";" + "€" + formatter.format(price) + ";"
+ code+ ";" + name + " \n");
}
}
Shop Class:
public class Shop implements Serializable {
public List<Product> collection;
public Shop() {
collection = new ArrayList<Product>();
}
public void addProduct(Product product) {
collection.add(product);
}
public void sellProduct(String name) {
for (Product product : collection) {
if (name.equals(product.getNm())) {
if (product.getQnt() >= 0) {
prodotto.remove();
}
return;
}
}
}
public void duplicatedProduct(String code) {
for (Product product : collection) {
if (code.equals(product.getCod())) {
System.out.println("Error. Duplicated product");
}
return ;
}
}
#Override
public String toString() {
String total = "\n";
Iterator<Product> i = collection.iterator();
while (i.hasNext()) {
Product l = (Product) i.next();
total = total + l.toString();
}
return total;
}
}
Main Class:
public class Main {
static String fileName = null;
static Shop shp = new Shop();
static Scanner in = new Scanner(System.in);
static boolean running = true;
public static void main(String[] args) throws IOException {
while (running) {
System.out.println("\nPress 0 to load inventory. " + "\nPress 1 to save and quit"
+ "\nPress 2 to add product to the inventory" + "\nPress 3 to find a product"
+ "\nPress 4 for the total value of the inventory");
int answer = in.nextInt();
switch (answer) {
case 0:
System.out.println("Insert the name file to load.");
Loading(in.next());
break;
case 1:
saveAndQuit();
break;
case 2:
addProduct();
break;
case 3:
inputCode();
break;
case 4:
inventoryValue();
break;
}
}
System.exit(0);
}
private static void inventoryValue() throws FileNotFoundException {
Scanner scanner = new Scanner(new File("SHOP.txt"));
scanner.useDelimiter(";|\n");
Product[] products = new Product[0];
while (scanner.hasNext()) {
String department = scanner.next();
String unityOfMeasure = scanner.next();
int quantity = scanner.nextInt();
double price = scanner.nextDouble();
String code = scanner.next();
String name = scanner.next();
Product newProduct = new Product(department, unityOfMeasure, quantity, price, code, name);
products = newProduct(products, newProduct);
double totalValue = Arrays.stream(products).mapToDouble(p -> p.quantity * p.price).sum();
System.out.println("Total Value: " + totalValue + "\n\n");
for (Product product : products) {
System.out.println(product);
}
}
}
private static Product[] newProduct(Product[] products, Product productToAdd) {
Product[] newProducts = new Product[products.length + 1];
System.arraycopy(products, 0, newProducts, 0, products.length);
newProducts[newProducts.length - 1] = productToAdd;
return newProduct;
}
private static void inputCode() throws IOException {
String code;
String line = null;
System.out.println("\nInsert code: ");
code = in.next();
try {
FileReader fileReader = new FileReader("SHOP.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
String[] token = line.split(";");
if ((";" + line + ";").contains((";" + code + ";"))) {
System.out.println(line);
}
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Impossible to open the file ");
} catch (IOException ex) {
System.out.println("error opening the file ");
}
}
private static void addProduct() {
String department;
String unityOfMeasure;
int quantity;
double price;
String code;
String name;
System.out.println("\ninsert department: ");
department= in.next();
System.out.println("\ninsert unity of measure: ");
unityOfMeasure = in.next();
System.out.println("\ninserit quantity: ");
quantity = in.nextInt();
System.out.println("\ninsert price: ");
price = in.nextDouble();
System.out.println("\ninsert code: ");
code = in.next();
System.out.println("\ninsert name: \n");
name = in.next();
Product p = new Product(department, unityOfMeasure, quantity, price, code, name);
shp.addProduct(p);
}
private static void saveAndQuit() {
running = false;
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(new FileWriter("SHOP.txt", true));
printWriter.println(shp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (printWriter != null) {
printWriter.close();
}
}
}
private static void Loading(String name) throws IOException {
FileReader fr;
fr = new FileReader("SHOP.txt");
BufferedReader br;
br = new BufferedReader(fr);
String s;
while (true) {
s = br.readLine();
if (s == null)
break;
System.out.println(s);
}
br.close();
fr.close();
}
}
This is the content of the txt File (SHOP.txt) where products are stored :
H;L;10;10,50;83259875;YellowPaint
E;U;20;1,50;87678350;Lamp
H;L;10;10,50;83259891;BluePaint
H;L;10;10,00;83259892;RedPAint
H;U;30;12,00;98123742;Hammer
G;U;80;15,00;87589302;Seeds
G;U;3;130,00;17483921;Lawnmower
this is the error that i expect to solve:
Total value: 105.0
H;L;10;€10,50;83259875;YellowPaint
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Main.inventoryValue(Main.java:68)
at Main.main(Main.java:47)
How can I solve this problem?
In your file where you say it is storing a double for the price, it should just be a decimal value. You have a '€' symbol in front of it and a ',' instead of a '.'. scanner.nextDouble() will not work if there is another symbol there. I'd recommend to store your prices without the currency symbol and a decimal rather than a comma and just append the '€' in front of wherever you plan on showing your total as so:
System.out.println("Total Value: €" + totalValue + "\n\n");

array in object oriented programming

I'm a beginner in object-oriented programming and this is my first little project.I've heard that here everyone can help you in your code and this is my first time.Anyway, my problem why array doesn't store any value?
Here is the code:
public class Information {
private IT_Members[] member= new IT_Members[10];
private int counter = 0;
Information()
{
for ( int ctr=0;ctr<member.length;ctr++)
{
member[ctr] = new IT_Members ();
}
}
public void Add(IT_Members member)
{
if(counter<10)
{
this.member[counter].setName(member.getName());
this.member[counter].setDeparment(member.getDeparment());
this.member[counter].setPostion(member.getPostion());
this.member[counter].setID(member.getID()+counter);
counter++;
}
else
System.out.println("Add List Full");
}
public void Display()
{
if (counter!=0)
{
for (int ctr=0;ctr<10;ctr++){
System.out.println(this.member[ctr].getName()+
this.member[ctr].getDeparment()+
this.member[ctr].getPostion()+
this.member[ctr].getID());
}
}
else
System.out.println("No member yet!");
}
Here is the Main class:
import java.util.Scanner;
import java.util.Arrays;
public class Interface {
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
IT_Members input1 = new IT_Members();
Information input2 = new Information();
int x=1;
while(x!=0)
{
System.out.println(" \n[1] Add new student member. \n[2] View members.\nChoose now: ");
int choose = in.nextInt();
switch (choose){
case 1:
System.out.println("Name: ");
input1.setName(in.nextLine());
System.out.println("Deparment: ");
input1.setDeparment(in.nextLine());
System.out.println("Postion: ");
input1.setPostion(in.nextLine());
System.out.println("Student record has been added. ");
break;
case 2:
input2.Display();
break;
}
}
.........................................................................
public class IT_Members {
private String name,deparment,postion;
private int ID=1000;
private int Flag=0;
IT_Members (){
}
IT_Members (String name, String deparment , String postion ,int ID , int Flag){
this.name= name;
this.deparment=deparment;
this.postion=postion;
this.ID=ID;
this.Flag=Flag;
}
public String getName (){
return this.name;
}
public String getDeparment (){
return this.deparment;
}
public String getPostion (){
return this.postion;
}
public int getID (){
return this.ID;
}
public int getFlag (){
return this.Flag;
}
public void setName (String name){
this.name = name;
}
public void setDeparment (String Deparment){
this.deparment = deparment;
}
public void setPostion (String postion){
this.postion = postion;
}
public void setID (int ID){
this.ID = ID;
}
public void setFlag (int Flag){
this.Flag = Flag ;
}
public String toStu()
{
String str = "";
str = "\nName: " + this.name +
"\nDeparment: " + this.deparment +
"\nPostion: " + this.postion +
"\nID: " + this.ID;
return str;
}
}
Please, I'm stuck with this I appreciate any help.
Thanks.
You never call the Add function in the Information class. Therefore you never initialize any of the array elements you then want to display.
You need to add input2.Add(input1) before you print that is has been added.
You have to create every time a new Object and in the end you have to add in the list.
import java.util.Scanner;
import java.util.Arrays;
public class Interface {
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
Information input2 = new Information();
int x=1;
while(x!=0)
{
System.out.println(" \n[1] Add new student member. \n[2] View members.\nChoose now: ");
int choose = in.nextInt();
switch (choose){
case 1:
IT_Members input1 = new IT_Members();// this need to be here so that every time crete new object
System.out.println("Name: ");
input1.setName(in.nextLine());
System.out.println("Deparment: ");
input1.setDeparment(in.nextLine());
System.out.println("Postion: ");
input1.setPostion(in.nextLine());
input2.Add(input1); // that was missing
System.out.println("Student record has been added. ");
break;
case 2:
input2.Display();
break;
}
}

Printing string arrays to a text file using java

I am trying to print out the results of the users inputs to a simple text file but everything I have tried has rendered unsuccessful. I tried using a PrintWriter within the switch case but the results still just printed out null. I am quite new to Java so maybe I am missing obvious?
Here is the code:
package parkingsystem;
import java.io.*;
import java.util.Scanner;
public class Registration {
static String [][] userData;
static String [][] fileData;
public static void Registration(){
Scanner input = new Scanner(System.in);
String lotNo;
String First;
String Last;
String studentID;
String phoneNo;
String email;
String carNo;
String dateReg;
String strcontent;
String proceed;
boolean proceed2 = true;
userData = new String [50][6];
fileData = new String [50][6];
int counter = 0;
int col;
int row;
boolean carry_on = true;
MainMenu choices = new MainMenu();
while(proceed2=true){
System.out.println("Press Y/y to add a new user");
System.out.println("Press N/n to return to menu");
proceed = input.nextLine();
switch (proceed) {
case "Y":
case "y":
System.out.println("Enter your student ID");
studentID = input.nextLine();
System.out.println("Enter your first name");
First = input.nextLine();
System.out.println("Enter your last name");
Last = input.nextLine();
System.out.println("Enter your car number");
carNo = input.nextLine();
System.out.println("Enter your contact number");
phoneNo = input.nextLine();
System.out.println("Enter your email address");
email = input.nextLine();
row = counter ;
userData [row][0] = studentID;
userData [row][1] = First;
userData [row][2] = Last;
userData [row][3] = carNo;
userData [row][4] = phoneNo;
userData [row][5] = email;
if (counter == 6){
carry_on=false;
}
proceed2 = false;
break;
case "N":
case "n":
choices.Menus();
break;
}
}
}
}
Here's a second pass at re-factoring your code.
So now in this refactoring we capture and store the newly created CarOwner objects and store them in a list.
Then we see how to go through that List of CarOwner's and then write those objects to a file called carOwners.dat
Ordinarily, in industry, code re-factoring is done in the context of having a set of unit tests against which you can ensure that the refactoring hasn't broken the required behaviour of the code but we are just learning here so this work serves to explain some of the concepts that you are missing and this first pass iteration below has some issues of its own so don't take this as the final product.
Refactorings
I have created a CarOwner class.
I have renamed the Boolean variable canProceed so that it reads more naturally.
Update : I have made the CarOwner class Serializable; this will allow us to write the Object to a File.
Update : I have added code that up the new CarOwners and adds it to a List and then I iterate over the list to write those CarOwner objects to a FileStream.
package parkingsystem;
import java.io.FileNotFoundException;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.io.FileOutputStream;
import java.util.Scanner;
public class Registration {
public static void main(String[] args) {
List carOwners = new ArrayList();
Scanner input = new Scanner(System.in);
boolean canProceed = true;
while (canProceed) {
System.out.println("Press Y/y to add a new user");
System.out.println("Press N/n to return to menu");
String optionRequested = input.nextLine();
if (optionRequested.equalsIgnoreCase("Y")) {
CarOwner owner = new CarOwner();
System.out.println("Enter your student ID");
owner.setStudentID(input.nextLine());
System.out.println("Enter your first name");
owner.setFirst(input.nextLine());
System.out.println("Enter your last name");
owner.setLast(input.nextLine());
System.out.println("Enter your car number");
owner.setCarNo(input.nextLine());
System.out.println("Enter your contact number");
owner.setContactNumber(input.nextLine());
System.out.println("Enter your email address");
owner.setEmail(input.nextLine());
owner.setDateReg(new Date().toString());
carOwners.add(owner);
} else if (optionRequested.equals("N") || optionRequested.equals("n")) {
canProceed = false;
}
}
ObjectOutputStream objectWriter = null;
for (CarOwner carOwner : carOwners) {
try {
objectWriter = new ObjectOutputStream(new FileOutputStream("carOwners.dat"));
objectWriter.writeObject(carOwner);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here's what the CarOwner class now looks like ...
package parkingsystem;
import java.io.Serializable;
public class CarOwner implements Serializable{
private String First;
private String Last;
private String studentID;
private String email;
private String carNo;
private String dateReg;
private String contactNumber;
public CarOwner() {
}
public String getFirst() {
return First;
}
public void setFirst(String first) {
First = first;
}
public String getLast() {
return Last;
}
public void setLast(String last) {
Last = last;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCarNo() {
return carNo;
}
public void setCarNo(String carNo) {
this.carNo = carNo;
}
public String getDateReg() {
return dateReg;
}
public void setDateReg(String dateReg) {
this.dateReg = dateReg;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getContactNumber() {
return contactNumber;
}
#Override
public String toString() {
return "CarOwner{" +
"First='" + First + '\'' +
", Last='" + Last + '\'' +
", studentID='" + studentID + '\'' +
", email='" + email + '\'' +
", carNo='" + carNo + '\'' +
", dateReg='" + dateReg + '\'' +
", contactNumber='" + contactNumber + '\'' +
'}';
}
}
Ok so creating the CarOwner class is done to make a start at making this code more object oriented.
Secondly the re-factored code demonstrates correct use of a Boolean variable in Java.
As the other commentators have already pointed out the assignment operator = is easily confused with the test for Boolean equality. See Java Operators
Also I have renamed Boolean proceed; to be Boolean canProceed; This is a common strategy. Naming a Boolean variable to read as a question to which the "answer" is, yes or no, or True or False.
This then means we can write code like while(canProceed) which reads very easily. See also if statement on the Java tutorial
I hope this helps.

Categories