private static String checkString(Func function, Scanner input, boolean newAccount, UserID uid) {

    String str = "";
    boolean valid = false;
    while (!valid) {
      if (function == Func.USERNAME) {

        if (newAccount) {
          System.out.println("Please enter your new username: "******"Please enter your user name");
        }
        str = input.next();
        valid = checkUserName(str, newAccount);
      } else if (function == Func.PASSWORD) {
        System.out.println("Please enter your password: "******"Please enter your first name: ");
        str = input.next();
        valid = str.length() > 2;
      }

      if (!valid && !newAccount) return null;
    }

    return !valid ? null : str;
  }
  /*
   * Similar to makeSureValInRange function except it is meant to return
   * more than one values of valid user input via LinkedList and it will
   * not return unless all of the input is valid
   * @param1 scanner object
   * @param2 lowerbound int
   * @param3 upperbound int
   * @param4 String that represents the entity we are entering the values for
   */
  public static LinkedList<Integer> makeSureValInRange2(
      Scanner scan, int lowerbound, int upperbound, String inputFor) {
    assert (lowerbound <= upperbound);
    LinkedList<Integer> list = new LinkedList<Integer>();
    System.out.println(
        SearchCriteria.prioritySetUpString(
            SearchCriteria.StringEnum.SELECT_CRITERIA, inputFor)); // prints the options to the user
    int value = scan.nextInt();
    if (valInRange(lowerbound, upperbound, value)) {
      list.add(value); // If the first inputted is in range then we add more values

      boolean done = false;
      int i = lowerbound;
      while (!done
          && i < upperbound) { // keep looking for input until user enters a duplicate value
        // or the LinkedList of input is full
        value = scan.nextInt();
        if (!list.contains(value) && valInRange(lowerbound, upperbound, value)) list.add(value);
        else done = true;
        i++;
      }
      return list;
    } else { // If the first value intered is not valid, then we return a null, which means that
      // we use default values (all values within range)
      System.out.println(
          SearchCriteria.prioritySetUpString(SearchCriteria.StringEnum.DEFAULT, inputFor));
      return null;
    }
  }
  /*
   *  Making sure that the user input is in range
   *  @param1 Scanner object for input
   *  @param2 lowerbound integer
   *  @param3 upperbound integer
   *  @param4 String that specifies for which attribute/field input is for
   *  printing purposes
   *  @param5 ValType enum that specifies whether the primitive value is
   *  an int or double
   *  @param6 boolean that specifies whether the input is an Enum value
   *  @param7 boolean that specifies whether to return the value if out of
   *  range (false) or not (true)
   */
  public static Number makeSureValInRange(
      Scanner input,
      int lowerbound,
      int upperbound,
      String inputFor,
      ValType valType,
      boolean enumeration,
      boolean withinRange) {

    boolean valid = !withinRange;
    Number val = 0;

    while (!valid) {

      System.out.println(inputString(inputFor, null, StringOption.SELECT, enumeration));

      val = valType == ValType.INTEGER ? input.nextInt() : input.nextDouble();

      if (val.intValue() < lowerbound || val.intValue() > upperbound) {
        System.out.println(inputString(inputFor, null, StringOption.INCORRECT, enumeration));
      } else {
        valid = true;
      }
    }
    return val;
  }
  /** Display the file in the text area */
  private void showFile() {
    Scanner input = null;
    try {
      // Use a Scanner to read text from the file
      input = new Scanner(new File(jtfFilename.getText().trim()));

      // Read a line and append the line to the text area
      while (input.hasNext()) jtaFile.append(input.nextLine() + '\n');
    } catch (FileNotFoundException ex) {
      System.out.println("File not found: " + jtfFilename.getText());
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (input != null) input.close();
    }
  }
Example #5
0
 public static void main(String args[]) throws IOException {
   MissingValues mv = new MissingValues();
   while (true) {
     System.out.println(
         "Menu : \t1. Global Constant\t2. AtrributeMean\n\t3. Specific AttributeMean\t4. Most ProbableValue\n\t\t\t0. Exit");
     switch (in.nextInt()) {
       case 1:
         mv.globalConstant();
         break;
       case 2:
         mv.attributeMean();
         break;
       case 3:
         mv.specificAttributeMean();
         break;
       case 4:
         mv.probableValue();
         break;
       case 0:
         System.exit(0);
       default:
         System.out.println("Invalid Option..!");
     }
   }
 }
  protected static void removeContact(UserID user, Scanner scan) {
    System.out.println("Please enter username of the user you want to remove: ");
    String username = scan.next();

    if (user.removeContact(username)) {
      System.out.println("Remove was successful.");
    } else {
      System.out.println("Cannot remove contact, check make sure username is correct");
    }
  }
 protected static void addContact(UserID user, Scanner scan) {
   assert (user != null);
   System.out.println("Please enter username of the user you want to add: ");
   String username = scan.next();
   UserID userAboutToAdd = registeredUsers.get(username);
   if (userAboutToAdd != null) {
     user.addContact(username);
     System.out.println("Contact added.");
   } else System.out.println("Contact cannot be added, check make sure username is correct");
 }
  public static void main(String[] args) throws Exception {

    File f = new File(inputFile);
    if (f.exists()) {
      Scanner input = new Scanner(f);
      String credentials = input.nextLine();
      input.close();
      String uname = credentials.split(",")[0].split("=")[1];
      String pword = credentials.split(",")[1].split("=")[1];

      con = connectToDb(uname, pword);
      if (con != null) {
        System.out.println("Connected to Database:" + con);
        loadData(uname, pword);
        task1();
        task2();
        task3();
        task4();
        con.close();
      } else System.out.println("Connection Error");
    } else System.out.println("Input file system.in not found");
  }
Example #9
0
  public static void main(String args[]) throws IOException {
    try {
      Scanner in = args.length == 0 ? new Scanner(System.in) : new Scanner(Paths.get(args[0]));

      try (Connection conn = getConnection()) {
        Statement stat = conn.createStatement();

        while (true) {
          if (args.length == 0) System.out.println("Enter command or EXIT to exit:");

          if (!in.hasNextLine()) return;

          String line = in.nextLine();
          if (line.equalsIgnoreCase("EXIT")) return;
          if (line.trim().endsWith(";")) // remove trailing semicolon
          {
            line = line.trim();
            line = line.substring(0, line.length() - 1);
          }
          try {
            boolean isResult = stat.execute(line);
            if (isResult) {
              ResultSet rs = stat.getResultSet();
              showResultSet(rs);
            } else {
              int updateCount = stat.getUpdateCount();
              System.out.println(updateCount + " rows updated");
            }
          } catch (SQLException ex) {
            for (Throwable e : ex) e.printStackTrace();
          }
        }
      }
    } catch (SQLException e) {
      for (Throwable t : e) t.printStackTrace();
    }
  }
  protected static void searchBasedOnCriteria(UserID user, Scanner scan) {

    assert (user != null && scan != null);

    SearchCriteria criteria = user.getUserCriteria();
    if (criteria != null) { //
      System.out.println("Current search criteria:\n" + criteria);
      System.out.println(
          "Press 1 if you would like to set up new search criteria or "
              + "anything else if you want to use current one");
      String input = scan.next();
      if (input.length() == 1 && input.charAt(0) == '1') user.setUpSearch(scan);
    } else {
      user.setUpSearch(scan);
    }

    Search search = new Search(user);
    printUserList(search.findUsersBasedOnSearchCriteria());
  }
  /*
   * method used to input values for search criteria ranges (Age, Weight, Height)
   * User can enter -1 to input default values (lowerbound, upperbound) or the function
   * won't terminate until proper input is entered for the range
   * @param5 Enum specifies type of val we are entering input for; either an integer or double
   */
  public static Number[] makeSureValInRangeRange(
      Scanner scan, int lowerbound, int upperbound, String className, ValType type) {

    System.out.println(
        "Press and enter any value on keyboard to enter values for "
            + className
            + " range or enter -1 to use default values for the range");
    Number[] range = new Number[2];

    if (scan.nextInt() == -1) {
      System.out.println("You had selected default values");
      range[0] = lowerbound;
      range[1] = upperbound;
      return range;
    } else {
      range[0] = makeSureValInRange(scan, lowerbound, upperbound, "lowerbound", type, false, true);
      range[1] = makeSureValInRange(scan, lowerbound, upperbound, "upperbound", type, false, true);
      return range;
    }
  }
Example #12
0
  public static void main(String[] args) {
    //////////////////////////
    // The values in following 4 lines should be user input
    int startPos = 200;
    int endPos = 1000;
    int totalNumPixel = 1044;
    double threshhold = 0.0001;
    /////////////////////////
    int numPixel = endPos - startPos;
    double wavelength[] = new double[totalNumPixel];
    double photonCount[] = new double[totalNumPixel];
    double SpecNoBk[] = new double[numPixel];
    double ThisSpectrum[] = new double[numPixel];
    double ThisXaxis[] = new double[numPixel];
    double Po[] = new double[numPixel];
    double Re[] = new double[numPixel];
    double P[] = new double[6];
    double Re2[] = new double[numPixel - 1];
    double mySUM[] = new double[numPixel];
    int ind[];
    double DEV;
    double prevDEV;
    Connection connection = null;
    Statement stmt = null;
    String pattern = "##.##";

    try {
      Scanner in = new Scanner(new FileReader(args[0]));
      int i = 0;
      while (in.hasNextDouble()) {
        wavelength[i] = in.nextDouble();
        photonCount[i] = in.nextDouble();
        ++i;
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    ThisSpectrum = Arrays.copyOfRange(photonCount, startPos, endPos);
    ThisXaxis = Arrays.copyOfRange(wavelength, startPos, endPos);
    final WeightedObservedPoints obs = new WeightedObservedPoints();

    for (int i = 0; i < numPixel; i++) {
      obs.add(ThisXaxis[i], ThisSpectrum[i]);
    }

    final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(5);
    P = fitter.fit(obs.toList());
    Polyval pVal = new Polyval(P, ThisXaxis, numPixel);
    Po = pVal.evl();

    for (int i = 0; i < numPixel; i++) {
      Re[i] = ThisSpectrum[i] - Po[i];
    }

    for (int i = 0; i < numPixel - 1; i++) {
      Re2[i] = Re[i + 1] - Re[i];
    }

    DEV = Math.sqrt(StatUtils.populationVariance(Re2, 0, Re2.length));
    for (int i = 0; i < numPixel; i++) {
      mySUM[i] = Po[i] + DEV;
    }

    int jj = 0; // jj is the length of points to be removed
    for (int i = 0; i < numPixel; i++) {
      if (ThisSpectrum[i] > mySUM[i]) {
        jj++;
        ;
      }
    }
    ind = new int[jj];

    int jjj = 0;
    for (int i = 0; i < numPixel; i++) {
      if (ThisSpectrum[i] > mySUM[i]) {
        ind[jjj] = i;
        jjj++;
      }
    }

    int indKeepLength = numPixel - ind.length;
    int indKeep[] = new int[indKeepLength];
    int k = 0;
    for (int i = 0; i < numPixel; i++) {
      if (!ArrayUtils.contains(ind, i)) {
        indKeep[k] = i;
        k++;
      }
    }
    double ThisSpectrumKeep[] = new double[indKeepLength];
    double ThisXaxisKeep[] = new double[indKeepLength];
    double PoKeep[] = new double[indKeepLength];
    double ReKeep[] = new double[indKeepLength];
    double Re2Keep[] = new double[indKeepLength - 1];
    double mySUMKeep[] = new double[indKeepLength];

    for (int i = 0; i < indKeepLength; i++) {
      ThisSpectrumKeep[i] = ThisSpectrum[indKeep[i]];
      ThisXaxisKeep[i] = ThisXaxis[indKeep[i]];
    }

    prevDEV = DEV;

    // at the point, ThisSpectrum and ThisXaxis should have reduced size
    final WeightedObservedPoints obs1 = new WeightedObservedPoints();

    for (int i = 0; i < indKeepLength; i++) {
      obs1.add(ThisXaxisKeep[i], ThisSpectrumKeep[i]);
    }

    while (true) {
      final PolynomialCurveFitter fitter1 = PolynomialCurveFitter.create(5);
      P = fitter1.fit(obs1.toList());
      Polyval pVal1 = new Polyval(P, ThisXaxisKeep, indKeepLength);
      PoKeep = pVal1.evl();

      for (int i = 0; i < indKeepLength; i++) {
        ReKeep[i] = ThisSpectrumKeep[i] - PoKeep[i];
      }

      for (int i = 0; i < indKeepLength - 1; i++) {
        Re2Keep[i] = ReKeep[i + 1] - ReKeep[i];
      }

      DEV = Math.sqrt(StatUtils.populationVariance(Re2Keep, 0, Re2Keep.length));

      for (int i = 0; i < indKeepLength; i++) {
        mySUMKeep[i] = PoKeep[i] + DEV;
      }

      for (int i = 0; i < indKeepLength; i++) {
        if (ThisSpectrumKeep[i] > mySUMKeep[i]) ThisSpectrumKeep[i] = mySUMKeep[i];
      }
      if ((Math.abs(DEV - prevDEV) / DEV) < threshhold) break;
      prevDEV = DEV;

      obs1.clear();
      for (int i = 0; i < indKeepLength; i++) {
        obs1.add(ThisXaxisKeep[i], ThisSpectrumKeep[i]);
      }
    }
    Polyval pVal2 = new Polyval(P, ThisXaxis, numPixel);
    double FLbk[] = pVal2.evl();
    for (int i = 0; i < ThisXaxis.length; i++) {
      SpecNoBk[i] = ThisSpectrum[i] - FLbk[i];
    }

    // the write-to-file part is only for testing purpose, ThisXaxis and SpecNoBk are two outputs
    try {
      FileWriter fr = new FileWriter(args[1]);
      BufferedWriter br = new BufferedWriter(fr);
      PrintWriter out = new PrintWriter(br);
      DecimalFormat df = new DecimalFormat(pattern);
      for (int j = 0; j < ThisXaxis.length; j++) {
        if (Double.toString(wavelength[j]) != null) out.write(ThisXaxis[j] + "\t" + SpecNoBk[j]);
        out.write("\r\n");
      }
      out.close();
    } catch (IOException e) {
      System.out.println(e);
    }
  }
  private void insertRows(Connection connection) {
    // Build the SQL INSERT statement
    String sqlInsert = "insert into " + jtfTableName.getText() + " values (";

    // Use a Scanner to read text from the file
    Scanner input = null;

    // Get file name from the text field
    String filename = jtfFilename.getText().trim();

    try {
      // Create a scanner
      input = new Scanner(new File(filename));

      // Create a statement
      Statement statement = connection.createStatement();

      System.out.println(
          "Driver major version? " + connection.getMetaData().getDriverMajorVersion());

      // Determine if batchUpdatesSupported is supported
      boolean batchUpdatesSupported = false;

      try {
        if (connection.getMetaData().supportsBatchUpdates()) {
          batchUpdatesSupported = true;
          System.out.println("batch updates supported");
        } else {
          System.out.println(
              "The driver is of JDBC 2 type, but " + "does not support batch updates");
        }
      } catch (UnsupportedOperationException ex) {
        System.out.println("The driver does not support JDBC 2");
      }

      // Determine if the driver is capable of batch updates
      if (batchUpdatesSupported) {
        // Read a line and add the insert table command to the batch
        while (input.hasNext()) {
          statement.addBatch(sqlInsert + input.nextLine() + ")");
        }

        statement.executeBatch();

        jlblStatus.setText("Batch updates completed");
      } else {
        // Read a line and execute insert table command
        while (input.hasNext()) {
          statement.executeUpdate(sqlInsert + input.nextLine() + ")");
        }

        jlblStatus.setText("Single row update completed");
      }
    } catch (SQLException ex) {
      System.out.println(ex);
    } catch (FileNotFoundException ex) {
      System.out.println("File not found: " + filename);
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (input != null) input.close();
    }
  }