Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.Dimension;
- import java.awt.GridLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.WindowEvent;
- import java.awt.event.WindowListener;
- import java.io.BufferedInputStream;
- import java.io.BufferedWriter;
- import java.io.FileInputStream;
- import java.io.FileWriter;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- import javax.swing.BoxLayout;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- /**
- *
- * @author Phantom6208
- * @version 1.2
- *
- * This Program asks the user simple questions and saves it in a file.
- *
- * Than it trys to compare the results to the results in the file.
- * If one of the results match, it says a welcome back
- *
- * 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...'
- *
- */
- public class Window extends JFrame implements ActionListener {
- /**
- * Yes button (in question window)
- */
- private JButton yes;
- /**
- * No button (in question window)
- */
- private JButton no;
- /**
- * This label shows the actual question
- */
- private JLabel question;
- /**
- * The panel witch get added to window
- */
- private JPanel panel;
- /**
- * Panel witch holds question.
- * Get added to panel
- */
- private JPanel panel1;
- /**
- * Panel witch holds the yes and no button.
- * Get added to panel
- */
- private JPanel panel2;
- /**
- * Layout (GridLayout), get applied to panel
- */
- private GridLayout layout;
- /**
- * Array of questions, in next version loaded by file
- */
- private String[] questions = {
- "This is a test question, please press 'YES'.",
- "This is a test question, please press 'NO'.",
- "This is a test question, please press what you want to.",
- "Did you ever travel to London?",
- "Did you ever killed a person?",
- "Did you ever broke a leg?",
- "Do you have more than 10$ in your pocket?",
- "Do you like this program?"
- };
- /**
- * Index of actual question
- */
- private int qNumber;
- /**
- * Saves users answers as string.
- * 1 = yes, 0 = no
- */
- private String tempID;
- /**
- * Main function, creates window and nothing else.
- * @param args
- */
- public static void main(String args[]) {
- JFrame frame = new Window();
- }
- /**
- * Window Class, creates the question window.
- */
- public Window() {
- System.out.println("[INFO] Starting program...");
- tempID = "";
- yes = new JButton("Yes");
- no = new JButton("No");
- question = new JLabel("undefined");
- panel = new JPanel();
- panel1 = new JPanel();
- panel2 = new JPanel();
- layout = new GridLayout(2, 0);
- // ---
- /**
- * Adds ActionListener to buttons yes and no.
- */
- yes.addActionListener(this);
- no.addActionListener(this);
- // ---
- /**
- * Adds components to panels
- */
- panel1.add(question);
- panel2.add(yes);
- panel2.add(no);
- panel.setLayout(layout);
- panel.add(panel1);
- panel.add(panel2);
- /**
- * Adds panel to window
- */
- add(panel);
- // ---
- /**
- * Sets question text; sets Question index to 1
- */
- question.setText(questions[0]);
- qNumber = 1;
- // ---
- /**
- * Set window Title
- */
- setTitle("Question Game");
- /**
- * Set window location and its size
- */
- setLocation(100, 100);
- setSize(new Dimension(500, 95));
- /**
- * Since now window is not resizeable (size by user editable)
- */
- setResizable(false);
- /**
- * Makes window visible on screen.
- */
- setVisible(true);
- }
- @Override
- /**
- * Catches Button-Events
- */
- public void actionPerformed(ActionEvent event) {
- /**
- * If button yes get pressed.
- */
- boolean action = false;
- if(event.getSource() == yes) { action = true; }
- if(event.getSource() == no) { action = false; }
- /**
- * Saves user input in tempID
- */
- if(action) {
- tempID += 1;
- System.out.println("[INFO] User pressed 'YES' for question " + qNumber);
- }
- else {
- tempID += 0;
- System.out.println("[INFO] User pressed 'NO' for question " + qNumber);
- }
- try {
- /**
- * try to set new question;
- * count question index up
- */
- question.setText(questions[qNumber]);
- qNumber++;
- /**
- * executed if index runs out of range (all questions answerd)
- */
- } catch(Exception e) {
- if(questions.length == qNumber) {
- System.out.println("[INFO] User finished all questions.");
- } else {
- /**
- * If its not the last question, throws error
- */
- System.out.println("[ERROR] Unknown error.");
- e.printStackTrace();
- }
- try {
- /**
- * Creates scanner to search users file.
- */
- Scanner scanner=new Scanner(new File("users.csv"));
- boolean found = false;
- /**
- * List of matches
- */
- ArrayList<String[]> matches = new ArrayList();
- /**
- * While scanner doesn't reach the end
- */
- while(scanner.hasNextLine()) {
- String nextLine = scanner.nextLine();
- /**
- * If the user input matches 80% or more.
- */
- if(testSameUser(tempID, nextLine.split(";")[1]) >= 0.8){
- System.out.println("[INFO] User maybe identificated: user" + nextLine.split(";")[0]);
- found = true;
- /**
- * Saves userID
- */
- String[] tempList = new String[2];
- tempList[0] = nextLine.split(";")[0];
- tempList[1] = String.valueOf(testSameUser(tempID, nextLine.split(";")[1].toString()));
- matches.add(tempList);
- }
- }
- if(!found) {
- /**
- * Opens users.csv file for reading
- */
- BufferedWriter users = new BufferedWriter(new FileWriter("users.csv", true));
- /**
- * Writes information about new user (userid, answers)
- */
- users.write(countLines("users.csv")+1 + ";" + tempID + "\r\n");
- users.close();
- } else {
- String[][] matchesArray = new String[matches.size()][2];
- for(int i=0; i<matches.size(); i++) {
- matches.get(0);
- }
- double max = Double.parseDouble(matchesArray[0][1]);
- int maxindex = 0;
- for ( int i = 1; i < matches.size(); i++) {
- if ( Double.parseDouble(matchesArray[i][1]) > max) {
- max = Double.parseDouble(matchesArray[i][1]);
- maxindex = i;
- }
- }
- System.out.println("[INFO] User possibly identificated: user" + matchesArray[maxindex][0]);
- new PromtWindow("I know who you are!", "I've identificated you, " + matchesArray[maxindex][0] + "!");
- }
- scanner.close();
- } catch (Exception exc) {
- System.out.println("[ERROR] can't save answers");
- exc.printStackTrace();
- }
- System.out.println("[INFO] Exit program...");
- dispose();
- }
- }
- /**
- * Tests how many percent of user1 and user2 are the same.
- * @param user1
- * @param user2
- * @return
- */
- public double testSameUser(String user1, String user2) {
- /**
- * throws error, if user1 and user2 have different lengths
- */
- if(user1.length() != user2.length()) {
- System.out.println("[ERROR] Uservalues don't have the same length!");
- /**
- * exit function (program still runs)
- */
- return 0F;
- }
- double sameAnswers = 0;
- /**
- * converts user1 and user2 from string to char arrays
- */
- char[] user1char = user1.toCharArray();
- char[] user2char = user2.toCharArray();
- for(int i=0; i<user1.length(); i++) {
- if(user1char[i] == user2char[i]) {
- sameAnswers++;
- }
- }
- /**
- * divides sameAnswers/length = percent of right answers
- */
- return sameAnswers/user1.length();
- }
- /**
- * This function counts the lines of a file.
- * I don't made this function, i found it on <a href="stackoverflow.com">stackoverflow.com</a>
- * @param filename
- * @return
- * @throws IOException
- */
- public static int countLines(String filename) throws IOException {
- InputStream is = new BufferedInputStream(new FileInputStream(filename));
- try {
- byte[] c = new byte[1024];
- int count = 0;
- int readChars = 0;
- boolean empty = true;
- while ((readChars = is.read(c)) != -1) {
- empty = false;
- for (int i = 0; i < readChars; ++i) {
- if (c[i] == '\n') {
- ++count;
- }
- }
- }
- return (count == 0 && !empty) ? 1 : count;
- } finally {
- is.close();
- }
- }
- }
- /**
- * This class opens a little promt-window with text and a 'OK' button.
- * @author Phantom6208
- *
- */
- class PromtWindow extends JFrame implements ActionListener {
- /**
- * Creates variables
- */
- private JButton ok;
- private JLabel label;
- private JPanel panel;
- private BoxLayout layout;
- /**
- * Constructor
- * @param windowTitle
- * @param promt
- */
- public PromtWindow(String windowTitle, String promt) {
- /**
- * Creates label, button, panel and layout
- */
- ok = new JButton("OK");
- label = new JLabel(promt + " ");
- panel = new JPanel();
- layout = new BoxLayout(panel, BoxLayout.LINE_AXIS);
- // ---
- /**
- * Adds ActionListener to catch inputs.
- */
- ok.addActionListener(this);
- // ---
- /**
- * Sets layout of panel; Adds components to panel.
- */
- panel.setLayout(layout);
- panel.add(label);
- panel.add(ok);
- add(panel);
- // ---
- /**
- * Sets window title, its location, its size and if its resizeable
- */
- setTitle(windowTitle);
- setLocation(100, 100);
- setSize(new Dimension(200, 75));
- setResizable(false);
- /**
- * Makes window visible
- */
- setVisible(true);
- }
- @Override
- /**
- * If user press ok -> window get closed.
- */
- public void actionPerformed(ActionEvent e) {
- if(e.getSource() == ok) {
- this.dispose();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement