SlideShare a Scribd company logo
1 of 14
Download to read offline
JAVA...W'i't'h
N.E.T_B.E.A.N.S_______________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
____________________________________________________
***********Product*********************
package rooster.nest;
import java.text.NumberFormat;
public class Product {
private long id;
private String code;
private String description;
private double price;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String name) {
this.description = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getPriceFormatted() {
NumberFormat currencyFormatter =
NumberFormat.getCurrencyInstance();
return currencyFormatter.format(getPrice());
}
}
********DBException************
package crows.foot;
/*
* This is just a wrapper class so we can throw a common exception for
* the UI to catch without tightly coupling the UI to the database layer.
*/
public class DBException extends Exception {
DBException() {}
DBException(Exception e) {
super(e);
}
}
*******DBUtil************
package crows.foot;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
private static Connection connection;
private DBUtil() {}
public static synchronized Connection getConnection() throws DBException {
if (connection != null) {
return connection;
}
else {
try {
// set the db url, username, and password
String url = "jdbc:mysql://localhost:3306/mma";
String username = "mma_user";
String password = "sesame";
// get and return connection
connection = DriverManager.getConnection(
url, username, password);
return connection;
} catch (SQLException e) {
throw new DBException(e);
}
}
}
public static synchronized void closeConnection() throws DBException {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
throw new DBException(e);
} finally {
connection = null;
}
}
}
}
*************ProductDB**************
package crows.foot;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import rooster.nest.Product;
public class ProductDB {
private static Product getProductFromRow(ResultSet rs) throws SQLException {
int productID = rs.getInt(1);
String code = rs.getString(2);
String description = rs.getString(3);
double price = rs.getDouble(4);
String note = rs.getString(5);
Product p = new Product();
p.setId(productID);
p.setCode(code);
p.setDescription(description);
p.setPrice(price);
return p;
}
public static List getAll() throws DBException {
String sql = "SELECT * FROM Product ORDER BY ProductID";
List products = new ArrayList<>();
Connection connection = DBUtil.getConnection();
try (PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
Product p = getProductFromRow(rs);
products.add(p);
}
rs.close();
return products;
} catch (SQLException e) {
throw new DBException(e);
}
}
public static Product get(String productCode) throws DBException {
String sql = "SELECT * FROM Product WHERE Code = ?";
Connection connection = DBUtil.getConnection();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, productCode);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
Product p = getProductFromRow(rs);
rs.close();
return p;
} else {
rs.close();
return null;
}
} catch (SQLException e) {
throw new DBException(e);
}
}
public static void add(Product product) throws DBException {
String sql
= "INSERT INTO Product (Code, Description, ListPrice) "
+ "VALUES (?, ?, ?)";
Connection connection = DBUtil.getConnection();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, product.getCode());
ps.setString(2, product.getDescription());
ps.setDouble(3, product.getPrice());
ps.executeUpdate();
} catch (SQLException e) {
throw new DBException(e);
}
}
public static void update(Product product) throws DBException {
String sql = "UPDATE Product SET "
+ "Code = ?, "
+ "Description = ?, "
+ "ListPrice = ?"
+ "WHERE ProductID = ?";
Connection connection = DBUtil.getConnection();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, product.getCode());
ps.setString(2, product.getDescription());
ps.setDouble(3, product.getPrice());
ps.setLong(4, product.getId());
ps.executeUpdate();
} catch (SQLException e) {
throw new DBException(e);
}
}
public static void delete(Product product)
throws DBException {
String sql = "DELETE FROM Product "
+ "WHERE ProductID = ?";
Connection connection = DBUtil.getConnection();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setLong(1, product.getId());
ps.executeUpdate();
} catch (SQLException e) {
throw new DBException(e);
}
}
}
***********Console*****************
package dog.breath;
import java.util.Scanner;
public class Console {
private static Scanner sc = new Scanner(System.in);
public static void displayNewLine() {
System.out.println();
}
public static void display(String string) {
System.out.println(string);
}
public static String getString(String prompt) {
System.out.print(prompt);
String s = sc.nextLine(); // read the whole line
return s;
}
public static int getInt(String prompt) {
boolean isValid = false;
int i = 0;
while (isValid == false) {
System.out.print(prompt);
try {
i = Integer.parseInt(sc.nextLine());
isValid = true;
} catch (NumberFormatException e) {
System.out.println("Error! Invalid integer value. Try again.");
}
}
return i;
}
public static int getInt(String prompt, int min, int max) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
i = getInt(prompt);
if (i <= min) {
System.out.println(
"Error! Number must be greater than " + min);
} else if (i >= max) {
System.out.println(
"Error! Number must be less than " + max);
} else {
isValid = true;
}
}
return i;
}
public static double getDouble(String prompt) {
boolean isValid = false;
double d = 0;
while (isValid == false) {
System.out.print(prompt);
try {
d = Double.parseDouble(sc.nextLine());
isValid = true;
} catch (NumberFormatException e) {
System.out.println("Error! Invalid decimal value. Try again.");
}
}
return d;
}
public static double getDouble(String prompt,
double min, double max) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
d = getDouble(prompt);
if (d <= min) {
System.out.println(
"Error! Number must be greater than " + min);
} else if (d >= max) {
System.out.println(
"Error! Number must be less than " + max);
} else {
isValid = true;
}
}
return d;
}
}
*************Main***************
package dog.breath;
import java.util.List;
import rooster.nest.Product;
import crows.foot.DBException;
import crows.foot.DBUtil;
import crows.foot.ProductDB;
public class Main {
// declare a class variable
public static void main(String args[]) {
// display a welcome message
Console.displayNewLine();
Console.display("Welcome to the Product Manager ");
// display the command menu
displayMenu();
// perform 1 or more actions
String action = "";
while (!action.equalsIgnoreCase("exit")) {
// get the input from the user
action = Console.getString("Enter a command: ");
Console.displayNewLine();
if (action.equalsIgnoreCase("list")) {
displayAllProducts();
} else if (action.equalsIgnoreCase("add")) {
addProduct();
} else if (action.equalsIgnoreCase("update")) {
updateProduct();
} else if (action.equalsIgnoreCase("del") ||
action.equalsIgnoreCase("delete")) {
deleteProduct();
} else if (action.equalsIgnoreCase("help") ||
action.equalsIgnoreCase("menu")) {
displayMenu();
} else if (action.equalsIgnoreCase("exit")) {
Console.display("Bye. ");
} else {
Console.display("Error! Not a valid command. ");
}
}
}
public static void displayMenu() {
Console.display("COMMAND MENU");
Console.display("list - List all products");
Console.display("add - Add a product");
Console.display("update - Update a product");
Console.display("del - Delete a product");
Console.display("help - Show this menu");
Console.display("exit - Exit this application ");
}
public static void displayAllProducts() {
Console.display("PRODUCT LIST");
List products = null;
try {
products = ProductDB.getAll();
} catch (DBException e) {
Console.display(e + " ");
}
if (products == null) {
Console.display("Error! Unable to get products. ");
} else {
Product p;
StringBuilder sb = new StringBuilder();
for (Product product : products) {
p = product;
sb.append(StringUtil.padWithSpaces(
p.getCode(), 12));
sb.append(StringUtil.padWithSpaces(
p.getDescription(), 34));
sb.append(p.getPriceFormatted());
sb.append(" ");
}
Console.display(sb.toString());
}
}
public static void addProduct() {
String code = Console.getString("Enter product code: ");
String description = Console.getString("Enter product name: ");
double price = Console.getDouble("Enter price: ");
Product product = new Product();
product.setCode(code);
product.setDescription(description);
product.setPrice(price);
try {
ProductDB.add(product);
Console.display(product.getDescription()
+ " was added to the database. ");
} catch (DBException e) {
Console.display("Error! Unable to add product.");
Console.display(e + " ");
}
}
public static void updateProduct() {
String code = Console.getString("Enter product code to update: ");
Product product;
try {
product = ProductDB.get(code);
if (product == null) {
throw new Exception("Product not found.");
}
} catch (Exception e) {
Console.display("Error! Unable to update product.");
Console.display(e + " ");
return;
}
String description = Console.getString("Enter product name: ");
double price = Console.getDouble("Enter price: ");
product.setDescription(description);
product.setPrice(price);
try {
ProductDB.update(product);
} catch (DBException e) {
Console.display("Error! Unable to update product.");
Console.display(e + " ");
}
Console.display(product.getDescription() + " was updated in the database. ");
}
public static void deleteProduct() {
String code = Console.getString("Enter product code to delete: ");
Product product;
try {
product = ProductDB.get(code);
if (product == null) {
throw new Exception("Product not found.");
}
} catch (Exception e) {
Console.display("Error! Unable to delete product.");
Console.display(e + " ");
return;
}
try {
ProductDB.delete(product);
} catch (DBException e) {
Console.display("Error! Unable to delete product.");
Console.display(e + " ");
}
Console.display(product.getDescription() + " was deleted from the database. ");
}
public static void exit() {
try {
DBUtil.closeConnection();
} catch (DBException e) {
Console.display("Error! Unable to close connection.");
Console.display(e + " ");
}
System.out.println("Bye. ");
System.exit(0);
}
}
***********StringUtil********************
package dog.breath;
public class StringUtil {
public static String padWithSpaces(String s, int length) {
if (s.length() < length) {
StringBuilder sb = new StringBuilder(s);
while (sb.length() < length) {
sb.append(" ");
}
return sb.toString();
} else {
return s.substring(0, length);
}
}
}
Solution
Java defines several bitwise operators, which can be applied to the integer sorts, long, int, short,
char, and byte.
Bitwise operator works on bits and performs bit-via-bit operation. count on if a = 60 and b = 13;
now in binary format they'll be as follows
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
athe subsequent desk lists the bitwise operators
anticipate integer variable A holds 60 and variable B holds thirteen then
show Examples
Operator Description example
& (bitwise and) Binary AND Operator copies a bit to the end result if it exists in each
operands. (A & B) will supply 12 that is 0000 1100
a chunk if it exists in either B) will supply 61 that is 0011 1101
^ (bitwise XOR) Binary XOR Operator copies the bit if it's far set in one operand but no
longer both. (A ^ B) will deliver forty nine that's 0011 0001
~ (bitwise compliment) Binary Ones supplement Operator is unary and has the effect of
'flipping' bits. (~A ) will supply -61 which is 1100 0011 in 2's supplement shape because of a
signed binary range.
<< (left shift) Binary Left Shift Operator. The left operands fee is moved left by using the
variety of bits distinct by means of the proper operand. A << 2 will give 240 which is 1111
0000
>> (proper shift) Binary right Shift Operator. The left operands fee is moved proper by using
the number of bits detailed through the right operand. A >> 2 will give 15 which is 1111
>>> (zero fill right shift) Shift proper 0 fill operator. The left operands price is moved proper
by the wide variety of bits detailed by means of the right operand and shifted values are filled up
with zeros. A >>>2 will give 15

More Related Content

Similar to JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf

This is to test a balanced tree. I need help testing an unbalanced t.pdf
This is to test a balanced tree. I need help testing an unbalanced t.pdfThis is to test a balanced tree. I need help testing an unbalanced t.pdf
This is to test a balanced tree. I need help testing an unbalanced t.pdfakaluza07
 
Nodejs do teste de unidade ao de integração
Nodejs  do teste de unidade ao de integraçãoNodejs  do teste de unidade ao de integração
Nodejs do teste de unidade ao de integraçãoVinícius Pretto da Silva
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mockskenbot
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfkostikjaylonshaewe47
 
WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015Fernando Daciuk
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testingVisual Engineering
 
Chaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreChaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreNicolas Carlo
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Beautiful java script
Beautiful java scriptBeautiful java script
Beautiful java scriptÜrgo Ringo
 
I Have the following Java program in which converts Date to Words an.pdf
I Have the following Java program in which converts Date to Words an.pdfI Have the following Java program in which converts Date to Words an.pdf
I Have the following Java program in which converts Date to Words an.pdfallystraders
 
Java programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdfJava programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdffathimafancy
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql JOYITAKUNDU1
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 

Similar to JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf (20)

This is to test a balanced tree. I need help testing an unbalanced t.pdf
This is to test a balanced tree. I need help testing an unbalanced t.pdfThis is to test a balanced tree. I need help testing an unbalanced t.pdf
This is to test a balanced tree. I need help testing an unbalanced t.pdf
 
Nodejs do teste de unidade ao de integração
Nodejs  do teste de unidade ao de integraçãoNodejs  do teste de unidade ao de integração
Nodejs do teste de unidade ao de integração
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mocks
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
 
java assignment
java assignmentjava assignment
java assignment
 
WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
Chaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreChaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscore
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Day 5
Day 5Day 5
Day 5
 
Beautiful java script
Beautiful java scriptBeautiful java script
Beautiful java script
 
07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt
 
I Have the following Java program in which converts Date to Words an.pdf
I Have the following Java program in which converts Date to Words an.pdfI Have the following Java program in which converts Date to Words an.pdf
I Have the following Java program in which converts Date to Words an.pdf
 
Java programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdfJava programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdf
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 
My java file
My java fileMy java file
My java file
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 

More from calderoncasto9163

LOS At the time of her death on September 4, 2015, Alicia held the .pdf
LOS At the time of her death on September 4, 2015, Alicia held the .pdfLOS At the time of her death on September 4, 2015, Alicia held the .pdf
LOS At the time of her death on September 4, 2015, Alicia held the .pdfcalderoncasto9163
 
Match the following terms with the definitions given belowTerms Gi.pdf
Match the following terms with the definitions given belowTerms Gi.pdfMatch the following terms with the definitions given belowTerms Gi.pdf
Match the following terms with the definitions given belowTerms Gi.pdfcalderoncasto9163
 
Let us roll a die twice. The number from the first throw is denoted .pdf
Let us roll a die twice. The number from the first throw is denoted .pdfLet us roll a die twice. The number from the first throw is denoted .pdf
Let us roll a die twice. The number from the first throw is denoted .pdfcalderoncasto9163
 
Is there relationship between having a high school education and kno.pdf
Is there relationship between having a high school education and kno.pdfIs there relationship between having a high school education and kno.pdf
Is there relationship between having a high school education and kno.pdfcalderoncasto9163
 
In a survey, 600 mothers and fathers were asked about the importance.pdf
In a survey, 600 mothers and fathers were asked about the importance.pdfIn a survey, 600 mothers and fathers were asked about the importance.pdf
In a survey, 600 mothers and fathers were asked about the importance.pdfcalderoncasto9163
 
in html 1 A Header with font size ranging from h4 to h1 with at l.pdf
in html 1 A Header with font size ranging from h4 to h1 with at l.pdfin html 1 A Header with font size ranging from h4 to h1 with at l.pdf
in html 1 A Header with font size ranging from h4 to h1 with at l.pdfcalderoncasto9163
 
Identify these monomers (general classification). Are the monomers h.pdf
Identify these monomers (general classification).  Are the monomers h.pdfIdentify these monomers (general classification).  Are the monomers h.pdf
Identify these monomers (general classification). Are the monomers h.pdfcalderoncasto9163
 
How is the Internet come about How was the World Wide Web ( WWW .pdf
How is the Internet come about  How was the World Wide Web ( WWW .pdfHow is the Internet come about  How was the World Wide Web ( WWW .pdf
How is the Internet come about How was the World Wide Web ( WWW .pdfcalderoncasto9163
 
Explain the answers in sufficient details i.e show the work ace Wha.pdf
Explain the answers in sufficient details i.e show the work ace Wha.pdfExplain the answers in sufficient details i.e show the work ace Wha.pdf
Explain the answers in sufficient details i.e show the work ace Wha.pdfcalderoncasto9163
 
Each figure is an isometry image of the figure at the right. Tell whe.pdf
Each figure is an isometry image of the figure at the right. Tell whe.pdfEach figure is an isometry image of the figure at the right. Tell whe.pdf
Each figure is an isometry image of the figure at the right. Tell whe.pdfcalderoncasto9163
 
E. None of the above.E. Actually, they differ in all of these ways.pdf
E. None of the above.E. Actually, they differ in all of these ways.pdfE. None of the above.E. Actually, they differ in all of these ways.pdf
E. None of the above.E. Actually, they differ in all of these ways.pdfcalderoncasto9163
 
Describe the difference between a. The pulmonary and systemic circula.pdf
Describe the difference between a. The pulmonary and systemic circula.pdfDescribe the difference between a. The pulmonary and systemic circula.pdf
Describe the difference between a. The pulmonary and systemic circula.pdfcalderoncasto9163
 
Cross a homozygous running, heterozygous black mouse with a waltzing.pdf
Cross a homozygous running, heterozygous black mouse with a waltzing.pdfCross a homozygous running, heterozygous black mouse with a waltzing.pdf
Cross a homozygous running, heterozygous black mouse with a waltzing.pdfcalderoncasto9163
 
Describe some effects that cybertechnology has had so far for our se.pdf
Describe some effects that cybertechnology has had so far for our se.pdfDescribe some effects that cybertechnology has had so far for our se.pdf
Describe some effects that cybertechnology has had so far for our se.pdfcalderoncasto9163
 
Choose a deployment platform that allows for the implementation o.pdf
Choose a deployment platform that allows for the implementation o.pdfChoose a deployment platform that allows for the implementation o.pdf
Choose a deployment platform that allows for the implementation o.pdfcalderoncasto9163
 
Abstract Base Class (C++ Program)Create an abstract base class cal.pdf
Abstract Base Class (C++ Program)Create an abstract base class cal.pdfAbstract Base Class (C++ Program)Create an abstract base class cal.pdf
Abstract Base Class (C++ Program)Create an abstract base class cal.pdfcalderoncasto9163
 
A range of values estimated to have a high probably of containing th.pdf
A range of values estimated to have a high probably of containing th.pdfA range of values estimated to have a high probably of containing th.pdf
A range of values estimated to have a high probably of containing th.pdfcalderoncasto9163
 
A thrown lump of clay hits a block in mid air and sticks to it. what.pdf
A thrown lump of clay hits a block in mid air and sticks to it. what.pdfA thrown lump of clay hits a block in mid air and sticks to it. what.pdf
A thrown lump of clay hits a block in mid air and sticks to it. what.pdfcalderoncasto9163
 
Answer die following questions with short answers Explain the d.pdf
Answer die following questions with short answers  Explain the d.pdfAnswer die following questions with short answers  Explain the d.pdf
Answer die following questions with short answers Explain the d.pdfcalderoncasto9163
 
A single breeding pair of rabbits is introduced to Australia in 1900.pdf
A single breeding pair of rabbits is introduced to Australia in 1900.pdfA single breeding pair of rabbits is introduced to Australia in 1900.pdf
A single breeding pair of rabbits is introduced to Australia in 1900.pdfcalderoncasto9163
 

More from calderoncasto9163 (20)

LOS At the time of her death on September 4, 2015, Alicia held the .pdf
LOS At the time of her death on September 4, 2015, Alicia held the .pdfLOS At the time of her death on September 4, 2015, Alicia held the .pdf
LOS At the time of her death on September 4, 2015, Alicia held the .pdf
 
Match the following terms with the definitions given belowTerms Gi.pdf
Match the following terms with the definitions given belowTerms Gi.pdfMatch the following terms with the definitions given belowTerms Gi.pdf
Match the following terms with the definitions given belowTerms Gi.pdf
 
Let us roll a die twice. The number from the first throw is denoted .pdf
Let us roll a die twice. The number from the first throw is denoted .pdfLet us roll a die twice. The number from the first throw is denoted .pdf
Let us roll a die twice. The number from the first throw is denoted .pdf
 
Is there relationship between having a high school education and kno.pdf
Is there relationship between having a high school education and kno.pdfIs there relationship between having a high school education and kno.pdf
Is there relationship between having a high school education and kno.pdf
 
In a survey, 600 mothers and fathers were asked about the importance.pdf
In a survey, 600 mothers and fathers were asked about the importance.pdfIn a survey, 600 mothers and fathers were asked about the importance.pdf
In a survey, 600 mothers and fathers were asked about the importance.pdf
 
in html 1 A Header with font size ranging from h4 to h1 with at l.pdf
in html 1 A Header with font size ranging from h4 to h1 with at l.pdfin html 1 A Header with font size ranging from h4 to h1 with at l.pdf
in html 1 A Header with font size ranging from h4 to h1 with at l.pdf
 
Identify these monomers (general classification). Are the monomers h.pdf
Identify these monomers (general classification).  Are the monomers h.pdfIdentify these monomers (general classification).  Are the monomers h.pdf
Identify these monomers (general classification). Are the monomers h.pdf
 
How is the Internet come about How was the World Wide Web ( WWW .pdf
How is the Internet come about  How was the World Wide Web ( WWW .pdfHow is the Internet come about  How was the World Wide Web ( WWW .pdf
How is the Internet come about How was the World Wide Web ( WWW .pdf
 
Explain the answers in sufficient details i.e show the work ace Wha.pdf
Explain the answers in sufficient details i.e show the work ace Wha.pdfExplain the answers in sufficient details i.e show the work ace Wha.pdf
Explain the answers in sufficient details i.e show the work ace Wha.pdf
 
Each figure is an isometry image of the figure at the right. Tell whe.pdf
Each figure is an isometry image of the figure at the right. Tell whe.pdfEach figure is an isometry image of the figure at the right. Tell whe.pdf
Each figure is an isometry image of the figure at the right. Tell whe.pdf
 
E. None of the above.E. Actually, they differ in all of these ways.pdf
E. None of the above.E. Actually, they differ in all of these ways.pdfE. None of the above.E. Actually, they differ in all of these ways.pdf
E. None of the above.E. Actually, they differ in all of these ways.pdf
 
Describe the difference between a. The pulmonary and systemic circula.pdf
Describe the difference between a. The pulmonary and systemic circula.pdfDescribe the difference between a. The pulmonary and systemic circula.pdf
Describe the difference between a. The pulmonary and systemic circula.pdf
 
Cross a homozygous running, heterozygous black mouse with a waltzing.pdf
Cross a homozygous running, heterozygous black mouse with a waltzing.pdfCross a homozygous running, heterozygous black mouse with a waltzing.pdf
Cross a homozygous running, heterozygous black mouse with a waltzing.pdf
 
Describe some effects that cybertechnology has had so far for our se.pdf
Describe some effects that cybertechnology has had so far for our se.pdfDescribe some effects that cybertechnology has had so far for our se.pdf
Describe some effects that cybertechnology has had so far for our se.pdf
 
Choose a deployment platform that allows for the implementation o.pdf
Choose a deployment platform that allows for the implementation o.pdfChoose a deployment platform that allows for the implementation o.pdf
Choose a deployment platform that allows for the implementation o.pdf
 
Abstract Base Class (C++ Program)Create an abstract base class cal.pdf
Abstract Base Class (C++ Program)Create an abstract base class cal.pdfAbstract Base Class (C++ Program)Create an abstract base class cal.pdf
Abstract Base Class (C++ Program)Create an abstract base class cal.pdf
 
A range of values estimated to have a high probably of containing th.pdf
A range of values estimated to have a high probably of containing th.pdfA range of values estimated to have a high probably of containing th.pdf
A range of values estimated to have a high probably of containing th.pdf
 
A thrown lump of clay hits a block in mid air and sticks to it. what.pdf
A thrown lump of clay hits a block in mid air and sticks to it. what.pdfA thrown lump of clay hits a block in mid air and sticks to it. what.pdf
A thrown lump of clay hits a block in mid air and sticks to it. what.pdf
 
Answer die following questions with short answers Explain the d.pdf
Answer die following questions with short answers  Explain the d.pdfAnswer die following questions with short answers  Explain the d.pdf
Answer die following questions with short answers Explain the d.pdf
 
A single breeding pair of rabbits is introduced to Australia in 1900.pdf
A single breeding pair of rabbits is introduced to Australia in 1900.pdfA single breeding pair of rabbits is introduced to Australia in 1900.pdf
A single breeding pair of rabbits is introduced to Australia in 1900.pdf
 

Recently uploaded

भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 

Recently uploaded (20)

भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 

JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf

  • 1. JAVA...W'i't'h N.E.T_B.E.A.N.S_______________________________________________________________ _____________________________________________________________________________ _____________________________________________________________________________ ____________________________________________________ ***********Product********************* package rooster.nest; import java.text.NumberFormat; public class Product { private long id; private String code; private String description; private double price; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDescription() { return description; } public void setDescription(String name) { this.description = name; } public double getPrice() { return price; } public void setPrice(double price) {
  • 2. this.price = price; } public String getPriceFormatted() { NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(); return currencyFormatter.format(getPrice()); } } ********DBException************ package crows.foot; /* * This is just a wrapper class so we can throw a common exception for * the UI to catch without tightly coupling the UI to the database layer. */ public class DBException extends Exception { DBException() {} DBException(Exception e) { super(e); } } *******DBUtil************ package crows.foot; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBUtil { private static Connection connection; private DBUtil() {} public static synchronized Connection getConnection() throws DBException { if (connection != null) { return connection; }
  • 3. else { try { // set the db url, username, and password String url = "jdbc:mysql://localhost:3306/mma"; String username = "mma_user"; String password = "sesame"; // get and return connection connection = DriverManager.getConnection( url, username, password); return connection; } catch (SQLException e) { throw new DBException(e); } } } public static synchronized void closeConnection() throws DBException { if (connection != null) { try { connection.close(); } catch (SQLException e) { throw new DBException(e); } finally { connection = null; } } } } *************ProductDB************** package crows.foot; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List;
  • 4. import rooster.nest.Product; public class ProductDB { private static Product getProductFromRow(ResultSet rs) throws SQLException { int productID = rs.getInt(1); String code = rs.getString(2); String description = rs.getString(3); double price = rs.getDouble(4); String note = rs.getString(5); Product p = new Product(); p.setId(productID); p.setCode(code); p.setDescription(description); p.setPrice(price); return p; } public static List getAll() throws DBException { String sql = "SELECT * FROM Product ORDER BY ProductID"; List products = new ArrayList<>(); Connection connection = DBUtil.getConnection(); try (PreparedStatement ps = connection.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { while (rs.next()) { Product p = getProductFromRow(rs); products.add(p); } rs.close(); return products; } catch (SQLException e) { throw new DBException(e); } } public static Product get(String productCode) throws DBException { String sql = "SELECT * FROM Product WHERE Code = ?"; Connection connection = DBUtil.getConnection(); try (PreparedStatement ps = connection.prepareStatement(sql)) {
  • 5. ps.setString(1, productCode); ResultSet rs = ps.executeQuery(); if (rs.next()) { Product p = getProductFromRow(rs); rs.close(); return p; } else { rs.close(); return null; } } catch (SQLException e) { throw new DBException(e); } } public static void add(Product product) throws DBException { String sql = "INSERT INTO Product (Code, Description, ListPrice) " + "VALUES (?, ?, ?)"; Connection connection = DBUtil.getConnection(); try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setString(1, product.getCode()); ps.setString(2, product.getDescription()); ps.setDouble(3, product.getPrice()); ps.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } public static void update(Product product) throws DBException { String sql = "UPDATE Product SET " + "Code = ?, " + "Description = ?, " + "ListPrice = ?" + "WHERE ProductID = ?"; Connection connection = DBUtil.getConnection(); try (PreparedStatement ps = connection.prepareStatement(sql)) {
  • 6. ps.setString(1, product.getCode()); ps.setString(2, product.getDescription()); ps.setDouble(3, product.getPrice()); ps.setLong(4, product.getId()); ps.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } public static void delete(Product product) throws DBException { String sql = "DELETE FROM Product " + "WHERE ProductID = ?"; Connection connection = DBUtil.getConnection(); try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setLong(1, product.getId()); ps.executeUpdate(); } catch (SQLException e) { throw new DBException(e); } } } ***********Console***************** package dog.breath; import java.util.Scanner; public class Console { private static Scanner sc = new Scanner(System.in); public static void displayNewLine() { System.out.println(); } public static void display(String string) { System.out.println(string); } public static String getString(String prompt) { System.out.print(prompt);
  • 7. String s = sc.nextLine(); // read the whole line return s; } public static int getInt(String prompt) { boolean isValid = false; int i = 0; while (isValid == false) { System.out.print(prompt); try { i = Integer.parseInt(sc.nextLine()); isValid = true; } catch (NumberFormatException e) { System.out.println("Error! Invalid integer value. Try again."); } } return i; } public static int getInt(String prompt, int min, int max) { int i = 0; boolean isValid = false; while (isValid == false) { i = getInt(prompt); if (i <= min) { System.out.println( "Error! Number must be greater than " + min); } else if (i >= max) { System.out.println( "Error! Number must be less than " + max); } else { isValid = true; } } return i; } public static double getDouble(String prompt) { boolean isValid = false;
  • 8. double d = 0; while (isValid == false) { System.out.print(prompt); try { d = Double.parseDouble(sc.nextLine()); isValid = true; } catch (NumberFormatException e) { System.out.println("Error! Invalid decimal value. Try again."); } } return d; } public static double getDouble(String prompt, double min, double max) { double d = 0; boolean isValid = false; while (isValid == false) { d = getDouble(prompt); if (d <= min) { System.out.println( "Error! Number must be greater than " + min); } else if (d >= max) { System.out.println( "Error! Number must be less than " + max); } else { isValid = true; } } return d; } } *************Main*************** package dog.breath; import java.util.List; import rooster.nest.Product; import crows.foot.DBException;
  • 9. import crows.foot.DBUtil; import crows.foot.ProductDB; public class Main { // declare a class variable public static void main(String args[]) { // display a welcome message Console.displayNewLine(); Console.display("Welcome to the Product Manager "); // display the command menu displayMenu(); // perform 1 or more actions String action = ""; while (!action.equalsIgnoreCase("exit")) { // get the input from the user action = Console.getString("Enter a command: "); Console.displayNewLine(); if (action.equalsIgnoreCase("list")) { displayAllProducts(); } else if (action.equalsIgnoreCase("add")) { addProduct(); } else if (action.equalsIgnoreCase("update")) { updateProduct(); } else if (action.equalsIgnoreCase("del") || action.equalsIgnoreCase("delete")) { deleteProduct(); } else if (action.equalsIgnoreCase("help") || action.equalsIgnoreCase("menu")) { displayMenu(); } else if (action.equalsIgnoreCase("exit")) { Console.display("Bye. "); } else { Console.display("Error! Not a valid command. "); } } }
  • 10. public static void displayMenu() { Console.display("COMMAND MENU"); Console.display("list - List all products"); Console.display("add - Add a product"); Console.display("update - Update a product"); Console.display("del - Delete a product"); Console.display("help - Show this menu"); Console.display("exit - Exit this application "); } public static void displayAllProducts() { Console.display("PRODUCT LIST"); List products = null; try { products = ProductDB.getAll(); } catch (DBException e) { Console.display(e + " "); } if (products == null) { Console.display("Error! Unable to get products. "); } else { Product p; StringBuilder sb = new StringBuilder(); for (Product product : products) { p = product; sb.append(StringUtil.padWithSpaces( p.getCode(), 12)); sb.append(StringUtil.padWithSpaces( p.getDescription(), 34)); sb.append(p.getPriceFormatted()); sb.append(" "); } Console.display(sb.toString()); } } public static void addProduct() {
  • 11. String code = Console.getString("Enter product code: "); String description = Console.getString("Enter product name: "); double price = Console.getDouble("Enter price: "); Product product = new Product(); product.setCode(code); product.setDescription(description); product.setPrice(price); try { ProductDB.add(product); Console.display(product.getDescription() + " was added to the database. "); } catch (DBException e) { Console.display("Error! Unable to add product."); Console.display(e + " "); } } public static void updateProduct() { String code = Console.getString("Enter product code to update: "); Product product; try { product = ProductDB.get(code); if (product == null) { throw new Exception("Product not found."); } } catch (Exception e) { Console.display("Error! Unable to update product."); Console.display(e + " "); return; } String description = Console.getString("Enter product name: "); double price = Console.getDouble("Enter price: "); product.setDescription(description); product.setPrice(price); try {
  • 12. ProductDB.update(product); } catch (DBException e) { Console.display("Error! Unable to update product."); Console.display(e + " "); } Console.display(product.getDescription() + " was updated in the database. "); } public static void deleteProduct() { String code = Console.getString("Enter product code to delete: "); Product product; try { product = ProductDB.get(code); if (product == null) { throw new Exception("Product not found."); } } catch (Exception e) { Console.display("Error! Unable to delete product."); Console.display(e + " "); return; } try { ProductDB.delete(product); } catch (DBException e) { Console.display("Error! Unable to delete product."); Console.display(e + " "); } Console.display(product.getDescription() + " was deleted from the database. "); } public static void exit() { try { DBUtil.closeConnection();
  • 13. } catch (DBException e) { Console.display("Error! Unable to close connection."); Console.display(e + " "); } System.out.println("Bye. "); System.exit(0); } } ***********StringUtil******************** package dog.breath; public class StringUtil { public static String padWithSpaces(String s, int length) { if (s.length() < length) { StringBuilder sb = new StringBuilder(s); while (sb.length() < length) { sb.append(" "); } return sb.toString(); } else { return s.substring(0, length); } } } Solution Java defines several bitwise operators, which can be applied to the integer sorts, long, int, short, char, and byte. Bitwise operator works on bits and performs bit-via-bit operation. count on if a = 60 and b = 13; now in binary format they'll be as follows a = 0011 1100 b = 0000 1101 ----------------- a&b = 0000 1100 athe subsequent desk lists the bitwise operators
  • 14. anticipate integer variable A holds 60 and variable B holds thirteen then show Examples Operator Description example & (bitwise and) Binary AND Operator copies a bit to the end result if it exists in each operands. (A & B) will supply 12 that is 0000 1100 a chunk if it exists in either B) will supply 61 that is 0011 1101 ^ (bitwise XOR) Binary XOR Operator copies the bit if it's far set in one operand but no longer both. (A ^ B) will deliver forty nine that's 0011 0001 ~ (bitwise compliment) Binary Ones supplement Operator is unary and has the effect of 'flipping' bits. (~A ) will supply -61 which is 1100 0011 in 2's supplement shape because of a signed binary range. << (left shift) Binary Left Shift Operator. The left operands fee is moved left by using the variety of bits distinct by means of the proper operand. A << 2 will give 240 which is 1111 0000 >> (proper shift) Binary right Shift Operator. The left operands fee is moved proper by using the number of bits detailed through the right operand. A >> 2 will give 15 which is 1111 >>> (zero fill right shift) Shift proper 0 fill operator. The left operands price is moved proper by the wide variety of bits detailed by means of the right operand and shifted values are filled up with zeros. A >>>2 will give 15