Java please: Write a Java program that does the following jobs. Step1. Creates a
ID: 3592217 • Letter: J
Question
Java please:
Write a Java program that does the following jobs.
Step1. Creates a Car table with car manufacturers, models, model years, and fuel efficiency ratings.
Step2. Reads data from a text file and insert the cars to the table created in Step 1.
Step3. Interact with the user, where the user can select one of the following actions.
- (Q) Quit: quit the program
- (A) Add a car: insert a car to the table
- (C) Calculate avg: calculate the average
- (W) Write the entire table to a text file
- (P) Print the entire table
- (M) Print a subset of the rows based on efficiency
The user can choose one of these actions with typing Q,A,C, W, P, or M in the console. When adding a car, the user must provide manufacturer, model, year, and mpg through the console.
When writing the table to a text file, the user must provide output text file name. When selecting a subset of the rows based on efficiency an upper bound value must be provided.
Four files are provided with the assignment. **THESE ARE POSTED BELOW**
1. CarDB.java: the main class of this assignment.
2. Database.properties: file for Apache Derby
3. SimpleDataSource.java: file for Apache Derby
4. Carmpg.txt: sample text file for Step 2.
Provide one source file (CarDB.java). In other words, Database.properties, SimpleDataSource.java, or Carmpg.txt are not submitted. In modifying the source file,
1. Do not change the file (class) names. Points will be deducted if you have different names.
2. Fill in your name in the @author section of the comment in each of the files. If you do not, points will be deducted.
Make sure to submit source file (*.java). Class file (*.class) will not be graded and receive zero credit.
**(CarDB)
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.IOException;
/**
* Code for HW5
* @author
*/
/**
Creates the Car table, insert some data into the table,
and drop the table from a database.
*/
//ARGS database.properties
public class CarDB
{
public static void main(String[] args) throws IOException, SQLException,
ClassNotFoundException
{
if (args.length == 0)
{
System.out.println("Usage: java CarDB propertiesFile");
System.exit(0);
}
SimpleDataSource.init(args[0]);
...
}
}
**SimpleDataSource.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
A simple data source for getting database connections.
*/
public class SimpleDataSource
{
private static String url;
private static String username;
private static String password;
/**
Initializes the data source.
@param fileName the name of the property file that
contains the database driver, URL, username, and password
*/
public static void init(String fileName) throws IOException,
ClassNotFoundException
{
//complete this method
}
/**
Gets a connection to the database.
@return the database connection
*/
public static Connection getConnection() throws SQLException
{
//complete this method
}
}
**database.properties
jdbc.url=jdbc:derby:BigJavaDB;create=true
# With other databases, you may need to add entries such as these
# jdbc.username=admin
# jdbc.password=secret
# jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver
**carmpg.txt
2017 Toyota Prius 52
2017 Kia Optima 31
2017 Hyundai Sonata 31
2017 Nissan Altima 31
2017 Chevrolet Malibu 30
2017 Honda Accord 30
2017 Mazda 6 29
2017 Subaru Legacy 29
2017 Toyota Camry 27
2017 Chrysler 200 27
2017 Ford Fusion 27
2017 Volkswagen Passat 27
2017 Volkswagen CC 25
2017 Chevrolet Impala 25
2017 Buick LaCrosse 25
2017 Nissan Maxima 25
2017 Buick Regal 24
Explanation / Answer
Car.java
package carTest;
import java.util.Scanner;
public class Car {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String id;
CarDB car=new CarDB();
//prints the data to be selected
System.out.print("Please select any of the following option:");
System.out.println("(Q) Quit: quit the program");
System.out.println("(A) Add a car: insert a car to the table");
System.out.println("(C) Calculate avg: calculate the average");
System.out.println("(W) Write the entire table to a text file");
System.out.println("(P) Print the entire table");
System.out.println("(M) Print a subset of the rows based on efficiency");
//reads the entered data
id = scanner.nextLine();
if(id.equalsIgnoreCase("q")){
System.exit(0);
}else if(id.equalsIgnoreCase("a")){
System.out.println("Enter Manufacturer:");
String manufacturer=scanner.nextLine();
System.out.println("Enter Model:");
String model =scanner.nextLine();
System.out.println("Enter Manufacture year:");
int year=Integer.parseInt(scanner.nextLine());
System.out.println("Enter car efficiency:");
int mpg=Integer.parseInt(scanner.nextLine());
car.addCar(manufacturer, model, year, mpg);
System.out.println("Car details Added");
}else if(id.equalsIgnoreCase("c")){
car.getAvgEfficiency();
}else if(id.equalsIgnoreCase("w")){
System.out.println("Enter file Name");
String fileName=scanner.nextLine();
car.SaveToText(fileName);
}else if(id.equalsIgnoreCase("p")){
car.printTable();
}else if(id.equalsIgnoreCase("m")){
System.out.println("Enter the efficiency");
int mpg=Integer.parseInt(scanner.nextLine());
car.getCarsEfficiency(mpg);
}else{
System.out.println("Value Entered is invalid");
}
scanner.close();
}
}
CarDB.java
package carTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.Scanner;
public class CarDB {
private static Properties props = new Properties();
private static FileInputStream file;
private static ResultSet rs = null;
private static Connection conn = null;
private static Statement stmt = null;
private static PreparedStatement psInsert = null;
public CarDB() {
createConnection();
loadTextFile();
}
public void loadTextFile() {
File inputFile = new File("D:\workspace\Test\src\carTest\carmpg.txt");
Scanner inputStream;
String line;
try {
inputStream = new Scanner(inputFile);
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
String[] values = line.split(" ");
addCar(values[1], values[2], Integer.parseInt(values[0].trim()), Integer.parseInt(values[3].trim()));
}
inputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void SaveToText(String fileName) {
try {
rs = stmt.executeQuery("select * from car");
FileWriter writer = new FileWriter(fileName, false);
while (rs.next()) {
writer.append(
" " + rs.getString(1) + " " + rs.getString(2) + " " + rs.getInt(3) + " " + rs.getInt(4) + " ");
}
writer.flush();
writer.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void printTable() {
try {
rs = stmt.executeQuery("select * from car");
System.out.println("Manufacturer Model Year Efficiency");
while (rs.next()) {
System.out.println(" " + rs.getString(1) + " " + rs.getString(2) + " " + rs.getInt(3) + " "
+ rs.getInt(4) + " ");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// Adds Car details
public void addCar(String manufacturer, String model, int mfg_year, int mpg) {
try {
psInsert = conn.prepareStatement("insert into car(manufacturer,model,mfg_Year,mpg) values (?,?,?,?)");
psInsert.setString(1, manufacturer);
psInsert.setString(2, model);
psInsert.setInt(3, mfg_year);
psInsert.setInt(4, mpg);
psInsert.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
// gets all the car details with given efficiency
public void getCarsEfficiency(int efficiency) {
try {
rs = stmt.executeQuery("select * from car where mpg =" + efficiency);
System.out.println("Cars with Efficiency..." + efficiency);
while (rs.next()) {
System.out.println(" " + rs.getString(1) + " " + rs.getString(2) + " " + rs.getInt(3) + " "
+ rs.getInt(4) + " ");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void getAvgEfficiency() {
try {
rs = stmt.executeQuery("select AVG(mpg) from car");
System.out.println("Cars with Efficiency...");
while (rs.next()) {
System.out.println("Average Efficiency " + rs.getString(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void createConnection() {
try {
file = new FileInputStream("src\database.properties");
props.load(file);
file.close();
String driver = props.getProperty("jdbc.driver");
if (driver != null) {
Class.forName(driver);
}
String url = props.getProperty("jdbc.url");
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
// use this for creating table if not created.
String createString1 = "drop TABLE car";
stmt.executeUpdate(createString1);
String createString = "CREATE TABLE CAR (Manufacturer varchar(100), Model varchar(100), mfg_Year int, mpg int)";
stmt.executeUpdate(createString);
// split the words
} catch (Exception except) {
except.printStackTrace();
}
}
}
database.properties
jdbc.url=jdbc:derby:Lab11DB;create=true
jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver
Sample Output:
Please select any of the following option:(Q) Quit: quit the program
(A) Add a car: insert a car to the table
(C) Calculate avg: calculate the average
W) Write the entire table to a text file
(P) Print the entire table
(M) Print a subset of the rows based on efficiency
w
Enter file Name
test.txt
test.txt
Toyota Prius 2017 52
Kia Optima 2017 31
Hyundai Sonata 2017 31
Nissan Altima 2017 31
Chevrolet Malibu 2017 30
Honda Accord 2017 30
Mazda 6 2017 29
Subaru Legacy 2017 29
Toyota Camry 2017 27
Chrysler 200 2017 27
Ford Fusion 2017 27
Volkswagen Passat 2017 27
Volkswagen CC 2017 25
Chevrolet Impala 2017 25
Buick LaCrosse 2017 25
Nissan Maxima 2017 25
Buick Regal 2017 24
Please select any of the following option:(Q) Quit: quit the program
(A) Add a car: insert a car to the table
(C) Calculate avg: calculate the average
W) Write the entire table to a text file
(P) Print the entire table
(M) Print a subset of the rows based on efficiency
p
Manufacturer Model Year Efficiency
Toyota Prius 2017 52
Kia Optima 2017 31
Hyundai Sonata 2017 31
Nissan Altima 2017 31
Chevrolet Malibu 2017 30
Honda Accord 2017 30
Mazda 6 2017 29
Subaru Legacy 2017 29
Toyota Camry 2017 27
Chrysler 200 2017 27
Ford Fusion 2017 27
Volkswagen Passat 2017 27
Volkswagen CC 2017 25
Chevrolet Impala 2017 25
Buick LaCrosse 2017 25
Nissan Maxima 2017 25
Buick Regal 2017 24
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.