Why Hibernate cant create DB? SQLSyntaxErrorException and CommandAcceptanceException - java

I have three DBs, of which hibernate can only create 2/3. Can someone explain why hibernate can not create a third table "goods"
1: org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table goods (ID integer not null, brand varchar(255), desc varchar(255), model varchar(255), price float(53) not null, type varchar(255), primary key (ID)) engine=InnoDB" via JDBC Statement
---> at Models.Main.main(Main.java:18) <---
2: Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc varchar(255), model varchar(255), price float(53) not null, type varchar(25' at line 1
<persistence
xmlns="https://jakarta.ee/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"
version="3.0">
<persistence-unit name="OrderDB">
<properties>
<property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/orderdb"/>
<property name="jakarta.persistence.jdbc.user" value="root"/>
<property name="jakarta.persistence.jdbc.password" value="qwer1234"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
MAIN:
package Models;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;
import java.util.List;
import java.util.Scanner;
public class Main {
static EntityManagerFactory emf;
static EntityManager em;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
emf = Persistence.createEntityManagerFactory("OrderDB");
while (true) {
System.out.println("1: add user");
System.out.println("2: add goods");
System.out.println("3: create order");
System.out.println("4: view users");
System.out.println("5: view goods");
System.out.println("6: view orders");
System.out.print("-> ");
String s = sc.nextLine();
switch (s) {
case "1":
addUser(sc);
break;
case "2":
addGoods(sc);
break;
case "3":
createOrder(sc);
break;
case "4":
viewUsers();
break;
case "5":
viewGoods();
break;
case "6":
viewOrders();
break;
default:
return;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
em.close();
emf.close();
}
}
private static void addUser(Scanner sc) {
System.out.println("Enter information about user:");
System.out.print("Enter name: ");
String name = sc.nextLine();
System.out.print("Enter last name: ");
String lastName = sc.nextLine();
System.out.print("Enter age: ");
String strAge = sc.nextLine();
int age = Integer.parseInt(strAge);
System.out.print("Enter email: ");
String email = sc.nextLine();
System.out.print("Enter phone: ");
String phone = sc.nextLine();
try {
em = emf.createEntityManager();
em.getTransaction().begin();
User user = new User(name, lastName, age, email, phone);
em.persist(user);
em.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
em.close();
}
}
private static void addGoods(Scanner sc) {
System.out.println("Enter information about product:");
System.out.print("Enter type: ");
String type = sc.nextLine();
System.out.print("Enter brand: ");
String brand = sc.nextLine();
System.out.print("Enter model: ");
String model = sc.nextLine();
System.out.print("Enter price: ");
double price = Double.parseDouble(sc.nextLine());
System.out.print("Enter description: ");
String desc = sc.nextLine();
try {
em = emf.createEntityManager();
em.getTransaction().begin();
Good good = new Good(type, brand, model, price, desc);
em.persist(good);
em.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
em.close();
}
}
private static void createOrder(Scanner sc) {
System.out.println("Enter information about order:");
System.out.print("Enter goods id: ");
int goodID = Integer.parseInt(sc.nextLine());
System.out.print("Enter user id: ");
int userID = Integer.parseInt(sc.nextLine());
System.out.print("Enter order name: ");
String orderName = sc.nextLine();
try {
em = emf.createEntityManager();
em.getTransaction().begin();
Order order = new Order(goodID, userID, orderName);
em.persist(order);
em.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
em.close();
}
}
private static void viewUsers() {
try {
em = emf.createEntityManager();
Query query = em.createQuery("SELECT u FROM User u", User.class);
List<User> list = (List<User>) query.getResultList();
for (User u : list)
System.out.println(u);
} catch (Exception e) {
e.printStackTrace();
} finally {
em.close();
}
}
private static void viewGoods() {
try {
em = emf.createEntityManager();
Query query = em.createQuery("SELECT g FROM Good g", Good.class);
List<Good> list = (List<Good>) query.getResultList();
for (Good g : list)
System.out.println(g);
} catch (Exception e) {
e.printStackTrace();
} finally {
em.close();
}
}
private static void viewOrders() {
try {
em = emf.createEntityManager();
Query query = em.createQuery("SELECT o FROM Order o", Order.class);
List<Order> list = (List<Order>) query.getResultList();
for (Order o : list)
System.out.println(o);
} catch (Exception e) {
e.printStackTrace();
} finally {
em.close();
}
}
}
enter code here
GOODS:
package Models;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
#Entity
#Table(name = "goods")
public class Good {
private int ID;
private String type;
private String brand;
private String model;
private double price;
private String desc;
public Good(String type, String brand, String model, double price, String desc) {
this.type = type;
this.brand = brand;
this.model = model;
this.price = price;
this.desc = desc;
}
public Good() {
}
#Id
#GeneratedValue
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
#Override
public String toString() {
return "Good ID: " + ID + System.lineSeparator()
+ "Type: " + type + " " + brand + " " + model + System.lineSeparator()
+ "Price: " + price + System.lineSeparator()
+ "Description: " + desc;
}
}

I went through your code. The only fishy part is
private String desc;
"DESC" is reserved keyword in databases.
If you look closely at the syntax(query) issued in your database,
it will show you
CREATE TABLE goods (ID INTEGER NOT NULL,brand VARCHAR (255),DESC VARCHAR(255), model VARCHAR (255), price FLOAT (53) NOT NULL,TYPE VARCHAR(255), PRIMARY KEY (ID)) ENGINE = INNODB
You can see the "DESC" turns blue and shows that it is reserved keyword for "descending".
Try changing it to something else like "descs" or you can define column and change it to something else like`
#Column(name="descs")
private String desc;
It will work.`

Related

SQLite truncates my data

I have data that looks like this in console:
"to add:
rand_num = 1-231881-6-70885-12
name = heat boy
type = caucasian
price = 700.0
date = 2018-08-01"
Instead I get this for some reason in database:
"to add:
rand_num = 1-231881-6-70885-12
name = heat boy
type = caucasian
price = 70"
My controller:
public class Controller {
private description = "to add: \n"+
"rand_num = 1-231881-6-70885-12 \n"+
"name = heat boy \n"+
"type = caucasian \n"+
"price = 700.0 \n"+
"date = 2018-08-01"
private Model textFields() {
Model model = new Model();
model.setRand_num(description.getText());
}
try {
DAOClass daoClass = new DAOCLass();
daoClass.insert(textFields());
}
catch(SQLException e){
System.out.println(e);
}catch(ClassNotFoundException e) {
System.out.println(e);
}
}
My model:
public class model {
private SimpleStringProperty description;
public Model() {
this("");
}
public model(String description) {
super();
this.rand_num = new SimpleStringProperty(description);
}
//getter
public String getDescription() {
return description.get();
}
//setter
public void setDescription(String description) {
this.description.set(description);
}
//property
public StringProperty descriptionProperty(){
return description;
}
#Override
public String toString() {
return "to add: " +
}
}
DAO class
public class DAO {
public void insert(Model model) throws SQLException, ClassNotFoundException {
//initializing PreparedStatement
PreparedStatement preparedStatement = null;
String updateQuery =
"INSERT INTO modelDB \n" +
"(description) \n" +
"VALUES \n" +
"(?)";
//Execute DELETE operation
try {
preparedStatement = connection.prepareStatement(updateQuery);
preparedStatement.setString(1, model.description());
preparedStatement.executeUpdate();
} catch (SQLException e) {
System.out.print("Error: " + e);
throw e;
}
finally {
if(preparedStatement != null)
{
preparedStatement.close();
}
}
}
}
My SQLite table structure:
CREATE TABLE userActivityLogs (
logId INTEGER PRIMARY KEY AUTOINCREMENT,
description VARCHAR (10000)
);
Now I know there is no limit for SQLite and even if there was I am using varChar(10000). It all displays perfectly on console but once it is in the database it is truncated. Why is that and how can I fix this issue?
I dont´t see your random number truncated so the varchar(10000) isn´t at play here.
What i see in your code is:
preparedStatement.setString(4, model.getPrice());
preparedStatement.setString(4, model.getDate());
You are using the same index for Price and Date.

How to input data in the very best way in object programming Java

Just to let you know:
I know how to use Scanner od BufferedReader, just dont know where to use it in this case.
I am working on my first bigger app in Java.
(I had to use SQLite as a DB)
That's some kind of gym app, where I will add my workouts (4 simple variables)
And then it will be saved in DB and sorted to read out.
My question is...
How should I add an Input from the user?
I have setters and getters and no Idea where this input should be added.
In main class? Should I build a new method?
package bazadanych;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
DBConnector d = new DBConnector();
d.addWorkout( "bicek", 12, 5,22052019);
List<Workout> workouts = d.allWorkouts();
for (int i=0; i < workouts.size(); i++) {
System.out.println("---------------------------------");
System.out.println("The name of the excersise: " + workouts.get(i).getName());
System.out.println(" Number of reps: " + workouts.get(i).getReps());
System.out.println(" Weight: " + workouts.get(i).getWeight() + "kg");
System.out.println("Date: " + workouts.get(i).getDate());
System.out.println("---------------------------------");
}
}
package bazadanych;
public class Workout extends DBConnector {
private int workoutId;
private String name;
private int reps;
private int weight;
private int date;
public Workout(int workoutId, String name, int weight, int reps, int date)
{
setWorkoutId(workoutId);
setName(name);
setWeight(weight);
setReps(reps);
setDate(date);
}
// Getters
public int getDate()
{
return date;
}
public int getWorkoutId()
{
return workoutId;
}
public String getName()
{
return name;
}
public int getReps()
{
return reps;
}
public int getWeight()
{
return weight;
}
//Setters
public void setDate(int date)
{
this.date = date;
}
public void setName(String name)
{
this.name = name;
}
public void setReps(int reps)
{
this.reps = reps;
}
public void setWorkoutId(int workoutId)
{
this.workoutId = workoutId;
}
public void setWeight(int weight)
{
this.weight = weight;
}
}
package bazadanych;
import java.sql.*;
import java.util.LinkedList;
import java.util.List;
public class DBConnector {
// connection with datebase
private Connection conn;
// The object used to execute a static SQL statement and returning the results
private Statement stat;
// Construct
public DBConnector()
{
try
{
Class.forName("org.sqlite.JDBC");
}
catch (ClassNotFoundException e)
{
System.err.println("There is no JDBC driver");
e.printStackTrace();
}
try
{
conn = DriverManager.getConnection("jdbc:sqlite:GymApp.db"); // GymApp will be the name of the datebase
stat = conn.createStatement();
}
catch (SQLException e)
{
System.err.println("I can not connect");
}
CreateStructure();
}
public boolean CreateStructure()
{
// Rule to delete the table and create new, when we want to rework number of columnes etc.
// String dropFirst = "DROP TABLE IF EXISTS workouts;";
String sql = "CREATE TABLE IF NOT EXISTS workouts"
+ "("
+ "workoutId INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name varchar(100),"
+ "reps INTEGER, "
+ " weight INTEGER,"
+ " date INTEGER"
+ ")";
try
{
// stat.execute(dropFirst);
stat.execute(sql);
}
catch (SQLException e)
{
System.err.println("There is a problem by Structure creation");
e.printStackTrace();
return false;
}
return true;
}
public boolean addWorkout( String name, int reps, int weight, int date)
{ String sql = " insert into workouts values (Null,?,?,?,?);";
try
(PreparedStatement pStmt = conn.prepareStatement(sql)){
pStmt.setString(1, name);
pStmt.setInt(2,reps);
pStmt.setInt(3,weight);
pStmt.setInt(4, date);
pStmt.execute();
}
catch(SQLException e)
{
System.err.println("Can not add a new contact");
e.printStackTrace();
return false;
}
return true;
}
public List<Workout> allWorkouts()
{
List<Workout> workouts = new LinkedList<Workout>();
try {
ResultSet show = stat.executeQuery("SELECT * FROM workouts ORDER BY date");
int id;
String name;
int reps;
int weight;
int date;
while (show.next())
{
id = show.getInt("workoutId");
name = show.getString("name");
reps = show.getInt("reps");
weight = show.getInt("weight");
date = show.getInt("date");
workouts.add(new Workout(id, name,reps,weight,date));
}
}
catch (SQLException e)
{
e.printStackTrace();
return null;
}
return workouts;
}
public void closeConnection() {
try{
conn.close();
}
catch (SQLException e) {
System.err.println("There is connection closing error");
e.printStackTrace();
}
}
}
To answer your main question, you should add the input from the user in the main method. You'd use an instance of Scanner to read the values of workout name, reps and weight. Date you could simply pick up the current date, code sample below.
A few other recommendations:
1 - Change the workout date to long, that's a standard in the industry.
2 - The method CreateStructure does not follow Java coding standards, rename it to createStructure.
3 - You are storing the workout ID as NULL, that could cause you trouble later when trying to retrieve the data from the database.
Code sample:
public static void main(String[] args) {
DBConnector d = new DBConnector();
// Retrieve input from the user
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int reps = sc.nextInt();
int weight = sc.nextInt();
// create the workout with the data
d.addWorkout( name, reps, weight, LocalDate.now().toEpochDay());
List<Workout> workouts = d.allWorkouts();
// print workouts
}

No Suitable Found for add String

Am trying to retrieve data I Chosen From mysql and filter table the Item I choose by getting value of chosen Item I created A list this list am trying to add on it the chosen Item but I fount an underlined error No Suitable Found for add String
this is my main.java contains code I use
List<Menu> listItem = new ArrayList<Menu>();
if (insertedNumberOfCovers) {
Menu m = new Menu();
m.getAllRows();
while (orderNotFinished) {
System.out.println("Please Choose Item From Menu List");
input = new Scanner(System.in);
itemChosen = input.nextLine();
boolean insertedMenuItemId = db.goTodataBase.checkMenuItemInDB(itemChosen);
if (insertedMenuItemId) {
System.out.println("You Choose Item ID: " + itemChosen);
listItem.add(m.getAllRows(itemChosen));
System.out.print("Do you need to add more Items ? ");
hasFinished = input.nextLine();
orderNotFinished = hasFinished.equals("yes");
} else {
System.out.println("Item Chosen doen't exist");
}
}
and this is Menu.java that I retrieve data from
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package enitities;
import javax.swing.JTable;
public class Menu {
private int Menu_Id;
private String Name;
private float Price;
private String Type;
private String Category;
public int getMenu_Id() {
return Menu_Id;
}
public void setMenu_Id(int Menu_Id) {
this.Menu_Id = Menu_Id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public float getPrice() {
return Price;
}
public void setPrice(float Price) {
this.Price = Price;
}
public String getType() {
return Type;
}
public void setType(String Type) {
this.Type = Type;
}
public String getCategory() {
return Category;
}
public void setCategory(String Category) {
this.Category = Category;
}
public void getAllRows() {
db.goTodataBase.printData("menu");
}
public Menu getAllRows(Menu itemChosen) {
db.goTodataBase.printData("menu");
return itemChosen;
}
public String getValueByName(String itemChosen) {
String strSelect = "select Menu_Id from menu"
+ "where name=" + Name;
return itemChosen;
}
}
and this method that am Using to Print Table Values
public static void printData(String tableNameOrSelectStatement) {
try {
setConnection();
Statement stmt = con.createStatement();
ResultSet rs;
String strSelectPart = tableNameOrSelectStatement.substring(0, 4).toLowerCase();
String strSelect;
if ("select ".equals(strSelectPart)) {
strSelect = tableNameOrSelectStatement;
} else {
strSelect = "select * from " + tableNameOrSelectStatement;
}
rs = stmt.executeQuery(strSelect);
ResultSetMetaData rsmd = rs.getMetaData();
int c = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= c; i++) {
if (i > 1) {
System.out.print(", ");
}
String columnValue = rs.getString(i);
// System.out.print(columnValue + " " + rsmd.getColumnName(i));
System.out.print(columnValue + " ");
}
System.out.println("");
}
} catch (Exception e) {
Tools.msgBox(e.getMessage());
}
}
the error in this line
listItem.add(m.getAllRows(itemChosen));
The type error is pretty clear to me:
Menu.getAllRows(...) returns String.
listItem.add(...) takes Menu as an argument.
A String is not a Menu. Therefore you have a type error.
That said: you have many, many other things wrong with this code. Names that defy standard Java naming conventions, methods that don't do anything useful (why does getAllRows take Object as an argument but just cast it to a String to return it?), using float to store a currency value, and probably more.

How to Choose more than one item in method in java

I have just created a senario that looping which was I have to choose columns what I have selected from data base like this javaMain which have the senario
package myrestorderproject;
import enitities.Menu;
import enitities.Tables;
import java.awt.List;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* #author DELL
*/
public class MyRestOrderProject {
private static Scanner input;
public static void main(String[] args) {
// TODO code application logic here
input = new Scanner(System.in);
System.out.println("*-*-*-*-*-*Welcome to MyRestaurant*-*-*-*-*-*\n");
System.out.println("Please Choose Table From Tables List");
Tables t = new Tables();
t.getAllRows();
ArrayList<String> listItem = new ArrayList<String>();
boolean orderNotFinished = true;
while (orderNotFinished) {
System.out.print("Enter Table Number: ");
String tableNumber = input.nextLine();
boolean insertedTableNumber = db.goTodataBase.checkTableNumber(tableNumber);
if (insertedTableNumber) {
System.out.println("You Choose Table Number: " + tableNumber);
Menu m = new Menu();
m.getAllRows();
while (orderNotFinished) {
System.out.println("Please Choose Item From Menu List");
input = new Scanner(System.in);
String itemChosen = input.nextLine();
boolean insertedMenuItemId = db.goTodataBase.checkMenuItemInDB(itemChosen);
if (insertedMenuItemId) {
System.out.println("You Choose Item ID: " + itemChosen);
listItem.add(m.getAllRows(itemChosen));
System.out.print("Do you need to add more Items ? ");
String hasFinished = input.nextLine();
orderNotFinished = hasFinished.equals("yes");
} else {
System.out.println("Item Chosen doen't exist");
}
}
} else {
System.out.println("Table number does not exist");
}
}
}
}
I need now in the part which print "Please Choose Item From Menu List" after I choose the right Item Close the while loop,and I need also to choose more than one item that if I choose Items from menu give me the items was chosen with details getting from menu table
Like If I Choose Item ID 1 +Item ID 2 + Item ID 3 says that you have chosen
Item 1 Vegetable Pakora 20.00 veg Starters
Item 1 Vegetable Pakora 20.00 veg Starters
Item 1 Chicken Tikka 20.00 Non-veg Starters
after that exit the while loop
as every column have an ID, name, price, type and Category
and this method that am using in previous senario
public static boolean checkMenuItemInDB(String menuId) {
try {
setConnection();
Statement stmt = con.createStatement();
String strCheck = "select * from menu where "
+ "Menu_Id=" + menuId;
stmt.executeQuery(strCheck);
while (stmt.getResultSet().next()) {
return true;
}
} catch (Exception e) {
}
return false;
}
this is menu Class
package enitities;
import javax.swing.JTable;
/**
*
* #author DELL
*/
public class Menu {
private int Menu_Id;
private String Name;
private float Price;
private String Type;
private String Category;
public int getMenu_Id() {
return Menu_Id;
}
public void setMenu_Id(int Menu_Id) {
this.Menu_Id = Menu_Id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public float getPrice() {
return Price;
}
public void setPrice(float Price) {
this.Price = Price;
}
public String getType() {
return Type;
}
public void setType(String Type) {
this.Type = Type;
}
public String getCategory() {
return Category;
}
public void setCategory(String Category) {
this.Category = Category;
}
public void getAllRows() {
db.goTodataBase.printData("menu");
}
public String getAllRows(String itemChosen) {
db.goTodataBase.printData("menu");
return itemChosen;
}
}
this is a method which I calls in getAllRows
public static void printData(String tableNameOrSelectStatement) {
try {
setConnection();
Statement stmt = con.createStatement();
ResultSet rs;
String strSelectPart = tableNameOrSelectStatement.substring(0, 4).toLowerCase();
String strSelect;
if ("select ".equals(strSelectPart)) {
strSelect = tableNameOrSelectStatement;
} else {
strSelect = "select * from " + tableNameOrSelectStatement;
}
rs = stmt.executeQuery(strSelect);
ResultSetMetaData rsmd = rs.getMetaData();
int c = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= c; i++) {
if (i > 1) {
System.out.print(", ");
}
String columnValue = rs.getString(i);
// System.out.print(columnValue + " " + rsmd.getColumnName(i));
System.out.print(columnValue + " ");
}
System.out.println("");
}
} catch (Exception e) {
Tools.msgBox(e.getMessage());
}
}
About the loop :
Programmer tips : You need to avoid as much as possible while(true)-loop.
In your case you could use a system of flag, it will look like :
boolean customerHasFinished = false;
while(!customerHasFinished){
...
//Do your stuff
...
System.out.print("Have you finished ? ");
String hasFinished = input.nextLine();
customerHasFinished = hasFinished.equals("yes");
}
About multiple items :
The best way to store multiple items is to use collection.
In your case, you will probably need to create a Java class that represent an Item. Having fields like name, cost, etc. And then create a collection of Item.
An example with an ArrayList :
List<Item> listItem = new ArrayList<Item>();
boolean orderNotFinished = true;
while (orderNotFinished) {
System.out.println("Please Choose an Item From Menu List");
input = new Scanner(System.in);
String itemChosen = input.nextLine();
boolean insertedMenuItemId = db.goTodataBase.checkMenuItemInDB(itemChosen);
if (insertedMenuItemId) {
System.out.println("You Choose Item ID: " + itemChosen);
listItem.add(Item.getItemByName(itemChosen)); //Add the chosen item to the list
System.out.print("You want something else ? ");
String hasFinished = input.nextLine();
orderNotFinished = hasFinished.equals("yes");
}else {
System.out.println("Item Chosen doen't exist");
}
}

Searching an ArrayList to change object's value

I've made an ArrayList of players that I want to search through to change the amount they have paid. I want to be able to enter in their ID, then be able to change their amount paid just for that player. I am also writing it to a CSV file but I am not sure how to update that file with the new value. I'm not sure about how to go about doing this.
What I want to do is just update a value in the ArrayList for a specific player based on player input on the registration ID, then I want to update that value in the file.
Here are my 3 classes that I have made: SquashPlayer
package squashapplication;
import java.util.Scanner;
/**
*
* #author Evan
*/
public class SquashPlayer {
private static int maxRegistrationId;
private int id;
private String name;
private String parentName;
private String phoneNumber;
private String email;
private int amountPaid;
public SquashPlayer() {
}
public SquashPlayer(boolean getFromUser){
System.out.println("Enter Full Name:");
this.name = FileUtility.getInput().nextLine();
System.out.println("Enter Parents name:");
this.parentName = FileUtility.getInput().nextLine();
System.out.println("Enter phone number:");
this.phoneNumber = FileUtility.getInput().nextLine();
System.out.println("Enter e-mail:");
this.email = FileUtility.getInput().nextLine();
System.out.println("Enter amount paid:");
this.amountPaid = FileUtility.getInput().nextInt();
FileUtility.getInput().nextLine();
this.id = ++ maxRegistrationId;
}
public SquashPlayer(int id, String name, int amountPaid , String phoneNumber, String parentName , String email ) {
this.id = id;
this.amountPaid = amountPaid;
this.name = name;
this.parentName = parentName;
this.email = email;
this.phoneNumber = phoneNumber;
}
public SquashPlayer(String[] parts) {
this(Integer.parseInt(parts[0]), parts[1], Integer.parseInt(parts[2]), parts[3],parts[4], parts[5]);
if (Integer.parseInt(parts[0]) > maxRegistrationId) {
maxRegistrationId = Integer.parseInt(parts[0]);
}
}
public SquashPlayer(String csvValues) {
this(csvValues.split(","));
}
public String getCSV() {
return id + "," + name + "," + amountPaid + "," + phoneNumber + "," + email + "," + parentName;
}
public String getCSV(boolean withLineFeed){
if(withLineFeed){
return getCSV()+System.lineSeparator();
}else{
return getCSV();
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAmountPaid() {
return amountPaid;
}
public void setAmountPaid(int amountPaid) {
this.amountPaid = amountPaid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "ID=" +id+ ", Name=" + name + ", email=" + email + ", Phone Number=" + phoneNumber + ", Amount Paid=" + amountPaid + ", Parent's Name: "+parentName;
}
}
Here is my main class:
package squashapplication;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
public class SquashMain {
public static String MENU = "Options:\nA) Add player\nS) Show players\n G) Update Amount Paid\nX) Exit";
public static String FILE_NAME = "c:\\cis2232\\players.csv";
public static void main(String[] args) throws IOException {
Files.createDirectories(Paths.get("/cis2232"));
ArrayList<SquashPlayer> theList = new ArrayList();
loadPlayers(theList);
String choice = "";
do{
System.out.println(MENU);
choice = FileUtility.getInput().nextLine().toUpperCase();
switch(choice){
case "A":
SquashPlayer player = new SquashPlayer(true);
theList.add(player);
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(FILE_NAME, true);
bw = new BufferedWriter(fw);
bw.write(player.getCSV(true));
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
if (fw != null) {
fw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
break;
case "S":
System.out.println("Here are the players");
for (SquashPlayer SquashPlayer : theList) {
System.out.println(SquashPlayer);
}
break;
case "G":
case "X":
System.out.println("Goodbye");
break;
default:
System.out.println("Invalid option");
break;
}
}while (!choice.equalsIgnoreCase("x"));
}
public static void loadPlayers(ArrayList squash){
System.out.println("Loading players from the list!");
int counter = 0;
try{
ArrayList<String> tester = (ArrayList<String>) Files.readAllLines(Paths.get(FILE_NAME));
for(String current:tester){
System.out.println("Loading: "+current);
SquashPlayer temp = new SquashPlayer(current);
squash.add(temp);
counter++;
}
}catch(IOException ex){
System.out.println("Error loading players from file.");
System.out.println(ex.getMessage());
}
System.out.println("Loaded players from file: "+ counter + " players");
}
}
And here is where I store my scanner in FileUtility:
package squashapplication;
import java.util.Scanner;
public class FileUtility {
private static Scanner input = new Scanner(System.in);
public static Scanner getInput() {
return input;
}
}

Categories