Either my save_product function in my Repository.java class doesn't save correctly into the map product_repository or, maybe it does save, but I'm not outputting it correctly in my find_product function in my Repository.java class. I think I'm using the correct function to search for the value in the map, .get
I experimented with product_repository.keySet().iterator().forEachRemaining(System.out::println); but that's the first time I ever used that... also please forgive how I insert the keyinto the map product_repository in the create_new_product function in the Controller.java class. I'm new to java ...
Main.java
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
Controller controller = new Controller();
controller.create_new_product();
controller.search_product();
}
}
Product.java
package com.company;
public class Product {
private String product_name;
private String product_brand;
private int product_cost;
private int product_count;
private boolean product_availability;
public Product() {
}
public Product(String product_name, String product_brand,
int product_cost, int product_count, boolean product_availability) {
this.product_name = product_name;
this.product_brand = product_brand;
this.product_cost = product_cost;
this.product_count = product_count;
this.product_availability = product_availability;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_brand() {
return product_brand;
}
public void setProduct_brand(String product_brand) {
this.product_brand = product_brand;
}
public int getProduct_cost() {
return product_cost;
}
public void setProduct_cost(int product_cost) {
this.product_cost = product_cost;
}
public int getProduct_count() {
return product_count;
}
public void setProduct_count(int product_count) {
this.product_count = product_count;
}
public boolean isProduct_availability() {
return product_availability;
}
public void setProduct_availability(boolean product_availability) {
this.product_availability = product_availability;
}
}
Controller.java
package com.company;
import java.util.Scanner;
public class Controller {
private static Long key;
public static void create_new_product(){
Repository repository = new Repository();
//Supplier supplier = new Supplier();
Product product = new Product();
Scanner scanner = new Scanner(System.in);
key = 0L;
System.out.println("*****************************************************************");
System.out.println("********************NEW PRODUCT CREATION PAGE********************");
System.out.println("*****************************************************************");
System.out.println("Enter product name: ");
String name = scanner.nextLine();
product.setProduct_name(name);
System.out.println("Enter product brand: ");
String brand = scanner.nextLine();
product.setProduct_brand(brand);
System.out.println("Enter product cost: ");
int cost = scanner.nextInt();
product.setProduct_cost(cost);
System.out.println("Enter amount of products in stock: ");
int amount = scanner.nextInt();
product.setProduct_count(amount);
key++;
repository.save_product(key, product);
}
public void search_product(){
Repository repository = new Repository();
Product product = new Product();
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("*************************FIND PRODUCT PAGE***********************");
System.out.println("*****************************************************************");
// TO DO: Choices or if/else blocks not executing properly
System.out.println("\nSearch by ID or name?\nPress '1' for ID. Press '2' for name: ");
String choice = scanner.next();
if (choice.equals("1")) {
System.out.println("Enter product id: ");
Long id = scanner.nextLong();
repository.find_product(id);
try{
if (product.getProduct_count() > 0){
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
}
else if (choice.equals("2")) {
System.out.println("Enter product name: ");
String name = scanner.next();
repository.find_product(name);
try{
if (product.getProduct_count() > 0){
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
}
else {
System.out.println("Error. We apologize for the inconvenience.");
}
}
}
Repository.java
package com.company;
import java.util.HashMap;
import java.util.Map;
public class Repository {
private Map<Long, Product> product_repository = new HashMap<Long, Product>();
// TO DO: Implement while loops so program doesn't exit at the first error
public void save_product(Long key, Product newProductMap){
try{
if (product_repository.containsValue(newProductMap)) {
System.out.println("This product is already in the system." +
"\nFor safety reasons, we cannot add the same product twice.");
}
else {
product_repository.put(key, newProductMap);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
public void find_product(Long key){
try {
if (product_repository.containsKey(key)) {
System.out.println(product_repository.get(key));
}
else {
System.out.println("No matches were found for product id: " + key);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
// Overload
public void find_product(String name) {
try {
if (product_repository.containsValue(name)) {
System.out.println(product_repository.get(name));
product_repository.keySet().iterator().forEachRemaining(System.out::println);
}
else {
System.out.println("No matches were found for product name: " + name);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
}
You have to make Repository repository a field of your Controller class. You are currently throwing the repositories away after your methods create_new_product and search_product have executed. Therefore you need to remove the first line of each of these methods.
Another problem is inside your find_product(String name) method where your call product_repository.get(name) but name is a String and the get method expects an ID, i.e. a Long so this call will always return null.
As it was pointed out before the repository has to be made global. However, the entire code is a bit messy. You are searching for a product id but the id is not shown to you. It is like searching for database records but the ids are autogenerated. Good luck with that. So I would suggest to allow this program to enter the id as well. It makes much more sense if you want to search for the id.
Otherwise, if you are interested in only the value, id can be taken out.
Below you can find the modified code that works for all the methods.
//main stays the same
public class Main {
public static void main(String[] args) {
// write your code here
Controller controller = new Controller();
controller.create_new_product();
controller.search_product();
}
}
//controller is a bit changed. Added global repository and improved the search.
import java.util.Collection;
import java.util.Scanner;
public class Controller {
private static Long key;
Repository repository = new Repository();
public void create_new_product() {
Product product = new Product();
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("********************NEW PRODUCT CREATION PAGE********************");
System.out.println("*****************************************************************");
System.out.println("Enter product id: ");
long id = Long.parseLong(scanner.nextLine());
product.setProductId(id);
System.out.println("Enter product name: ");
String name = scanner.nextLine();
product.setProduct_name(name);
System.out.println("Enter product brand: ");
String brand = scanner.nextLine();
product.setProduct_brand(brand);
System.out.println("Enter product cost: ");
int cost = scanner.nextInt();
product.setProduct_cost(cost);
System.out.println("Enter amount of products in stock: ");
int amount = scanner.nextInt();
product.setProduct_count(amount);
repository.save_product(id, product);
}
public void search_product() {
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("*************************FIND PRODUCT PAGE***********************");
System.out.println("*****************************************************************");
// TO DO: Choices or if/else blocks not executing properly
System.out.println("\nSearch by ID or name?\nPress '1' for ID. Press '2' for name: ");
String choice = scanner.next();
if (choice.equals("1")) {
System.out.println("Enter product id: ");
Long id = scanner.nextLong();
Product product = repository.find_product(id);
try {
if (product.getProduct_count() > 0) {
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
} else if (choice.equals("2")) {
System.out.println("Enter product name: ");
String name = scanner.next();
Collection<Product> products = repository.find_products(name);
if (products.size() > 0) {
for (Product product : products) {
System.out.println(product.getProduct_name() + " are in stock!");
}
} else {
System.out.println(" out of stock.");
}
} else {
System.out.println("Error. We apologize for the inconvenience.");
}
}
}
//Added a new field to the Repository so you can also search by key.
import java.util.*;
public class Repository {
private Map<Long, Product> product_repository = new HashMap<Long, Product>();
// TO DO: Implement while loops so program doesn't exit at the first error
public void save_product(Long key, Product newProductMap) {
try {
if (!product_repository.containsKey(key)) {
product_repository.put(key, newProductMap);
} else {
System.out.println("This product is already in the system." +
"\nFor safety reasons, we cannot add the same product twice.");
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
public Product find_product(final Long key) {
try {
if (product_repository.containsKey(key)) {
System.out.println("Found product: " + product_repository.get(key).getProduct_name());
return product_repository.get(key);
} else {
System.out.println("No matches were found for product id: " + key);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
return null;
}
// Overload
public Collection<Product> find_products(final String name) {
Collection<Product> values = new ArrayList<>();
for (Map.Entry<Long, Product> productEntry : product_repository.entrySet()) {
if (productEntry.getValue().getProduct_name().equals(name)) {
System.out.println("matches were found for product name: " + name);
values.add(productEntry.getValue());
}
}
return values;
}
}
Related
I am not too familiar with polymorphism, and was wondering if I have it used in my code?
If this doesn't contain a polymorphic reference, could you lead me in a direction of where I would need to go? The files that the program is using are not included, as I am mainly curious about whether or not any polymorphic references are used.
java file 1 - this file runs the program
import java.util.Scanner;
public class ADTDemo {
ADTDictionary dictionary;
public static void menu() {
System.out.println("Welcome the Faculty Directory Program");
System.out.println(" Use commands:");
System.out.println(" list all");
System.out.println(" list DEPT_NAME");
System.out.println(" add DEPT_NAME, FIRST LAST");
System.out.println(" remove DEPT_NAME, FIRST LAST");
System.out.println(" exit");
}
public static void main(String[] args) {
menu();
String command;
ADTDemo dictObj = new ADTDemo();
dictObj.dictionary = new ADTDictionary();
dictObj.dictionary.read();
Scanner scanner = new Scanner(System.in);
do {
System.out.println("");
System.out.print(">>");
command = scanner.nextLine().trim();
if (!command.equals("exit")) {
dictObj.action(command);
} else {
dictObj.dictionary.saveEntries();
System.out.println("Goodbye! Have a nice day!");
}
} while (!command.equalsIgnoreCase("exit"));
}
public void action(String command) {
if (command.equalsIgnoreCase("LIST ALL")) {
dictionary.listAll();
return;
}
else if (command.toUpperCase().contains("LIST")) {
if (command.length() == 4){
System.out.println("Command needed.");
return;
}
command = command.substring(5, command.length());
dictionary.listDeptName(command);
return;
}
else if (command.toUpperCase().contains("ADD")) {
command = command.substring(4, command.length());
dictionary.add(command);
return;
}
else if (command.toUpperCase().contains("REMOVE")) {
command = command.substring(6, command.length());
dictionary.remove(command);
}
}
}
java file 2
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class ADTDictionary {
Map<String, List<String>> adtDictionary;
public void read() {
try {
File facultyFile = new File("faculty.txt");
File departmentFile = new File("departments.txt");
Scanner departmentScanner = new Scanner(departmentFile);
Scanner facultyScanner = new Scanner(facultyFile);
adtDictionary = new HashMap<String, List<String>>();
while (departmentScanner.hasNextLine()) {
String department = departmentScanner.nextLine().trim();
adtDictionary.put(department, new ArrayList<String>());
}
while (facultyScanner.hasNextLine()) {
String faculty = facultyScanner.nextLine();
String[] values = faculty.split(",");
adtDictionary.get(values[1].trim()).add(values[0]);
}
} catch (FileNotFoundException ex) {
System.out.println("ERROR: File not found.");
}
}
public void listAll() {
for (String key : adtDictionary.keySet()) {
for (String value : adtDictionary.get(key)) {
System.out.println(value + ", " + key);
}
}
}
public void listDeptName(String department) {
if (null != adtDictionary.get(department)) {
for (String name : adtDictionary.get(department)) {
System.out.println(name);
}
}
else{
System.out.println("Unknown entry made.");
}
}
public void add(String value) {
if(!value.contains(",")){
System.out.println("Incorrect entry.");
return;
}
String[] values = value.split(",");
String dept = values[0].trim();
String faculty = values[1].trim();
String[] facName = faculty.split(" ");
if (!(facName.length == 2)){
System.out.println("Please only enter First and Last name of faculty member.");
return;
}
if (!(null != adtDictionary.get(dept))) {
if(adtDictionary.containsKey(dept.toUpperCase())){
System.out.println("Incorrect departtment entry.");
return;
}
else if (dept == dept.toUpperCase()){
adtDictionary.put(dept, new ArrayList<String>());
}
else{
System.out.println("Incorrect department entry.");
return;
}
}
for (String name : adtDictionary.get(dept)) {
if (name.equalsIgnoreCase(faculty)) {
System.out.println("Cannot add " + name + " to " + dept + " because they already exist there.");
return;
}
}
adtDictionary.get(dept).add(faculty);
System.out.println("OK, added " + faculty);
}
public void remove(String value) {
String[] values = value.split(",");
String dept = values[0].trim();
String faculty = values[1].trim();
adtDictionary.get(dept).remove(faculty);
System.out.println("OK, removed " + faculty + " from " + dept);
}
public void saveEntries(){
try {
File facultyFile = new File("faculty.txt");
File departmentFile = new File("departments.txt");
PrintWriter facWriter = new PrintWriter(facultyFile);
PrintWriter deptWriter = new PrintWriter(departmentFile);
for (Object s : adtDictionary.keySet()) {
deptWriter.println(s);
}
deptWriter.close();
for (String key : adtDictionary.keySet()) {
for (String value : adtDictionary.get(key)) {
facWriter.println(value + ", " + key);
}
}
facWriter.close();
}
catch (IOException ex){
System.out.println("ERROR saving file.");
}
}
}
I know this is a very very common error but I am stuck on this one and I totally don't understand why is it happening.
Here is a part of my code
import java.util.ArrayList;
import java.util.Scanner;
public class Manager {
private static Scanner sc = new Scanner(System.in);
protected static ArrayList<String> identifications = new ArrayList<String>();
protected static String[] signIn() {
System.out.println("Hi !");
System.out.println("Welcome to School Management System");
System.out.print("Please enter your ID number : ");
boolean idValid = false;
String providedID = null;
int idListPosition = -1;
do {
try {
providedID = sc.nextLine();
} catch (Exception e) {
System.out.println("Sorry there was an error. Please try again");
System.out.print("Please enter your ID number : ");
}
} while (providedID == null);
while (idValid != true) {
for (String element : identifications) {
if (element.equals(providedID)) {
idValid = true;
idListPosition = identifications.indexOf(element);
break;
}
}
if (idValid && idListPosition != -1) {
System.out.println("Welcome !");
String[] returnValue = {"true", identifications.get(idListPosition), identifications.get(idListPosition + 1), identifications.get(idListPosition + 2)};
return (returnValue);
} else {
System.out.println("Error : the ID you entered does not exist. Please try again");
providedID = null;
do {
try {
providedID = sc.nextLine();
} catch (Exception e) {
System.out.println("Sorry there was an error. Please try again");
System.out.print("Please enter your ID number : ");
}
} while (providedID == null);
}
}
}
public static void main(String[] args) {
init();
String[] response = signIn();
if (response[2].equals("teacher")) {
Teacher user = new Teacher(response[1], response[2], response[3]);
}
if (response[2].equals("student")) {
Student user = new Student(response[1], response[2], response[3]);
}
System.out.println(user);
while(true) {
System.out.println("For help type in help");
System.out.print("Enter a command : ");
String commandWanted = sc.nextLine();
if (commandWanted.equals("info")) user.showInfos();
}
}
protected static void init() {
identifications.add("056789");
identifications.add("teacher");
identifications.add("Temperson");
}
}
The Teacher and Student classes are empty for now. I just made them use the super constructor of their parent class Person :
public class Person {
String type;
String name;
String idNumber;
public Person(String idnumber, String newType, String providedName) {
this.idNumber = idnumber;
this.type = newType;
this.name = providedName;
}
protected String[] showInfos() {
String[] returnValue = {this.type, this.name, this.idNumber};
return returnValue;
}
}
But I get user cannot be resolved to a variable and user cannot be resolved error.
Normally the code that needs user will never run unless sign in has completed. And since sign in never ends before a correct ID is entered, the user variable will always be assigned to a a value.
Thanks for helping !
The scope of the user object is limited to the if condition, hence you are getting this error.
If Teacher and Student extends Person then you can try this piece of code:
public static void main(String[] args) {
init();
String[] response = signIn();
Person user = null;
if (response[2].equals("teacher")) {
user = new Teacher(response[1], response[2], response[3]);
}
if (response[2].equals("student")) {
user = new Student(response[1], response[2], response[3]);
}
System.out.println(user);
while(true) {
System.out.println("For help type in help");
System.out.print("Enter a command : ");
String commandWanted = sc.nextLine();
if (commandWanted.equals("info")) user.showInfos();
}
}
You're having a Scope problem here:
if (response[2].equals("teacher")) {
Teacher user = new Teacher(response[1], response[2], response[3]);
}
if (response[2].equals("student")) {
Student user = new Student(response[1], response[2], response[3]);
}
System.out.println(user);
Variables declared in a if block are local to that if block. You can see this in it's simplest form with an example like this:
if(true) {
String value = "Out of Scope";
}
System.out.println(value); //value cannot be seen outside the if block
You will need to declare your Teacher and/or Student variable outside the if block if you wish to use them after the block (this is where using your inheritance class would come in handy). Using the previous example:
boolean someCondition = true;
String value;
if(someCondition) {
value = "In Scope - True";
} else {
value = "In Scope - False";
}
System.out.println(value); //value can now be seen
You have declared 2 different versions of user, so the print statement can't know which you mean. Or it couldn't if it could see either, but since each is declared inside of its own block, the print doesn't see either of them.
I really just need a point in the right direction for this code. I do not understand how to accomplish what it is asking.
Modify the ProductMainApp class so it responds appropriately if the addProduct and deleteProduct mwthod in the ProductTextFile class returns a flase value.
Modify the ProductTextFile class so it writes exceptions to a tex file names errorLog.txt instead of printing them to the console. To do that, add a method named printToLogFile that accepts an IOException as an argument. This method should append two records to the log file: one that indicates the date and time the exception occured and one that contains information about the exception.
Modify the getProducts and saveProducts methods so they call the printToLogFile method when an error occurs.
Here is the PrintTextFile:
import java.util.*;
import java.io.*;
import java.nio.file.*;
public final class ProductTextFile implements ProductDAO
{
private ArrayList<Product> products = null;
private Path productsPath = null;
private File productsFile = null;
private final String FIELD_SEP = "\t";
public ProductTextFile()
{
productsPath = Paths.get("products.txt");
productsFile = productsPath.toFile();
products = this.getProducts();
}
public ArrayList<Product> getProducts()
{
// if the products file has already been read, don't read it again
if (products != null)
return products;
products = new ArrayList<>();
if (Files.exists(productsPath)) // prevent the FileNotFoundException
{
try
{
if (true)
{
// throw new IOException();
}
// open the input stream
BufferedReader in =
new BufferedReader(
new FileReader(productsFile));
// read all products stored in the file
// into the array list
String line = in.readLine();
while(line != null)
{
String[] columns = line.split(FIELD_SEP);
String code = columns[0];
String description = columns[1];
String price = columns[2];
Product p = new Product(
code, description, Double.parseDouble(price));
products.add(p);
line = in.readLine();
}
// close the input stream
in.close();
}
catch(IOException e)
{
//System.out.println(e);
return null;
}
}
return products;
}
public Product getProduct(String code)
{
for (Product p : products)
{
if (p.getCode().equals(code))
return p;
}
return null;
}
public boolean addProduct(Product p)
{
products.add(p);
return this.saveProducts();
}
public boolean deleteProduct(Product p)
{
products.remove(p);
return this.saveProducts();
}
public boolean updateProduct(Product newProduct)
{
// get the old product and remove it
Product oldProduct = this.getProduct(newProduct.getCode());
int i = products.indexOf(oldProduct);
products.remove(i);
// add the updated product
products.add(i, newProduct);
return this.saveProducts();
}
private boolean saveProducts()
{
try
{
// open the output stream
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productsFile)));
// write all products in the array list
// to the file
for (Product p : products)
{
out.print(p.getCode() + FIELD_SEP);
out.print(p.getDescription() + FIELD_SEP);
out.println(p.getPrice());
}
// close the output stream
out.close();
}
catch(IOException e)
{
System.out.println(e);
return false;
}
return true;
}
}
Here is the ProductMainApp:
import java.util.Scanner;
import java.util.ArrayList;
public class ProductMaintApp implements ProductConstants
{
// declare two class variables
private static ProductDAO productDAO = null;
private static Scanner sc = null;
public static void main(String args[])
{
// display a welcome message
System.out.println("Welcome to the Product Maintenance application\n");
// set the class variables
productDAO = DAOFactory.getProductDAO();
sc = new Scanner(System.in);
// display the command menu
displayMenu();
// perform 1 or more actions
String action = "";
while (!action.equalsIgnoreCase("exit"))
{
// get the input from the user
action = Validator.getString(sc,
"Enter a command: ");
System.out.println();
if (action.equalsIgnoreCase("list"))
displayAllProducts();
else if (action.equalsIgnoreCase("add"))
{
addProduct();
}
else if (action.equalsIgnoreCase("del") || action.equalsIgnoreCase("delete"))
deleteProduct();
else if (action.equalsIgnoreCase("help") || action.equalsIgnoreCase("menu"))
displayMenu();
else if (action.equalsIgnoreCase("exit") || action.equalsIgnoreCase("quit"))
System.out.println("Bye.\n");
else
System.out.println("Error! Not a valid command.\n");
}
}
public static void displayMenu()
{
System.out.println("COMMAND MENU");
System.out.println("list - List all products");
System.out.println("add - Add a product");
System.out.println("del - Delete a product");
System.out.println("help - Show this menu");
System.out.println("exit - Exit this application\n");
}
public static void displayAllProducts()
{
System.out.println("PRODUCT LIST");
ArrayList<Product> products = productDAO.getProducts();
Product p = null;
StringBuilder sb = new StringBuilder();
if (productDAO.getProducts().equals(null))
{
System.out.println("Value Null");
System.exit(0);
}
for (int i = 0; i < products.size(); i++)
{
p = products.get(i);
sb.append(StringUtils.padWithSpaces(
p.getCode(), CODE_SIZE + 4));
sb.append(StringUtils.padWithSpaces(
p.getDescription(), DESCRIPTION_SIZE + 4));
sb.append(
p.getFormattedPrice());
sb.append("\n");
}
System.out.println(sb.toString());
}
public static void addProduct()
{
String code = Validator.getString(
sc, "Enter product code: ");
String description = Validator.getLine(
sc, "Enter product description: ");
double price = Validator.getDouble(
sc, "Enter price: ");
Product product = new Product();
product.setCode(code);
product.setDescription(description);
product.setPrice(price);
productDAO.addProduct(product);
System.out.println();
System.out.println(description
+ " has been added.\n");
}
public static void deleteProduct()
{
String code = Validator.getString(sc,
"Enter product code to delete: ");
Product p = productDAO.getProduct(code);
System.out.println();
if (p != null)
{
productDAO.deleteProduct(p);
System.out.println(p.getDescription()
+ " has been deleted.\n");
}
else
{
System.out.println("No product matches that code.\n");
}
}
}
You can use Exception.printStackTrace (stream) where stream is a outputstream to a file.
http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)
So I'm making a program that will store the meetings I've had with some kids I'm tutoring. It'll keep tabs on the meeting times, discussions, and how many hours I've done. I know how to write all the methods to do that, but my issue is that the program will only hold that information for the session that the program is open... how would I go about storing this information and accessing it after the program is closed and opened again?
This is some excerpts from a test score keeper program I did in java class that has this same issue...
public class Student {
private String name;
private int test1;
private int test2;
private int test3;
public Student() {
name = "";
test1 = 0;
test2 = 0;
test3 = 0;
}
public Student(String nm, int t1, int t2, int t3){
name = nm;
test1 = t1;
test2 = t2;
test3 = t3;
}
public Student(Student s){
name = s.name;
test1 = s.test1;
test2 = s.test2;
test3 = s.test3;
}
public void setName(String nm){
name = nm;
}
public String getName (){
return name;
}
public void setScore (int i, int score){
if (i == 1) test1 = score;
else if (i == 2) test2 = score;
else test3 = score;
}
public int getScore (int i){
if (i == 1) return test1;
else if (i == 2) return test2;
else return test3;
}
public int getAverage(){
int average;
average = (int) Math.round((test1 + test2 + test3) / 3.0);
return average;
}
public int getHighScore(){
int highScore;
highScore = test1;
if (test2 > highScore) highScore = test2;
if (test3 > highScore) highScore = test3;
return highScore;
}
public String toString(){
String str;
str = "Name: " + name + "\n" + //\n makes a newline
"Test 1: " + test1 + "\n" +
"Test 2: " + test2 + "\n" +
"Test 3: " + test3 + "\n" +
"Average: " + getAverage();
return str;
}
}
If your data is not too big or complicated - something that you could save in a Rolodex in days gone by - you can save it to a file. Add methods to your class that will format the data properly and write it to a given OutputStream or Writer or whatever. And a method that will read it back.
To write to the file, add an option "save" in your program menu, and when it's chosen, open a file, iterate through your data, and call the saving method for each of your object.
To read from the file, add an option "load" in your program menu, and when it's chosen, open a file, and use your method of reading for each object.
The method for reading can be a static method in the class, that will first see if there are any data in the file and if it can read them properly, and only if it did, will create an object and return it (otherwise return null). There are other options, but this is the one that most encapsulates the needs of the object.
There is also an option to serialize and deserialize each object and put it in an object stream.
If the data is complicated, and there are many objects with various relations between them, you should use a database. This will require learning some database design and SQL.
To demonstrate the file reading/writing idea, add to your Student class:
public void save(PrintWriter outfile) {
outfile.format("%s|%d|%d|%d%n", name, test1, test2, test3);
}
This will write a line with the fields separated by "|" (vertical bar). Of course, you'll have to make sure none of the student names has a vertical bar in it. So you'll need to modify your 4-parameter constructor and your setter:
public Student(String nm, int t1, int t2, int t3) {
name = nm.replaceAll("\\|", "");
test1 = t1;
test2 = t2;
test3 = t3;
}
public void setName(String nm) {
name = nm.replaceAll("\\|", "");
}
Now, to read the file, we add a static method:
public static Student load(BufferedReader infile) throws IOException {
String line;
line = infile.readLine();
// Check if we reached end of file
if (line == null) {
return null;
}
// Split the fields by the "|", and check that we have no less than 4
// fields.
String[] fields = line.split("\\|");
if (fields.length < 4) {
return null;
}
// Parse the test scores
int[] tests = new int[3];
for (int i = 0; i < 3; i++) {
try {
tests[i] = Integer.parseInt(fields[i + 1]);
} catch (NumberFormatException e) {
// The field is not a number. Return null as we cannot parse
// this line.
return null;
}
}
// All checks done, data ready, create a new student record and return
// it
return new Student(fields[0], tests[0], tests[1], tests[2]);
}
You can see that this is more complicated, because you need to check that everything is OK at every step. In any case when things are not OK, we return null but of course, you can decide to just display a warning and read the next line. You'll have to return null when there are no more lines, though.
So, assuming we have a List<Student> students, here is how we write it to a file. I just chose "students.txt" but you can specify a full path leading where you want it. Note how I'm making a backup of the old file before I open the new file. If something goes wrong, at least you have the previous version of the file.
File f = new File("students.txt");
if (f.exists()) {
File backup = new File("students.bak");
if ( ! f.renameTo(backup) ) {
System.err.println( "Could not create backup.");
return;
}
f = new File("students.txt");
}
try ( PrintWriter outFile = new PrintWriter(f);) {
for (Student student : students) {
student.save(outFile);
}
} catch (FileNotFoundException e) {
System.err.println("Could not open file for writing.");
return;
}
After you do this, if you look for the file "students.txt", you will see the records you wrote in it.
How about reading it? Assume we have an empty students list (not null!):
try ( BufferedReader inFile = new BufferedReader(new FileReader(f))) {
Student student;
while ( ( student = Student.load(inFile)) != null) {
students.add(student);
}
} catch (FileNotFoundException e) {
System.err.println( "Could not open file for reading.");
return;
} catch (IOException e) {
System.err.println( "An error occured while reading from the file.");
}
Having done this, you can check your students list, and unless there were errors in the file, all your records will be there.
This is a demonstration, of course. You may want to read into some other collection or instead of printing an error and returning do something else. But it should give you the idea.
You could use db4o for persisting your data. Its an object-database with a spimple api to use. You can store java object read or delete them..
Download it here DB4O
And use the snippets of this tutorial (GER):Tutorial in German
Here is an example:
and Code:
package db4o.example;
public class Student {
String name;
public Student(String name) {
this.name = name;
}
#Override
public String toString() {
return "Student Name: " + name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package db4o.example;
import java.util.List;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
public class Main {
public static void main(String[] args) {
ObjectContainer db = Db4oEmbedded.openFile("F:\\studentDB");
saveExample(db);
readAllExample(db);
readExample(db);
deleteAllExample(db);
db.close();
}
private static void deleteAllExample(ObjectContainer db) {
System.out.println("DeleteAllExample Example:");
List<Student> allStudents =readAllExample(db);
for (Student student : allStudents) {
db.delete(student);
}
db.commit();
}
private static List<Student> readAllExample(ObjectContainer db) {
System.out.println("ReadAllExample Example:");
List<Student> allStudents = db.query(Student.class);
System.out.println("Count: " + allStudents.size());
for (Student student : allStudents) {
System.out.println(student);
}
return allStudents;
}
private static void readExample(ObjectContainer db) {
System.out.println("ReadExample Example:");
Student queryStudent = new Student("Max Mustermann");
// Gets all Students named Max Mustermann
List<Student> students = db.queryByExample(queryStudent);
System.out.println("Count: " + students.size());
for (Student student : students) {
System.out.println(student);
}
}
private static void saveExample(ObjectContainer db) {
System.out.println("Save Example:");
Student myStudent = new Student("Max Mustermann");
db.store(myStudent);
db.commit();
}
}
I have an assignment to carry out using BlueJ where I am given a class called HW4CustomerList and I must create a Text-Based UI for it. The class I have to create is called CustomerTUI and contains a method called addCustomer which adds a new Customer object of mine to an ArrayList. This method in particular is what I am stuck with. The class specification says that I cannot take any parameters (i.e. a no-args method). In previous work we have used the BlueJ 'method box' to interact with objects and add them to ArrayLists, however I do not know if this can be used in this particular instance. Please find below my code so far for CustomerTUI and the code for the Customer class and HW4CustomerList class. Many thanks in advance.
CustomerTUI class:
import java.util.Scanner;
public class CustomerTUI
{
private HW4CustomerList customerList;
private Scanner myScanner;
public CustomerTUI()
{
customerList = new HW4CustomerList();
myScanner = new Scanner(System.in);
}
public void menu()
{
int command;
boolean running = true;
while(running)
{
displayMenu();
command = getCommand();
execute(command);
}
}
private void addCustomer()
{
customerList.addCustomer();
}
private void displayMenu()
{
System.out.println(" CustomerList program ");
System.out.println("=========================================");
System.out.println("|Add a customer to the list..........[1]|");
System.out.println("|Get number of customers.............[2]|");
System.out.println("|Remove a customer from the list.....[3]|");
System.out.println("|Show all customer details...........[4]|");
System.out.println("|Show a specific customers details...[5]|");
System.out.println("|Quit................................[6]|");
System.out.println("=========================================");
}
private void execute(int command)
{
if(command == 1)
{
addCustomer();
}
else if(command == 2)
{
getNumberOfCustomers();
}
else if(command == 3)
{
removeCustomer();
}
else if(command == 4)
{
showAllCustomers();
}
else if(command == 5)
{
showCustomer();
}
else if(command == 6)
{
quitCommand();
}
else
{
unknownCommand(command);
}
}
private int getCommand()
{
System.out.println("Enter the command of the function you wish to use: ");
int command = myScanner.nextInt();
return command;
}
private void getNumberOfCustomers()
{
if(customerList.getNumberOfCustomers() == 1)
{
System.out.println("We have " + customerList.getNumberOfCustomers() + " customer.");
}
else
{
System.out.println("We have " + customerList.getNumberOfCustomers() + " customers.");
}
}
private void quitCommand()
{
System.out.println("The program is now closing down...");
System.exit(0);
}
private void removeCustomer()
{
String accNo;
System.out.println("Enter the account number of the customer you wish to remove: ");
accNo = myScanner.next();
if (customerList.removeCustomer(accNo) == true)
{
System.out.println("Customer with account number " + accNo + " was successfully removed.");
}
else
{
System.out.println("Customer with account number " + accNo + " was NOT successfully removed.");
System.out.println("Please try again.");
}
}
private void showAllCustomers()
{
customerList.getAllCustomers();
}
private void showCustomer()
{
String accNo;
System.out.println("Enter the account number of the customer you wish to view: ");
accNo = myScanner.next();
if(customerList.getCustomer(accNo) == false)
{
System.out.println("Could not find customer with account number " + accNo + ".");
}
else
{
return;
}
}
private void unknownCommand(int command)
{
System.out.println("Command number " + command + " is not valid. Please try again.");
}
}
HW4CustomerList class:
import java.util.*;
public class HW4CustomerList
{
private ArrayList<Customer> customers;
public HW4CustomerList()
{
customers = new ArrayList<Customer>();
}
public void addCustomer(Customer customer)
{
customers.add(customer);
}
public int getNumberOfCustomers()
{
return customers.size();
}
public boolean getCustomer(String accountNumber)
{
for(Customer customer : customers)
{
if(accountNumber.equals(customer.getAccountNumber()))
{
customer.printCustomerDetails();
return true;
}
}
return false;
}
public void getAllCustomers()
{
for(Customer customer : customers)
{
customer.printCustomerDetails();
System.out.println("\n");
}
}
public boolean removeCustomer(String accountNumber)
{
int index = 0;
for (Customer customer: customers)
{
if (accountNumber.equals(customer.getAccountNumber()))
{
customers.remove(index);
return true;
}
index++;
}
return false;
}
}
I think all you need to do is create a new Customer object in your addCustomer() method. This would probably require getting additional details:
public void addCustomer()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter customer name: ");
String name = scanner.nextLine();
//any additional details
Customer customer = new Customer(name, otherParams);
customers.add(customer);
}
Hope that helps!