Advertisement
Transformator

Untitled

Jan 11th, 2015
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.02 KB | None | 0 0
  1. import java.awt.Dimension;
  2. import java.awt.GridLayout;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.awt.event.WindowEvent;
  6. import java.awt.event.WindowListener;
  7. import java.io.BufferedInputStream;
  8. import java.io.BufferedWriter;
  9. import java.io.FileInputStream;
  10. import java.io.FileWriter;
  11. import java.io.File;
  12. import java.io.IOException;
  13. import java.io.InputStream;
  14. import java.util.ArrayList;
  15. import java.util.List;
  16. import java.util.Scanner;
  17.  
  18. import javax.swing.BoxLayout;
  19. import javax.swing.JButton;
  20. import javax.swing.JFrame;
  21. import javax.swing.JLabel;
  22. import javax.swing.JPanel;
  23.  
  24. /**
  25.  *
  26.  * @author Phantom6208
  27.  * @version 1.2
  28.  *
  29.  * This Program asks the user simple questions and saves it in a file.
  30.  *
  31.  * Than it trys to compare the results to the results in the file.
  32.  * If one of the results match, it says a welcome back
  33.  *
  34.  * in version 1.3: If one result is more than 80% same and the result with the most percent, it promts a window with 'Welcome back user...'
  35.  *
  36.  */
  37. public class Window extends JFrame implements ActionListener {
  38.     /**
  39.      * Yes button (in question window)
  40.      */
  41.     private JButton yes;
  42.     /**
  43.      * No button (in question window)
  44.      */
  45.     private JButton no;
  46.    
  47.     /**
  48.      * This label shows the actual question
  49.      */
  50.     private JLabel question;
  51.    
  52.     /**
  53.      * The panel witch get added to window
  54.      */
  55.     private JPanel panel;
  56.     /**
  57.      * Panel witch holds question.
  58.      * Get added to panel
  59.      */
  60.     private JPanel panel1;
  61.     /**
  62.      * Panel witch holds the yes and no button.
  63.      * Get added to panel
  64.      */
  65.     private JPanel panel2;
  66.    
  67.     /**
  68.      * Layout (GridLayout), get applied to panel
  69.      */
  70.     private GridLayout layout;
  71.    
  72.     /**
  73.      * Array of questions, in next version loaded by file
  74.      */
  75.     private String[] questions = {
  76.         "This is a test question, please press 'YES'.",
  77.         "This is a test question, please press 'NO'.",
  78.         "This is a test question, please press what you want to.",
  79.         "Did you ever travel to London?",
  80.         "Did you ever killed a person?",
  81.         "Did you ever broke a leg?",
  82.         "Do you have more than 10$ in your pocket?",
  83.         "Do you like this program?"
  84.     };
  85.    
  86.     /**
  87.      * Index of actual question
  88.      */
  89.     private int qNumber;
  90.    
  91.     /**
  92.      * Saves users answers as string.
  93.      * 1 = yes, 0 = no
  94.      */
  95.     private String tempID;
  96.    
  97.     /**
  98.      * Main function, creates window and nothing else.
  99.      * @param args
  100.      */
  101.     public static void main(String args[]) {
  102.         JFrame frame = new Window();
  103.     }
  104.    
  105.     /**
  106.      * Window Class, creates the question window.
  107.      */
  108.     public Window() {
  109.         System.out.println("[INFO] Starting program...");
  110.        
  111.         tempID = "";
  112.        
  113.         yes = new JButton("Yes");
  114.         no = new JButton("No");
  115.        
  116.         question = new JLabel("undefined");
  117.        
  118.         panel = new JPanel();
  119.         panel1 = new JPanel();
  120.         panel2 = new JPanel();
  121.        
  122.         layout = new GridLayout(2, 0);
  123.        
  124.         // ---
  125.         /**
  126.          * Adds ActionListener to buttons yes and no.
  127.          */
  128.         yes.addActionListener(this);
  129.         no.addActionListener(this);
  130.        
  131.         // ---
  132.        
  133.         /**
  134.          * Adds components to panels
  135.          */
  136.         panel1.add(question);
  137.        
  138.         panel2.add(yes);
  139.         panel2.add(no);
  140.        
  141.         panel.setLayout(layout);
  142.         panel.add(panel1);
  143.         panel.add(panel2);
  144.        
  145.         /**
  146.          * Adds panel to window
  147.          */
  148.         add(panel);
  149.        
  150.         // ---
  151.        
  152.         /**
  153.          * Sets question text; sets Question index to 1
  154.          */
  155.         question.setText(questions[0]);
  156.         qNumber = 1;
  157.        
  158.         // ---
  159.        
  160.         /**
  161.          * Set window Title
  162.          */
  163.         setTitle("Question Game");
  164.        
  165.         /**
  166.          * Set window location and its size
  167.          */
  168.         setLocation(100, 100);
  169.         setSize(new Dimension(500, 95));
  170.         /**
  171.          * Since now window is not resizeable (size by user editable)
  172.          */
  173.         setResizable(false);
  174.        
  175.         /**
  176.          * Makes window visible on screen.
  177.          */
  178.         setVisible(true);
  179.     }
  180.    
  181.     @Override
  182.     /**
  183.      * Catches Button-Events
  184.      */
  185.     public void actionPerformed(ActionEvent event) {
  186.         /**
  187.          * If button yes get pressed.
  188.          */
  189.         boolean action = false;
  190.         if(event.getSource() == yes) { action = true; }
  191.         if(event.getSource() == no) { action = false; }
  192.        
  193.         /**
  194.          * Saves user input in tempID
  195.          */
  196.         if(action) {
  197.             tempID += 1;
  198.             System.out.println("[INFO] User pressed 'YES' for question " + qNumber);
  199.         }
  200.         else {
  201.             tempID += 0;
  202.             System.out.println("[INFO] User pressed 'NO' for question " + qNumber);
  203.         }
  204.  
  205.         try {
  206.             /**
  207.              * try to set new question;
  208.              * count question index up
  209.              */
  210.             question.setText(questions[qNumber]);
  211.             qNumber++;
  212.         /**
  213.          * executed if index runs out of range (all questions answerd)
  214.          */
  215.         } catch(Exception e) {
  216.             if(questions.length == qNumber) {
  217.                 System.out.println("[INFO] User finished all questions.");
  218.             } else {
  219.                 /**
  220.                  * If its not the last question, throws error
  221.                  */
  222.                 System.out.println("[ERROR] Unknown error.");
  223.                 e.printStackTrace();
  224.             }
  225.                
  226.             try {
  227.                 /**
  228.                  * Creates scanner to search users file.
  229.                  */
  230.                 Scanner scanner=new Scanner(new File("users.csv"));
  231.                    
  232.                 boolean found = false;
  233.                    
  234.                 /**
  235.                  * List of matches
  236.                  */
  237.                 ArrayList<String[]> matches = new ArrayList();
  238.                    
  239.                 /**
  240.                  * While scanner doesn't reach the end
  241.                  */
  242.                 while(scanner.hasNextLine()) {
  243.                     String nextLine = scanner.nextLine();
  244.                     /**
  245.                      * If the user input matches 80% or more.
  246.                      */
  247.                     if(testSameUser(tempID, nextLine.split(";")[1]) >= 0.8){
  248.                         System.out.println("[INFO] User maybe identificated: user" + nextLine.split(";")[0]);
  249.                        
  250.                         found = true;
  251.                         /**
  252.                          * Saves userID
  253.                          */
  254.                         String[] tempList = new String[2];
  255.                         tempList[0] = nextLine.split(";")[0];
  256.                         tempList[1] = String.valueOf(testSameUser(tempID, nextLine.split(";")[1].toString()));
  257.                         matches.add(tempList);
  258.                     }
  259.                 }
  260.                    
  261.                 if(!found) {
  262.                     /**
  263.                      * Opens users.csv file for reading
  264.                      */
  265.                     BufferedWriter users = new BufferedWriter(new FileWriter("users.csv", true));
  266.                     /**
  267.                      * Writes information about new user (userid, answers)
  268.                      */
  269.                     users.write(countLines("users.csv")+1 + ";" + tempID + "\r\n");
  270.                     users.close();
  271.                 } else {
  272.                     String[][] matchesArray = new String[matches.size()][2];
  273.                    
  274.                     for(int i=0; i<matches.size(); i++) {
  275.                         matches.get(0);
  276.                     }
  277.                    
  278.                     double max = Double.parseDouble(matchesArray[0][1]);
  279.                     int maxindex = 0;
  280.  
  281.                     for ( int i = 1; i < matches.size(); i++) {
  282.                         if ( Double.parseDouble(matchesArray[i][1]) > max) {
  283.                             max = Double.parseDouble(matchesArray[i][1]);
  284.                             maxindex = i;
  285.                         }
  286.                     }
  287.                    
  288.                     System.out.println("[INFO] User possibly identificated: user" + matchesArray[maxindex][0]);
  289.                    
  290.                     new PromtWindow("I know who you are!", "I've identificated you, " + matchesArray[maxindex][0] + "!");
  291.                 }
  292.                    
  293.                 scanner.close();
  294.             } catch (Exception exc) {
  295.                 System.out.println("[ERROR] can't save answers");
  296.                 exc.printStackTrace();
  297.             }
  298.             System.out.println("[INFO] Exit program...");
  299.             dispose();
  300.         }
  301.     }
  302.    
  303.     /**
  304.      * Tests how many percent of user1 and user2 are the same.
  305.      * @param user1
  306.      * @param user2
  307.      * @return
  308.      */
  309.     public double testSameUser(String user1, String user2) {
  310.         /**
  311.          * throws error, if user1 and user2 have different lengths
  312.          */
  313.         if(user1.length() != user2.length()) {
  314.             System.out.println("[ERROR] Uservalues don't have the same length!");
  315.             /**
  316.              * exit function (program still runs)
  317.              */
  318.             return 0F;
  319.         }
  320.        
  321.         double sameAnswers = 0;
  322.        
  323.         /**
  324.          * converts user1 and user2 from string to char arrays
  325.          */
  326.         char[] user1char = user1.toCharArray();
  327.         char[] user2char = user2.toCharArray();
  328.        
  329.         for(int i=0; i<user1.length(); i++) {
  330.             if(user1char[i] == user2char[i]) {
  331.                 sameAnswers++;
  332.             }
  333.         }
  334.        
  335.         /**
  336.          * divides sameAnswers/length = percent of right answers
  337.          */
  338.         return sameAnswers/user1.length();
  339.     }
  340.    
  341.     /**
  342.      * This function counts the lines of a file.
  343.      * I don't made this function, i found it on <a href="stackoverflow.com">stackoverflow.com</a>
  344.      * @param filename
  345.      * @return
  346.      * @throws IOException
  347.      */
  348.     public static int countLines(String filename) throws IOException {
  349.         InputStream is = new BufferedInputStream(new FileInputStream(filename));
  350.         try {
  351.             byte[] c = new byte[1024];
  352.             int count = 0;
  353.             int readChars = 0;
  354.             boolean empty = true;
  355.             while ((readChars = is.read(c)) != -1) {
  356.                 empty = false;
  357.                 for (int i = 0; i < readChars; ++i) {
  358.                     if (c[i] == '\n') {
  359.                         ++count;
  360.                     }
  361.                 }
  362.             }
  363.             return (count == 0 && !empty) ? 1 : count;
  364.         } finally {
  365.             is.close();
  366.         }
  367.     }
  368. }
  369.  
  370. /**
  371.  * This class opens a little promt-window with text and a 'OK' button.
  372.  * @author Phantom6208
  373.  *
  374.  */
  375. class PromtWindow extends JFrame implements ActionListener {
  376.  
  377.     /**
  378.      * Creates variables
  379.      */
  380.     private JButton ok;
  381.     private JLabel label;
  382.     private JPanel panel;
  383.     private BoxLayout layout;
  384.    
  385.     /**
  386.      * Constructor
  387.      * @param windowTitle
  388.      * @param promt
  389.      */
  390.     public PromtWindow(String windowTitle, String promt) {
  391.         /**
  392.          * Creates label, button, panel and layout
  393.          */
  394.         ok = new JButton("OK");
  395.         label = new JLabel(promt + "      ");
  396.         panel = new JPanel();
  397.         layout = new BoxLayout(panel, BoxLayout.LINE_AXIS);
  398.        
  399.         // ---
  400.        
  401.         /**
  402.          * Adds ActionListener to catch inputs.
  403.          */
  404.         ok.addActionListener(this);
  405.        
  406.         // ---
  407.        
  408.         /**
  409.          * Sets layout of panel; Adds components to panel.
  410.          */
  411.         panel.setLayout(layout);
  412.        
  413.         panel.add(label);
  414.         panel.add(ok);
  415.        
  416.         add(panel);
  417.        
  418.         // ---
  419.  
  420.         /**
  421.          * Sets window title, its location, its size and if its resizeable
  422.          */
  423.         setTitle(windowTitle);
  424.        
  425.         setLocation(100, 100);
  426.         setSize(new Dimension(200, 75));
  427.         setResizable(false);
  428.        
  429.         /**
  430.          * Makes window visible
  431.          */
  432.         setVisible(true);
  433.        
  434.     }
  435.    
  436.     @Override
  437.     /**
  438.      * If user press ok -> window get closed.
  439.      */
  440.     public void actionPerformed(ActionEvent e) {
  441.         if(e.getSource() == ok) {
  442.             this.dispose();
  443.         }
  444.     }
  445. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement