In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
What this article shares with you is about how java implements vending machines. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it.
Request:
Simple vending machine
Process:
[coin]-> [Show goods list]-> [Select an item number to purchase]-> [prompt for shipment]-> [change]
Functional requirements:
1. Use the mysql database to store all goods in the database (goods should have at least basic information such as number, name, quantity, price, etc., and other attributes can be added to improve the program).
two。 To have friendly customer prompts, for example: please enter the number of the purchase item.
3. The list is required to include the remaining quantity of each commodity.
4. After shipping, you can choose [change] or [continue to buy] instead of making change directly.
The following are the ideas and answers to the problem (skip the operation of creating tables in the database):
1. The first step is to add the JDBC link package to the path. This step has been mentioned in previous blogs and will be skipped here. Then open the drive in the code:
Import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class DBUtil {/ / define the JDBC package import path private String dbDriver = "com.mysql.jdbc.Driver"; / / connect to the database to operate private String url = "jdbc:mysql://localhost:3306/database"; / / Database user name private String user = "root" / / Database password private String password = "123456"; / * * Open the JDBC drive * if the opening is not successful, throw an exception * @ return * @ throws Exception * / public Connection getDBConn () throws Exception {try {Class.forName (dbDriver); return DriverManager.getConnection (url, user, password) } catch (ClassNotFoundException e) {throw new ClassNotFoundException ("Database driver does not exist!") ;} catch (SQLException e) {throw new SQLException ("database connection exception!") ;}} / * close Connection, * throw an exception if the shutdown is not successful * / public void close (Connection conn) {try {if (conn! = null) {conn.close () }} catch (SQLException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}} / * close Statement, * throw an exception if the shutdown is unsuccessful * / public void close (Statement stat) {try {if (stat! = null) {stat.close () }} catch (SQLException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}} / * close ResultSet, * throw an exception if the shutdown is unsuccessful * / public void close (ResultSet rs) {try {if (rs! = null) {rs.close () Catch (SQLException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}
2. After operating JDBC, create a new class to define the properties and methods of the vending machine:
Import java.sql.Connection;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.Scanner;public class SimpleVendingMachine {/ / instantiate the JDBC connection and input method DBUtil dbu = new DBUtil (); Scanner scanner = new Scanner (System.in); / / define Connection,Statement and ResultSet Connection conn = null; Statement stat = null; ResultSet rs = null / / define invested gold coins and balance private double money; private static double balance = 0; / / invested money public void slot (double money) {this.money = money;} / / display information about the current commodity public void displayAllGoods () {/ / result set encapsulation ArrayList rsList = new ArrayList (); String [] strTemp = null / / sql display operation String sql = "SELECT `Code`, `Name`, Number, Price FROM goods"; try {/ / Drive load conn = dbu.getDBConn (); stat = conn.createStatement (); rs = stat.executeQuery (sql); ResultSetMetaData rsmd = rs.getMetaData (); int columnCount = rsmd.getColumnCount () String [] columnNames = new String [columnCount]; for (int I = 0; I
< columnNames.length ; i++){ columnNames[i] = rsmd.getColumnName(i + 1); } rsList.add(columnNames); //遍历赋值 while(rs.next()){ strTemp = new String[columnCount]; for(int i = 0 ; i < columnNames.length ; i ++){ strTemp[i] = rs.getString(columnNames[i]); } rsList.add(strTemp); } //遍历输出 for(String[] datas : rsList){ for(String data : datas){ System.out.print(data + "\t"); } System.out.println(); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //关闭连接 dbu.close(rs); dbu.close(stat); dbu.close(conn); } } //进行购买 public void buyByCode(){ System.out.println("请输入您想购买的商品编号:"); int code = scanner.nextInt(); //如果购买成功,则商品数量减一,该商品销售所得金额增加自身价格 String sql = "update Goods set Number = Number - 1, Gain = Gain + Price where Code = " + code; try { //驱动器加载 conn = dbu.getDBConn(); //手动提交 //conn.setAutoCommit(false); stat = conn.createStatement(); //操作影响行数 int affectedRows = stat.executeUpdate(sql); //检查余额是否足够 if(checkMoney(code, stat, this.money)){ if(affectedRows >0) {System.out.println ("purchase succeeded!") ; / / manually submit / / conn.commit () if the operation is successful; / / follow-up actions: change or continue to purchase this.proceed ();}} else {System.out.println ("insufficient amount!") ; / / return to the location where the drive was loaded / / conn.rollback ();}} catch (ClassNotFoundException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} catch (SQLException e) {/ / TODO Auto-generated catch block e.printStackTrace () } catch (Exception e) {/ / TODO Auto-generated catch block e.printStackTrace ();} finally {dbu.close (rs); dbu.close (stat); dbu.close (conn) }} / / check whether the input amount is sufficient to purchase goods public boolean checkMoney (int code, Statement stat, double money) {ResultSet rs = null; try {rs = stat.executeQuery ("select Price from goods where Code =" + code) While (rs.next ()) {/ / A change to the balance SimpleVendingMachine.balance = money-rs.getDouble ("Price"); if (SimpleVendingMachine.balance > = 0) {return true;} else {return false } catch (SQLException e) {e.printStackTrace ();} return false;} / / define the subsequent operation public void proceed () {System.out.println ("Please choose change (0) or continue to purchase (1):"); int n = scanner.nextInt () Switch (n) {case 0: System.out.println ("remaining change:" + SimpleVendingMachine.balance + "returned!") ; break; case 1: this.money = SimpleVendingMachine.balance; buyByCode (); break;}
3. Then define the vending machine service menu to allow users to coin, purchase and follow-up operations:
Import java.util.Scanner;public class SVMService {SimpleVendingMachine svm = new SimpleVendingMachine (); Scanner scanner = new Scanner (System.in); public void service () {/ / display all goods svm.displayAllGoods (); System.out.println ("- -") / / input amount ready to purchase goods System.out.println ("Please enter the amount you want to invest:"); svm.slot (scanner.nextDouble ()); svm.buyByCode ();}}
4. Finally, the SVMService is instantiated and called in the main method:
What are the advantages of public class Demo {public static void main (String [] args) {SVMService svms = new SVMService (); svms.service ();}} Java. Simple, as long as understand the basic concepts, you can write applications suitable for a variety of situations; 2. Object oriented; 3. Distributed, Java is a network-oriented language; 4. Robust, java provides automatic garbage collection for memory management to prevent programmers from making mistakes when managing memory. ; 5. Security, Java used in the network and distributed environment must prevent the invasion of viruses. 6. Architecturally neutral, as long as the Java runtime system is installed, it can run on any processor. 7. Portability, Java can be easily ported to different machines on the network. 8. Interpretation execution, Java interpreter directly interprets and executes Java bytecode.
This is how java realizes the vending machine. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.