3

I'm new in object-oriented programming and I use Java. I'm stil finding it hard to manipulate through the classes using generics and stuff. As a practice, I looked for codes in the internet and my colleague suggested me a program that came from this site.

This is the first class:

import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;





public class quine extends JFrame implements ActionListener, WindowListener{
        /**
     * 
     */
    private static final long serialVersionUID = 1L;
        static ArrayList<Term>[][] table=new ArrayList[5][5];                   // SERVES AS OUR STORAGE FOR ARRANGING TERMS AND TO OUR RESULTING TERMS THAT ARE BEING COMPARED.
        static Vector<String> inputTerm= new Vector <String>();                 // STORES OUR ORIGINAL INPUT/NUMBERS
        static Vector<String> resultingTerms= new Vector <String>();            // STORES RESULTING TERMS FOR EACH SET OF COMPARISON
        static int var=0;                                                       //NUMBER OF VARIABLE
        static int numbers=0;                                                   //NUMBER OF INPUTS
        final static int maxTerms=1000;                                         //MAXIMUM NUMBER OF TERMS WITH SAME NUMBER OF 1'S
        static TextField result = new TextField("  ",50);
        static TextField text;
        static TextField text1;
        static quine  qWindow;
        static String finalT = "";

        public static void main(String[] args){
            qWindow = new quine("Quine-McCluskey Simulator");                   //creates a window
            qWindow.setSize(400,250);                                           //sets the size of the window
            qWindow.setVisible(true);                                           //makes the window visible
            qWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );            //CLOSES THE WINDOW WHEN CLOSING OR CLICKING THE X BUTTON


            JOptionPane.showMessageDialog(null, "Welcome to my Quine-McCluskey Simulator!"); //DISPLAYS MESSAGE
        }//end main

        public static int count_one(String temp){   //COUNT 1'S FROM EACH TERM

            int count=0;
            char[] tempArray=temp.toCharArray();
            int i=0;
            while(i<temp.length()){
                if(tempArray[i]=='1'){
                    count++;
                }
                i++;
            }//end while
            return count;
        }//end one

        public static void getPrimeImplicants(){                // PAIRS TERMS UNTIL NOTHING TO PAIR, END TERMS ARE OUR PRIME IMPLICANTS
            table=createTermTable(inputTerm);
            printTermTable();
            createPairing();

        }

        public static ArrayList<Term>[][] createTermTable(Vector <String> input){   // CREATE TABLE, ARRANGES TERMS BASED ON THE NUMBER OF 1'S IN 
                                                                                   //EACH TERM USING count_one,therefore, row 1 contains terms with 1 1 bit.
            Term temp;
            int one=0;
            int element=0;
            ArrayList[][] arrayLists = new ArrayList[var+1][maxTerms+1];            //CREATES AN ARRAY WITH VAR ROWS CORRESPONDING TO POSSIBLE NUMBER OF
                                                                                    // 1 FOR EACH TERM AND 1000 COLUMNS
            ArrayList<Term> [][]tempTable = arrayLists;
            for(int x=0;x<=var;x++){                                                //?
                for(int y=0;y<=maxTerms;y++){
                    tempTable[x][y]= new ArrayList<Term>();
                }//end y
            }//end for x

            for(int i=0;i<input.size();i++){
                one=count_one(input.get(i));                             //COUNT 1'S FROM EACH TERM
                temp=initTerm(input.get(i),false);                     // INITIALIZE PROPERTIES OF THAT TERM

                while(!tempTable[one][element].isEmpty()){
                    element++;
                }//end while

                tempTable[one][element].add(temp);
                element=0;
            }   //end for

            return tempTable;
        }//end createTermTable

        public static Term initTerm(String n,boolean u){                    //INITIALIZE USED and NUM PROPERTY OF THE TERM
            Term term=new Term();
            term.used=u;                                                    // TO INDICATE IF THE TERM IS ALREADY PAIRED
            term.num=n;                                                     // THE TERM ITSELF
            return term;
        }//end initTerm

        public static void printTermTable(){                                // PRINTS THE COMPUTATION/TABLES
            System.out.println("\nCOMPUTING:");
            for(int i=0;i<var+1;i++){
                System.out.print(i);
                System.out.println("    --------------------------------------------");
                for(int j=0;!table[i][j].isEmpty();j++){                    //PRINTS TERM ON EACH ROW WHILE TERM IS NOT EMPTY
                    System.out.println(table[i][j].get(0).num);
                }//end for j
            }//end for i

        }

        public static void createPairing(){                             //PAIRS A TERM TO EACH TERM ON THE NEXT ROW
            int finalterms=0;
            String term_num="";
            int found=0;
            Vector<String> preResult= new Vector<String>();
            for(int x=0;x<=var-1;x++){                                  // REPEATS PAIRING OF A TERMS OF THE TABLE VAR TIMES TO MAKE SURE WHAT ARE LEFT ARE PRIME IMPLICANTS
                preResult=new Vector<String>();                         // STORES THE RESULTING TERMS FOR EACH SET OF PAIRING
                for(int i=0;i<=var;i++){                            //COMPARES A ROW WITH EACH TERMS ON THE NEXT ROW
                    //Vector <String> rowResult= new Vector<String>();  //STORES RESULTING TERMS ON THAT PARTICULAR TERM OF THE ROW. THIS IS TO AVOID REPETITIONS
                    for(int j=0;!table[i][j].isEmpty();j++){            // TERM ON THE  ROW BEING COMPARED WITH EACH TERM ON NEXT ROW
                        if(i+1!=var+1)                                  // MAKES SURE THAT THE PROCESS NOT EXCEEDS THE ARRAYBOUND
                        for(int k=0;!table[i+1][k].isEmpty();k++){      //TERM ON THE NEXT ROW THAT IS BEING COMPARED WITH TERM ON THE CURRENT ROW.
                            term_num=pair(table[i][j].get(0).num,table[i+1][k].get(0).num); //ASSIGNS RESULT OF PAIRING TO term_num

                            if(term_num!=null){                         // IF PAIRING IS SUCCESSFUL
                                table[i+1][k].get(0).used=true;         // TERM IS PAIRED/USED
                                /*if(!rowResult.contains(term_num)){    //MAKES SURE THAT TERM IS NOT REPEATE
                                    rowResult.add(term_num);
                                    found=1;
                                }
                                */
                                if(!preResult.contains(term_num)){          // MAKES SURE THAT TERM IS NOT REPEATED
                                    preResult.add(term_num);
                                    found=1;
                                    finalterms++;                           // COUNTS THE FINAL/RESULTING TERMS FOR THIS SET OF PAIRING
                                }//end if !resultingTerms
                                found=1;
                            }//end if term_num!=null
                        }//end for k
                        if(found==0){                                       // IF TERM IS NOT SUCCESSFULLY PAIRED/USED, ADD TO THE RESULTING TERMS FOR THIS SET
                            if(table[i][j].get(0).used!=true){     
                                preResult.add(table[i][j].get(0).num);
                            }
                        }
                        found=0;
                    }//end for j

                }//end for i
                table=createTermTable(preResult);                               // CREATE ANOTHER TABLE FOR NEXT SET. THE NEW TABLE CONTAINS THE RESULTING TERMS OF THIS SET
                if(preResult.size()!=0)
                    resultingTerms=preResult;                                 //IF THE ARE RESULTING TERMS, THEN PRINT AND ASSIGN TO resultingterms. THE END VALUE OF resultingterms WILL BE SIMPLIFIED
                printTermTable();
            }//end for x

        }//end createPairing

        public static String pair(String a,String b){
            int difference=-1;
            char []array1 = new char[a.length()];                           
            char []array2;
            for(int i=0;i<var;i++){
                array1=a.toCharArray();                                     //CONVERTS TERMS OF TYPE STRING TO TERMS OF TYPE CHAR
                array2=b.toCharArray();
                if(array1[i]!=array2[i]){                                  // IF NOT EQUAL FOR A PARTICULAR CHARACTER FOR THE FIRST TIME, THEN GET THE INDEX CORRESPONDING TO THAT CHARACTER.
                    if(difference==-1)
                        difference=i;
                    else                                                     //IF NOT NOT EQUAL FOR THE FIRST TIME, THEN THE TERMS DIFFER IN MORE THAN 1 PLACE
                        return null;
                }//end if
            }//end for


            if(difference==-1)                                             //THE TERMS ARE INDENTICAL, RETURN NULL, PAIRING UNSUCCESSFUL
                return null;

            char[] result= a.toCharArray();                                //CHARACTER CORRESPONDING TO THE INDEX WHERE TERMS DIFFER ONLY ONCE WILL BE CHANGED TO '-' 
            result[difference]='-';
            String resulTerm= new String(result);
            return resulTerm;                                              //RETURNS THE MODIFIED TERM, PAIRING SUCCESSFUL
        }//end pair

        public static void simplifymore(){                                 //SIMPLIFY THE RESULTINGTERMS
            int primes=resultingTerms.size();                           // RESULTING TERMS CORRESPOND TO OUR PRIME IMPLICANTS
            int[][] s_table= new int[primes][numbers];                   //CREATES A TABLE WITH ROWS EQUAL TO NUMBER OF PRIME IMPLICANTS AND COLUMNS EQUAL TO THE NUMBER OF THE ORIGINAL INPUT
            for(int i=0;i<primes;i++){
                for(int j=0;j<numbers;j++){
                    s_table[i][j]=implies(resultingTerms.get(i),inputTerm.get(j));  
                }//end for j
            }//end for i

            Vector <String> finalTerms= new Vector<String>();               // STORES THE FINALTERMS
            int finished=0;
            int index=0;
            while(finished==0){                                             //UNTIL ALL ELEMENTS ARE NOW TURNED TO 0
                index=essentialImplicant(s_table);
                if(index!=-1)
                    finalTerms.add(resultingTerms.get(index));              // IF RESULTING TERM IS THE ONLY ONE IMPLYING THE CURRENT ORIGINAL TERM, THEN ADD TO FINAL TERMS
                else{                                                       // THOSE THAT HAVE MORE THAN ONE IMPLICATION FOR A PARTICULAR ORIGINAL TERM
                    index=largestImplicant(s_table);
                    if(index!=-1)
                        finalTerms.add(resultingTerms.get(index));          //ADD TO FINAL TERMS IF LARGEST IMPLICANT(ONE WHICH HAS MORE NUMBER OF 1'S. SEE COMMENTS ON largestImplicant.
                    else
                        finished=1;                                         //IF INDEX IS -1 THEN ALL ELEMENTS HAVE ALREADY BEEN DELETED OR HAVE MADE VALUE 0
                }//end else
            }//end while finished
            System.out.println("Final Terms :");
            for(int x=0;x<finalTerms.size();x++)                            //PRINTS THE FINAL TERMS IN BINARY FORMAT
                System.out.println(finalTerms.get(x));

            printSimplified(finalTerms);
        }//end simplifymore

        public static void printSimplified(Vector <String> finalTerms){
            String temp="";
            char[] tempArray;
            char variables[]= {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};   //basis for our variables to printed
            int index=0;
            int i=0;
            int j=0;
            System.out.print("F = ");
            while(i<finalTerms.size()){                                 //until all final terms are printed in algebraic form.

                temp=finalTerms.get(i);                                 //assigns current final term to temp
                tempArray=temp.toCharArray();                           //CONVERTS TEMP TO ARRAY

                while(j<var){
                    if(tempArray[j]=='-'){                              //IGNORES -
                        index++;
                    }
                    else if (tempArray[j]=='0'){
                        finalT+=variables[26-var+index]+"'";  // PRINTS THE CORRESPONDING LETTER.IF CHARACTER IS 0 THEN APPEND ' AFTER THE VARIABLE

                        index++;
                    }
                    else if (tempArray[j]=='1'){
                        finalT+=variables[26-var+index];     // PRINTS CORRESPONDING LETTER
                        index++;
                    }
                    else{};
                    j++;
                }//end while

                if(i<finalTerms.size()-1)
                    finalT+=" + ";                          // APPENDS +
                i++;
                temp="";
                j=0;
                index=0;
            }//end while
            System.out.println(finalT);
        }//print simplified

        public static int essentialImplicant(int[][] s_table){              // CHECKS EACH RESULTING TERM IMPLYING A PARTICULAR ORIGINAL TERM
            for(int i=0;i<s_table[0].length;i++){ // 
                int lastImplFound=-1;
                for(int impl=0;impl<s_table.length;impl++){
                    if(s_table[impl][i]==1){                                //IF RESULTING TERM IMPLIES ORIGINAL TERM
                        if(lastImplFound==-1){                              
                            lastImplFound=impl;
                        }else{                                          // IF MORE THAN ONE IMPLICATION,THEN IT IS NOT AN ESSENTIAL PRIME IMPLICANT.GO TO NEXT ORIGINAL TERM
                            lastImplFound=-1;
                            break;
                        }//end else
                    }
                }
                if(lastImplFound!=-1){                              // ONE IMPLICATION FOR THE ORIGINAL TERM. THIS IS AN ESSENTIAL PRIME IMPLICANT
                    implicant(s_table,lastImplFound);
                    return lastImplFound;
                }
            }//end for impl
            return -1;
        }

        public static void implicant(int [][] s_table,int impA){   // DELETE OR MAKE VALUE 0 THE ROW WHERE THE ESSENTIAL PRIME IMPLICANT IS AND THE COLUMNS OF ALL THE ORIGINAL TERMS IMPLIED BY IT
            for(int i=0;i<s_table[0].length;i++){
                if(s_table[impA][i]==1)
                    for(int impB=0;impB<s_table.length;impB++){
                        s_table[impB][i]=0;
                    }
            }
        }//end implicant

        public static int largestImplicant(int[][] s_table){
            int maxImp=-1;
            int max=0;
            for(int imp=0;imp<s_table.length;imp++){            // LOCATES WHICH HAS MORE NUMBER OF 1'C IN EACH PRIME
                int num=0;
                for(int i=0;i<s_table[0].length;i++){
                    if(s_table[imp][i]==1)
                        num++;
                }//end for i
                if(num>max){                            // TERM WITH MORE 1'S AT THE END OF THE LOOP WILL BE ADDED TO THE FINAL TERMS
                    max=num;
                    maxImp=imp;
                }//end if num>max
            }//end for imp

            if(maxImp!=-1){                             // IF WE HAVE SUCCESSFULLY LOCATED A PRIME IMPLICANT
                implicant(s_table,maxImp);              // DELETE OR MAKE VALUE 0 THE ROW WHERE THE ESSENTIAL PRIME IMPLICANT IS AND THE COLUMNS OF ALL THE ORIGINAL TERMS IMPLIED BY IT
                return maxImp;
            }//end if maxImp!=-1
            return -1;
        }   

        public static int implies(String term1, String term2){    // RETURNS 1 IF RESULTING TERM IMPLIES THE ORIGINAL TERM, 0 OTHERWISE
            char[] term1Array=term1.toCharArray();
            char[] term2Array=term2.toCharArray();
                                                                //EX. ORG TERM IS 100100, RES TERM IS 1--10- ,RESULTING TERM IMPLIES THE ORIGINAL TERM. SINCE - HERE IS TREATED AS 0 OR 1
            for(int i=0;i<var;i++){
                if(term1Array[i]!=term2Array[i] && term1Array[i]!='-') 
                    return 0;
            }

            return 1;
        }

//end class

        public quine(String name){
            super(name);                                            //ASSIGNS LABEL OF THE WINDOW
            setLayout(new GridLayout(1, 1));                        //SETS THE LAYOUT       
            setLocation(350,200);                                   //SETS THE LOCATION OF THE WINDOW ON THE SCREEN
            GridBagLayout gridbag = new GridBagLayout();        //used to align buttons
            GridBagConstraints constraints = new GridBagConstraints();//to specify the size and position for the gridbaglayout
            setLayout(gridbag);
            constraints.weighty = 1;                                //distributes spaces among columns
            constraints.weightx = 1;                                //distributes spaces among rows
            constraints.gridwidth = GridBagConstraints.REMAINDER;   //to specify that the component be the last one in its column

            Label label1 = new Label("     How many variables does the function have?");        //CREATES A LABEL
            label1.setVisible(true);                                            //MAKES THE LABEL VISIBLE, ASSIGNS NEW FONT AND COLOR THEN ADD TO THE WINDOW
            label1.setFont(new Font("Sans Serif", Font.BOLD, 12));
            label1.setBackground(Color.CYAN);
            add(label1);

            text1= new TextField("",10);
            gridbag.setConstraints(text1,constraints);                              //applies constraints to text
            text1.setEditable(true);                                                //SO THAT WE COULD STILL HAVE AN UNLIMITED LENGTH OF INPUT
            text1.setForeground(Color.black);
            text1.setBackground(Color.white);
            text1.setVisible(true);
            text1.addActionListener(this);                                          //ACTIVATES ACTIONLISTENER FOR THIS FIELD
            add(text1);


            label1 = new Label(" Please list all the minterms that evaluates to 1:");//CREATES LABEL
            gridbag.setConstraints(label1,constraints);
            label1.setVisible(true);                                                //MAKES THE LABEL VISIBLE, ASSIGNS NEW FONT AND COLOR THEN ADD TO THE WINDOW
            label1.setBackground(Color.green);label1.setFont(new Font("Sans Serif", Font.BOLD, 12));
            label1.setBackground(Color.CYAN);
            add(label1);


            text = new TextField("Enter your numbers here separated by a comma",50);
            gridbag.setConstraints(text,constraints);               //applies constraints to text
            text.setEditable(true);                                 //ENABLES UNLIMITED LENGTH OF INPUT
            text.setForeground(Color.black);
            text.setBackground(Color.white);
            text.setVisible(true);
            text.addActionListener(this);                   //ACTIVATES ACTIONLISTENER FOR THIS FIELD
            text.setForeground(Color.blue);
            add(text);

            JButton enter = new JButton ("Enter");          // CREATES BUTTON NAMED Enter
            enter.setVisible(true);                         //MAKES IT VISIBLE, APPLIES THE CONSTRAINTS, AND ADD TO THE WINDOW
            add(enter);
            enter.setBackground(Color.green);
            enter.addActionListener(this);                  //ACTIVATES ACTIONLISTENER
            gridbag.setConstraints(enter,constraints);

            JButton reset = new JButton ("Reset");          // CREATES BUTTON NAMED Reset
            reset.setVisible(true);                         //MAKES IT VISIBLE, APPLIES THE CONSTRAINTS, AND ADD TO THE WINDOW
            gridbag.setConstraints(reset,constraints);
            reset.setBackground(Color.green);
            add(reset);
            reset.addActionListener(this);  

            label1 = new Label(" Result:");
            gridbag.setConstraints(label1,constraints);
            label1.setVisible(true);
            label1.setBackground(Color.cyan);
            label1.setFont(new Font("Sans Serif", Font.BOLD, 12));
            label1.setBackground(Color.CYAN);
            add(label1);


            result = new TextField(" ",50);
            gridbag.setConstraints(result,constraints);             //applies constraints to text
            result.setEditable(true);
            result.setForeground(Color.black);
            result.setBackground(Color.white);
            result.setVisible(true);
            add(result);



        }

        public void actionPerformed(ActionEvent e) {
            String stringInput="";
            String numOfVar="";
            String temp="";
            String temp1="";
            int num=0;


            if(e.getActionCommand() == "Enter"){                    // IF Enter BUTTON IS CLICKED
                stringInput = text.getText();                       // GETS STRING INPUT FROM TEXT(MINTERMS) 
                numOfVar = text1.getText();                         //GETS STRING INPUT FROM TEXT1(VARIABLES)
                var = Integer.parseInt(numOfVar);                   //CONVERTS numOfVar TO INTEGER
                StringTokenizer token= new StringTokenizer(stringInput," ,"); //TOKENIZE INPUT. ELIMINATE ALL COMMAS AND SPACES
                while(token.hasMoreTokens()){                           //WHILE THERE ARE MORE TOKENS
                    temp1=token.nextToken();                        //GETS TOKEN
                    numbers++;                                          //COUNTS THE NUMBER OF INPUTS
                    num=Integer.parseInt(temp1);                    //CONVERT INPUT TO INTEGER
                    temp=Integer.toBinaryString(num);               //CONVERTS INTEGER FORM OF INPUT TO BINARY IN ITS PROPER LENGTH BASED ON THE NUMBER OF VARIABLES GIVEN
                    if(temp.length()!=var){                     
                        while(temp.length()!=var){
                            temp="0"+temp;
                    }
                    }
                    inputTerm.add(temp);                            //ADDS RESULT(BINARY FORM) TO inputTerm

                }//end while
                getPrimeImplicants();                                   //GET PRIMEIMPLICANTS
                simplifymore();                                         // SIMPLIFY MORE    
                result.setText(finalT);                                 // DISPLAYS THE RESULT (SIMPLIFIED) TO RESULT TEXTFIELD

            }//end if

            if(e.getActionCommand()== "Reset"){                 //RESETS THE VALUES FOR NEXT SET OF INPUTS
                var=0;
                table=new ArrayList[5][5];                      // SERVES AS OUR STORAGE FOR ARRANGING TERMS AND TO OUR RESULTING TERMS THAT ARE BEING COMPARED.
                inputTerm= new Vector <String>();               // STORES OUR ORIGINAL INPUT/NUMBERS
                resultingTerms= new Vector <String>();          //STORES THE RESULTING TERMS FOR EACH COMPUTATION
                finalT="";                                      //STORES THE FINAL TERMS IN THEIR ALGEBRAIC FORM
                numbers=0;                                      //COUNTS THE NUMBER OF INPUTS FROM THE USER
                text.setText("");                               //ERASE THE TEXTS DISPLAYED ON THE TEXT FIELDS
                text1.setText("");
                result.setText("");
            }   
        }

        public void windowActivated(WindowEvent e) {}
        public void windowClosed(WindowEvent e) {qWindow.setVisible(false);}    //CLOSES THE WINDOW AFTER PROGRAMS STOPS RUNNING
        public void windowClosing(WindowEvent e) {}
        public void windowDeactivated(WindowEvent e) {}
        public void windowDeiconified(WindowEvent e) {}
        public void windowIconified(WindowEvent e) {}
        public void windowOpened(WindowEvent e) {}

}//end class



And this is the second class. Funny (it only consists of less than 10 lines unlike the first one)

public class Term {
        public String num;

        public boolean used;

}


Can you please help me incorporate these two classes into one (if that's possible)? I tried declaring String num and boolean used inside the first class and removed the Term but it shows lot of errors. I tried separating the initTerm method into two: one returns a string and the other boolean. But it adds error. What else can I do? Can you also advise me some techniques in doing this?

4

2 回答 2

2

You can put the whole class inside quine so that Term becomes an inner class of quine. The class Term is then visible to the code in quine and you don't need a separate file anymore for the class Term.

于 2012-08-21T08:45:40.863 回答
1

1) Don't declare variables as public unless they are static. It's standard practise to use getter/setter methods to access member variables.

2) Have you tried creating a super class that extends JFrame then get quine to extend that class. Add getter/setters in the super class. Then the sub class can access them via getVariable() etc etc.

3) Class names should start with an upper case letter. Variables, methods and package names should all be lower case.

于 2012-08-21T08:47:49.227 回答