Enum implements the vending machine

Source: Internet
Author: User
Tags soap string splitter

Start by recommending Google's code style

: Https://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.8.4.3-switch-default

Enum vending machine 1. Define the input commands accepted by the vending machine:
Package Com.enumtest.enumstatemac;import Java.util.arrays;import Java.util.Random; Public enumInput {nickel (5), DIME (Ten), QUARTER ( -), DOLLAR ( -), Toothpaste ( $), CHIPS ( the), SODA ( -), SOAP ( -), Abort_transaction { Public int amout() {Throw NewRuntimeException ("Abort.amout ()"); }}, STOP {//Last instance         Public int amout() {Throw NewRuntimeException ("Shut.amout ()"); }    };//Commodity price    int value; Input (int value) { This.value=value; } Input () {}intAmount () {return value; }StaticRandom Rand =NewRandom ( -); Public StaticInputrandomselection() {//Dont include STOP:        returnVALUES () [Rand.nextint (values (). Length-1)]; } Public Static void Main(string[] args) {    }}
2. Vending Machine class
Package Com.enumtest.enumstatemac;importStaticNet.mindview.util.print.*;import Java.util.enummap;import Java.util.iterator;import Java.util.logging.Logger; Import Net.mindview.util.textfile;import com.java.array.generator.Generator;enumCategory {//define Category enum instanceMoney (Input.nickel, Input.dime, Input.quarter, Input.dollar), Item_selection (Input.toothpaste, Input.CHIPS, Input.soda, Input.soap), Quit_transaction (input.abort_transaction), Shut_down (input.stop);//Initialize Input instance    PrivateInput[] values;    Category (Input ... types) {values = types; }Private StaticEnummap<input, category> categories =NewEnummap<input, category> (Input.class);//Fill categories < input, according to the corresponding menu of input >    Static{ for(Category c:category.class.getenumconstants ()) for(Input type:c.values) categories.put (type, c); }//Get the appropriate category menu according to the input     Public StaticCategory categorize (input input) {returnCategories.get (input); }} Public  class vendingmachine {    //default machine state is resting    Private Staticstate state = state.resting;//default machine amount =0 coin amount    Private Static intAmount =0;Private StaticInput selection =NULL;enumstateduration {TRANSIENT}//Tagging enum    The Status enumeration instance of the machine is as follows:    //Standby Status Coin status shipment status Change status interrupt operation status    enumState {//Different reactions according to the input content        //Standby status will be performed:RESTING {voidNext (Input input) {Try{System.out.println ("Now state:"+ State +"Resting:input:"+ input); Thread.Sleep (10000L); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); }Switch(Category.categorize (input)) {//If the input is an amount of 1. Coin amount Setting 2. Machine status set to coin                 CaseMoney:amount + = Input.amount (); state = Adding_money; Break;// break to where                //If the shutdown                 CaseShut_down:state = TERMINAL;//Why???                default:                }            }        },//If the machine is in coin state will be executed:Adding_money {voidNext (Input input) {Try{System.out.println ("Now state:"+ State +"Adding_money:input:"+ input); Thread.Sleep ( theL); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); }Switch(Category.categorize (input)) {//Continue coin Operation                 CaseMoney:amount + = Input.amount (); Break;//Select item Operation                 CaseItem_selection:selection = input;//Insufficient amount                    if(Amount < Selection.amount ()) Print ("Insufficient money for"+ selection);Else                        //Shipping statusstate = dispensing; Break;//Cancel Operation                 CaseQuit_transaction:// changestate = Giving_change; Break;//Off                 CaseShut_down:state = TERMINAL;default:                }            }        },//ShippingDispensing (stateduration.transient) {voidNext () {Try{System.out.println ("Now state:"+ State +"Dispensing:input:"); Thread.Sleep ( theL); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); }//shipping, charge, set to change statusPrint"Here's your"+ selection);                Amount-= Selection.amount ();            state = Giving_change; }}, Giving_change (stateduration.transient) {voidNext () {Try{System.out.println ("Now state:"+ State +"Giving_change:input:"); Thread.Sleep ( theL); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); }//Change to standby                if(Amount >0) {print ("Your Change:"+ amount); Amount =0;            } state = RESTING; }}, TERMINAL {voidOutput () {print ("halted"); }        };Private BooleanIstransient =false; State () {} state (Stateduration trans) {istransient =true; }//Operation status: Standby state coin Status This method must be overridden        voidNext (Input input) {Throw NewRuntimeException (" only Call"+"Next (input input) for non-transient states"); }//In machine non-automatic operation state: Shipment Status Change Status This method must be overridden        voidNext () {Throw NewRuntimeException ("Only call Next () for"+"stateduration.transient states"); }voidOutput () {print ("Over amount:"+ amount); }    }//vending machine static method    Static voidRun (generator<input> gen) { while(state = state.terminal) {Input inputtemp = Gen.next ();if(NULL= = Inputtemp/ * Restrict return to an operation in input * /) {return; } state.next (Inputtemp/ * Restrict return to an operation in input * /);//Returns the input Operation                                                          //corresponding            //If the previous operation is a standby status, that is, there will be an action = next operation (call next (para), transient            //set to True).              while(state.istransient)//state.istransient representative has next actionState.next ();        State.output (); }    } Public Static voidMain (string[] args) {//Get an InputGenerator<input> Gen =NewRandominputgenerator ();if(Args.length = =1)//Input operation command to complete command initializationGen =NewFileinputgenerator (args[0]);    Run (gen); }}//For a basic sanity check: class randominputgenerator implements Generator<Input > {     PublicInput Next () {returnInput.randomselection (); }}//Create Inputs from a file of '; ' -separated Strings: class fileinputgenerator implements Generator<Input> {    Privateiterator<string> input; PublicFileinputgenerator (String fileName) {input =NewTextfile (FileName,";"). iterator (); }//Restrict return to an operation in input     PublicInput Next () {if(!input.hasnext ())return NULL; String Inputnext = Input.next (). Trim ();if(Inputnext = =NULL||"". Equals (Inputnext)) {System.out.println ("The order is illegal.");returnInput.abort_transaction;        } Input inputgenerated = enum.valueof (Input.class, Inputnext); System.out.println (inputgenerated);returninputgenerated; }}
3. Other helper classes and related interfaces:
package com.java.array.generator;publicinterface Generator<T> {    T next();}
//: Net/mindview/util/textfile.javaPackage Net.mindview.util;import Java.io.*;import java.util.*; Public classTextfile extends Arraylist<string> {//Read a file as a single string:   Public StaticStringRead(String fileName) {StringBuilder SB =NewStringBuilder ();Try{BufferedReaderinch=NewBufferedReader (NewFileReader (NewFile (FileName). Getabsolutefile ());Try{String s; while(s =inch. ReadLine ())! =NULL) {sb.append (s); Sb.append ("\ n"); }      }finally{inch. Close (); }    }Catch(IOException e) {Throw NewRuntimeException (e); }returnSb.tostring (); }//Read a file, split by any regular expression:   Public textfile(String fileName, String splitter) {Super (Arrays.aslist (read (fileName) split (splitter)));//Regular expression split () often leaves an empty    //String at the first position:    if(Get(0). Equals ("") Remove (0); }//normally read by lines:   Public textfile(String fileName) { This(FileName,"\ n"); }  }

Enum implements the vending machine

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.