Exemple #1
1
  /**
   * Moves and archives old, non-executed transactions into an archive file.
   *
   * <p>Makes sure the file to archive to doesn't exist, and shows amount of archived transactions
   */
  private static void arkiveraGamlaTransaktioner() {
    File archive;

    System.out.print("Mata in ett nytt filnamn att arkivera till: ");
    archive = new File(tbScanner.nextLine());

    while (archive.exists()) {
      System.out.print("Filen existerar redan; var god mata in ett nytt filnamn: ");
      archive = new File(tbScanner.nextLine());
    }
    tbScanner.reset();
    System.out.println("Sparar till: " + archive);

    // Hämtar datum en vecka tillbaka
    Calendar c = Calendar.getInstance();
    c.add(Calendar.WEEK_OF_YEAR, -1);

    // Försöker arkivera till den nya filen
    try {
      int antalArkiveradeTransaktioner;
      antalArkiveradeTransaktioner = m.archiveTransactions(c.getTime(), archive);
      System.out.println("Arkiverade " + antalArkiveradeTransaktioner + " transaktioner");
    } catch (IOException e) {
      System.out.println("Kunde inte skriva till arkivfilen!");
    }
  } // s**t på arkiveraGamlaTransaktioner
Exemple #2
1
  public static void main(String[] args) {
    long st, dt, et;
    String plaintext1 = "Yellow and Black Border Collies";
    String keysPath = "keys.txt";
    RSA rsa;

    try {
      Scanner in = new Scanner(new FileReader(keysPath));
      BigInteger n = new BigInteger(in.nextLine().substring(3));
      BigInteger e = new BigInteger(in.nextLine().substring(3));
      BigInteger d = new BigInteger(in.nextLine().substring(3));
      in.close();

      rsa = new RSA(n, e, d);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return;
    }

    //		rsa = new RSA(8, 1024);

    st = System.currentTimeMillis();
    String ciphertext = rsa.encrypt(plaintext1);
    dt = System.currentTimeMillis();
    String plaintext2 = rsa.decrypt(ciphertext);
    et = System.currentTimeMillis();

    System.out.println("enc time: " + (dt - st));
    System.out.println("dec time: " + (et - dt));
    System.out.println(plaintext2);

    // rsa.saveKeys(keysPath);
  }
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n = Integer.parseInt(scanner.nextLine());

    // Create all the vertices first.
    Vertex[] vertices = new Vertex[n];
    for (int i = 0; i < n; ++i) {
      vertices[i] = new Vertex(scanner.nextInt());
    }
    scanner.nextLine();

    // Connect the vertices.
    int parent, child;
    while (n > 1) {
      parent = scanner.nextInt() - 1;
      child = scanner.nextInt() - 1;
      vertices[parent].connectWith(vertices[child]);
      n--;
    }

    // Calculate the weights of all the vertices.
    Vertex root = vertices[0];
    root.calculateWeight();

    // Calculate the smallest possible difference when removing an edge.
    System.out.println(root.calculateSmallestDiff());
  }
Exemple #4
0
  public void makeTitle() throws FileNotFoundException {
    Scanner sc = new Scanner(new FileReader("Title.txt"));
    String line = "";
    while (sc.hasNextLine()) {
      numLines++;
      line = sc.nextLine();
      if (size < line.length()) {
        size = line.length();
      }
    }

    // for nice fonts use "poison" or "rowan cap" or "Lean" or "AMD AAA01" or "Caligraphy"
    sc = new Scanner(new FileReader("Title.txt"));
    grid = new Bullet[size][numLines];

    char[] lineChars = new char[size];
    for (int y = 0; y < numLines; y++) {
      lineChars = sc.nextLine().toCharArray();
      for (int x = 0; x < size; x++) {
        try {
          if (lineChars[x] != ' ') {
            //                         | plrSize
            //                         v
            grid[x][y] = new Bullet(x * 10 + width / 2 - size / 2 * 10, y * 10 + height / 5, 0);
            grid[x][y].xSpeed = 0;
            grid[x][y].ySpeed = 0;
            // grid[x][y].shpColor = (Color.GREEN);
          }
        } catch (Exception e) {

        }
      }
    }
  }
    public void interpretFromStream(InputStream in2) {
      Scanner in = new Scanner(in2);

      while (in.hasNextLine()) {
        // Calculating for 0 and 0, t = 37
        String[] line = in.nextLine().split("\\s+|[,]");

        String strA = line[2];
        String strB = line[4];

        UnafoldFoldEntry newEntry = new UnafoldFoldEntry(strA, strB);
        data.add(newEntry);

        line = in.nextLine().split("\\s+");
        int num = new Integer(line[0]);
        // 39	dG = -17.5	dH = -100.9	0-0

        double dg = new Double(line[3]);
        newEntry.mfeDG = dg;
        newEntry.pairs = new int[num];
        for (int k = 0; k < num; k++) {
          line = in.nextLine().split("\\s+");
          newEntry.pairs[k] = new Integer(line[4]) - 1;
        }
      }
    }
  /**
   * Test case for the method printMeasures() which prints the all the measures currently in
   * Tablature. This method is tested by first switching the output stream to a file and then
   * asserting that the contents of the file are equal to the expected value.
   */
  @Test
  public void testPrintMeasures() {
    try {
      PrintStream log = new PrintStream(new File("test files/tablature/printMeasures.txt"));
      System.setOut(log);

      String g = "||*-----<5>-----------<7>----------------------------*||";

      test.addLineToLastMeasure(g);
      test.addLineToLastMeasure(g);
      test.addLineToLastMeasure(g);
      test.addLineToLastMeasure(g);
      test.addLineToLastMeasure(g);
      test.addLineToLastMeasure(g);

      test.printMeasures();

      Scanner input = new Scanner(new File("test files/tablature/printMeasures.txt"));

      assertEquals(input.nextLine(), "Single");
      assertEquals(input.nextLine(), g);
      assertEquals(input.nextLine(), g);
      assertEquals(input.nextLine(), g);
      assertEquals(input.nextLine(), g);
      assertEquals(input.nextLine(), g);
      assertEquals(input.nextLine(), g);

      input.close();
    } catch (FileNotFoundException e) {
    }
  }
 public static void main(String[] args) {
   // テキストの表示
   System.out.println("ようこそ占いの館へ");
   // テキストの表示
   System.out.print("あなたの名前を入力してください>");
   // scannerのインスタンス
   scanner = new java.util.Scanner(System.in);
   String name = scanner.nextLine();
   // テキストの表示
   System.out.print("あなたの年齢を入力してください");
   // 変数ageStringに1行の入力されたテキストを格納
   String ageString = scanner.nextLine();
   // ageStringをageに変換
   int age = Integer.parseInt(ageString);
   // 0~3までの乱数を生成し、fortuneに格納
   int fortune = new java.util.Random().nextInt(4);
   // 1~4に変更
   fortune++;
   // テキストの表示
   System.out.println("占いの結果が出ました!");
   // テキストの表示
   System.out.println(age + "歳の" + name + "さん、あなたの運気番号は" + fortune + "です");
   // テキストの表示
   System.out.println("1:大吉," + " 2:中吉," + " 3:吉," + " 4:凶");
 }
Exemple #8
0
  public Game readGameInformation() {
    String fileName = "save file.txt";
    File currentSaveFile = new File(fileName);
    Scanner fileReader;
    Game currentGame = null;
    int gameRanking = 0;
    String gameTitle = "";
    ArrayList<String> gameRules = new ArrayList<String>();

    try {
      fileReader = new Scanner(currentSaveFile);
      gameTitle = fileReader.nextLine();
      gameRanking = fileReader.nextInt();
      while (fileReader.hasNext()) {
        gameRules.add(fileReader.nextLine());
      }

      currentGame = new Game(gameRules, gameRanking, gameTitle);
      fileReader.close();
    } catch (FileNotFoundException currentFileDoesNotExist) {
      JOptionPane.showMessageDialog(appFrame, currentFileDoesNotExist.getMessage());
    }

    return currentGame;
  }
  /**
   * ****************************************************** Allows the user to add more teams to the
   * database
   *
   * @param conn *****************************************************
   */
  public static void addTeams(Connection conn) {
    Scanner keyboard = new Scanner(System.in);
    try {
      char ans;
      String teamName;

      Statement stmt = conn.createStatement();

      do {
        // *********************************************
        // Task 3
        System.out.print("Enter the team name: ");
        teamName = keyboard.nextLine();
        String sqlStatement = "INSERT INTO Teams " + "(TeamName) " + "VALUES ('" + teamName + "')";
        stmt.executeUpdate(sqlStatement);
        // **********************************************

        System.out.print("Do you want to enter another team: ");
        ans = keyboard.nextLine().charAt(0);
      } while (ans == 'Y' || ans == 'y');

    } catch (Exception ex) {
      System.out.println("ERROR: " + ex.getMessage());
    }
  }
Exemple #10
0
  public static void main(String[] args) {
    StudentScores studSc = new StudentScores();
    Scanner in = new Scanner(System.in);
    boolean done = false;
    // Read the students names and scores, and add them to studSc
    do {
      Student s = new Student();

      System.out.println("Enter a student name or -1 to end: ");
      String name = in.nextLine();
      if (name.equals("-1")) done = true;
      else {
        System.out.println("Enter the student's score: ");
        int score = in.nextInt();
        in.nextLine(); // skip the end-of-line character
        /** Your code goes here */
        s.SetStudent(name, score);
      }
      studSc.add(s);
    } while (!done);
    // Find the students with highest and lowest scores and print
    // their names and scores
    /** And here */
    System.out.println("가장 높은 점수 >> " + studSc.getHighest());
    System.out.println("가장 낮은 점수 >> " + studSc.getLowest());
  }
Exemple #11
0
  public void loadDump(File dumpFile, File lineFile, File dumpInfoFile)
      throws FileNotFoundException, IOException {

    FileInputStream vertexStream = new FileInputStream(dumpFile);
    MappedByteBuffer inVertex =
        vertexStream.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, dumpFile.length());
    vertices = inVertex.asFloatBuffer();

    FileInputStream vertexLineStream = new FileInputStream(lineFile);
    MappedByteBuffer inLine;
    inLine = vertexLineStream.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, lineFile.length());
    stripVertexCounts = inLine.asIntBuffer();

    Scanner scanner = new Scanner(dumpInfoFile);

    String line;

    line = scanner.nextLine();
    minX = Float.parseFloat(line);
    line = scanner.nextLine();
    maxX = Float.parseFloat(line);
    line = scanner.nextLine();
    minY = Float.parseFloat(line);
    line = scanner.nextLine();
    maxY = Float.parseFloat(line);
  }
Exemple #12
0
 /** Adds the review. */
 private void addReview() {
   int id = 0;
   System.out.println(LINE_SPACING);
   String detail = null;
   int rating = 0;
   System.out.println("The movie list: ");
   movieUser.printMovieList();
   boolean done = false;
   while (!done) {
     System.out.print("Enter the id of the movie you want to review: ");
     try {
       id = Integer.parseInt(sc.nextLine());
     } catch (NumberFormatException e) {
       System.out.println("Please enter a valid number!");
       continue;
     }
     System.out.println(LINE_SPACING);
     System.out.print("Enter your review: ");
     detail = sc.nextLine();
     while (true) {
       System.out.print("Rate the movie(from 1 to 5): ");
       try {
         rating = Integer.parseInt(sc.nextLine());
       } catch (NumberFormatException e) {
         System.out.println("Please enter a valid number!");
         continue;
       }
       break;
     }
     System.out.println("Thank you for your review!");
     done = true;
   }
   movieUser.updateReview(id, detail, rating);
   movieUser.save();
 }
Exemple #13
0
  @Override
  public void readFile(File f) {
    Scanner sc;

    try {
      sc = new Scanner(f);
    } catch (FileNotFoundException e) {
      throw new IllegalArgumentException("Ficheiro n?o encontrado!");
    }
    try {
      while (sc.hasNextLine()) {
        sc.nextLine();
        String name = sc.nextLine();
        int cc = Integer.parseInt(sc.nextLine());
        String[] ddns = sc.nextLine().split("/");
        Data ddn =
            new Data(
                Integer.parseInt(ddns[0]), Integer.parseInt(ddns[1]), Integer.parseInt(ddns[2]));
        add(name, ddn, cc);
      }
    } catch (NullPointerException e) {
      sc.close();
      throw new IllegalArgumentException("Algo de errado se passou!");
    }
    sc.close();
  }
 // funciona pero TLE
 public static void main(String[] args) {
   Scanner sc = new Scanner(System.in);
   int casos = sc.nextInt();
   String entrada;
   sc.nextLine();
   List<Paciente> p = new ArrayList<Paciente>();
   for (int i = 0; i < casos; i++) {
     entrada = sc.nextLine();
     if (entrada.contains("I")) {
       p.add(
           new Paciente(
               i,
               entrada.substring(entrada.indexOf(' ') + 1, entrada.lastIndexOf(' ')),
               Integer.parseInt(entrada.substring(entrada.lastIndexOf(' ') + 1))));
     } else if (entrada.equals("A")) {
       Collections.sort(p);
       Collections.reverse(p);
       System.out.println(p.get(0));
       p.remove(0);
     }
     if (i == casos - 1) {
       System.out.println("----");
     }
   }
   sc.close();
 }
Exemple #15
0
 public static void readInput() {
   n = sc.nextInt();
   fibI = new int[n];
   for (int i = 0; i < n; i++) fibI[i] = sc.nextInt();
   sc.nextLine();
   cipher = sc.nextLine().replaceAll("[^A-Z]", "");
 }
Exemple #16
0
  public static void main(String[] args) {
    String phrase; // a string of characters
    int countBlank; // the number of blanks (spaces) in the phrase
    int length; // the length of the phrase
    char ch; // an individual character in the string
    int counta = 0;
    int counte = 0;
    int countt = 0;
    int counts = 0;
    String quit = "hahah";
    Scanner scan = new Scanner(System.in);

    // Print a program header
    do {
      System.out.println("Character Counter");

      // Read in a string and find its length
      System.out.print("Enter a sentence or phrase: ");
      phrase = scan.nextLine();
      length = phrase.length();

      // Initialize counts
      countBlank = 0;

      // a for loop to go through the string character by character

      for (int i = 1; i < length; i++) {
        ch = phrase.toLowerCase().charAt(i);
        if (ch == ' ') countBlank++;
      }
      for (int e = 1; e < length; e++) {
        ch = phrase.toLowerCase().charAt(e);
        if (ch == 't') countt++;
      }
      for (int a = 1; a < length; a++) {
        ch = phrase.toLowerCase().charAt(a);
        if (ch == 'a') counta++;
      }
      for (int b = 1; b < length; b++) {
        ch = phrase.toLowerCase().charAt(b);
        if (ch == 's') counts++;
      }
      for (int f = 1; f < length; f++) {
        ch = phrase.toLowerCase().charAt(f);
        if (ch == 'e') counte++;
      }

      // and count the blank spaces

      // Print the results
      System.out.println("Number of t's: " + countt);
      System.out.println("Number of a's: " + counta);
      System.out.println("Number of s's: " + counts);
      System.out.println("Number of e's: " + counte);
      System.out.println("Number of blank spaces: " + countBlank);
      System.out.println("if you want to stop. input quit now or otherwise hit enter");
      quit = scan.nextLine();
    } while (!quit.equalsIgnoreCase("quit"));
    System.out.println("program has ended");
  }
Exemple #17
0
  private static UnivariatePalette readPalette(Scanner scan) {
    String line = scan.nextLine();
    Scanner lineScan = new Scanner(line);
    lineScan.useDelimiter(",");

    String name = lineScan.next();
    int maxLength = lineScan.nextInt();
    SequenceType type = findSequenceType(lineScan.next());
    HashMap<Integer, Color[]> colorMap = new HashMap<Integer, Color[]>();
    Color[] colors = new Color[maxLength];
    for (int i = 0; i < maxLength; i++) {
      if (i > 0) {
        line = scan.nextLine();
        lineScan = new Scanner(line);
        lineScan.useDelimiter(",");
        lineScan.next();
        lineScan.next();
      }
      String indexString = lineScan.next();
      int index = Integer.valueOf(indexString);
      assert (i == index - 1);
      lineScan.next(); // skip letter
      int r = lineScan.nextInt();
      int g = lineScan.nextInt();
      String bString = lineScan.next();
      // logger.info("bString = " + bString);
      int b = Integer.valueOf(bString.trim());
      Color col = new Color(r, g, b);
      colors[i] = col;
    }
    colorMap.put(maxLength, colors);

    UnivariatePalette pal = new UnivariatePalette(name, type, colorMap, maxLength);
    return pal;
  }
  public void transferMoney() throws InsufficientFundsException, NonExistingBankAccountException {
    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter origin account number: ");
    long originAccountNumber = Long.parseLong(scanner.nextLine());
    System.out.println("Enter destination account number: ");
    long destinationAccountNumber = Long.parseLong(scanner.nextLine());
    System.out.println("Enter amount of money you want to transfer: ");
    double money = Double.parseDouble(scanner.nextLine());

    scanner.close();

    if (bank.get(originAccountNumber) == null || bank.get(destinationAccountNumber) == null) {
      throw new NonExistingBankAccountException("Bank account doesn't exist!");
    }
    bank.get(originAccountNumber).transfer(bank.get(destinationAccountNumber), money);
    bank.get(originAccountNumber)
        .getHistory()
        .add(
            String.format(
                "Transfered %d to bank account with number %d", money, destinationAccountNumber));
    bank.get(destinationAccountNumber)
        .getHistory()
        .add(
            String.format(
                "Received %d from bank account with number %d", money, originAccountNumber));
  }
 /** main */
 public static void main(String[] args) {
   BinaryTree<String> tree = initTree();
   System.out.println("Please think of an object: ");
   Scanner keyboard = new Scanner(System.in);
   while (!tree.isLeaf()) {
     System.out.println(tree.value());
     String input = keyboard.nextLine();
     if (input.equalsIgnoreCase("yes")) tree = tree.right();
     else if (input.equalsIgnoreCase("no")) tree = tree.left();
     else System.out.println("please enter yes or no: ");
   }
   System.out.println("Is your thing a " + tree.value() + "?\n");
   String input = keyboard.nextLine();
   if (input.equalsIgnoreCase("yes")) {
     System.out.println("GOT EM!!!!");
     return;
   } else if (input.equalsIgnoreCase("no")) {
     tree.setLeft(new BinaryTree<String>(tree.value()));
     System.out.println("Please enter your object : ");
     input = keyboard.nextLine();
     tree.setRight(new BinaryTree<String>(input));
     System.out.println(
         "Please enter a question that would distinguish your thing/person from a "
             + tree.value()
             + ": ");
     input = keyboard.nextLine();
     tree.setValue(input);
   }
 }
  public static void main(String[] args) {
    String line;
    int modulus = 253;
    long hash1, hash2, hash3;
    Scanner console = new Scanner(System.in);

    System.out.print("Hash code for ");
    if (args.length > 0) {
      line = args[0];
      System.out.println(line);
    } else line = console.nextLine();

    hash1 = line.hashCode();
    hash2 = myHashCode(line);
    System.out.printf("String.hashCode gives %d\n     myHashCode gives %d\n", hash1, hash2);
    // Get the unsigned value into the long integer:
    if (hash1 < 0) {
      hash1 = 0x100000000L + hash1;
      System.out.printf("After forcing an unsigned value:  %d\n", hash1);
    }
    System.out.printf("\nForcing results to stay less than %d\n", modulus);
    hash2 = hash1 % modulus;
    System.out.printf("%d mod %d goes to %d\n", hash1, modulus, hash2);
    hash3 = moduloHashCode(line, modulus);
    System.out.printf("moduloHashCode(\"%s\") gives %d\n", line, hash3);
    System.out.print("Press ENTER to exit: ");
    console.nextLine();
  }
Exemple #21
0
 public static void main(String[] args) {
   try {
     flraf = new FLRAF(28);
     sc = new Scanner(new File("btree/words.txt"));
   } catch (FileNotFoundException f) {
     System.out.println(f);
   }
   while (sc.hasNext()) flraf.write(sc.next());
   System.out.println("Block 0: " + flraf.read(0));
   System.out.println("Block 5643: " + flraf.read(5643));
   System.out.println("Block 45406: " + flraf.read(45406));
   sc = new Scanner(System.in);
   System.out.print("Another? > ");
   while (sc.nextLine().equalsIgnoreCase("y")) {
     System.out.print("Enter index to read > ");
     String s = sc.nextLine();
     if (s.contains(",")) {
       Integer j = Integer.parseInt(s.substring(0, s.lastIndexOf(",")));
       Integer k = Integer.parseInt(s.substring(s.lastIndexOf(",") + 1));
       String[] st = flraf.read(j, k);
       System.out.println("Blocks : " + j + " - " + k + " : ");
       for (int i = 0; i < st.length; i++)
         if (st[i] != null) System.out.println(st[i]);
         else System.out.println("Index out of range");
     } else {
       Integer i = Integer.parseInt(s);
       s = flraf.read(i);
       if (s != null) System.out.println("Block " + i + ": " + s);
       else System.out.println("Index out of range");
     }
     System.out.print("Another?");
   }
 }
  public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    int nodeCount = scanner.nextInt();
    int[] weightArr = new int[nodeCount + 1];
    GraphNode[] nodeArr = new GraphNode[nodeCount + 1];
    scanner.nextLine();
    for (int j = 1; j <= nodeCount; j++) {
      weightArr[j] = scanner.nextInt();
      sumOfAll += weightArr[j];
    }
    for (int j = 1; j <= nodeCount; j++) {
      nodeArr[j] = new GraphNode(j, weightArr[j]);
    }

    scanner.nextLine();

    for (int i = 1; i < nodeCount; i++) {
      int k = scanner.nextInt();
      int v = scanner.nextInt();
      nodeArr[k].list.add(nodeArr[v]);
      nodeArr[v].list.add(nodeArr[k]);
      scanner.nextLine();
    }

    minDifference(nodeArr[1], nodeArr[1], weightArr);
    System.out.println(ans);
  }
Exemple #23
0
  /**
   * Loads spaces from a text file
   *
   * @param filepath Filepath of text file
   */
  public void loadGame(String filepath) {
    if (loaded) return;
    InputStream stream = this.getClass().getResourceAsStream("/space1.txt");

    Scanner in = null;
    try {
      in = new Scanner(stream);
      while (in.hasNextLine()) {
        String name = in.nextLine();
        String scoreModifier = in.nextLine();
        String goAgain = in.nextLine();
        String RGB = in.nextLine();
        String[] colors = RGB.split(",");
        Color color =
            new Color(
                Integer.parseInt(colors[0]),
                Integer.parseInt(colors[1]),
                Integer.parseInt(colors[2]));
        // System.out.println(color.toString());
        Space space =
            new Space(name, Integer.parseInt(scoreModifier), Boolean.parseBoolean(goAgain));
        space.setColor(color);
        addSpace(space);
      }

    } catch (Exception e) {
      System.out.println("Unable to read file.");

    } finally {
      in.close();
    }
  }
Exemple #24
0
  Client() {
    sc = new Scanner(new InputStreamReader(System.in));
    try {
      clientSocket = new Socket("localhost", 27015);
      System.out.println("Connected to server!");
      System.out.println("Enter your Nick: ");
      Scanner sc = new Scanner(new InputStreamReader(System.in));
      name = sc.nextLine();
    } catch (Exception ex) {
      System.out.println("Can't connect to server " + ex);
    }
    try {
      in = new DataInputStream(clientSocket.getInputStream());
      out = new DataOutputStream(clientSocket.getOutputStream());

      ClientReader reader = new ClientReader();
      reader.start();
      String str = "";
      while (!str.equals("exit")) {
        str = sc.nextLine();
        out.writeUTF(name + ": " + str);
      }
    } catch (Exception ex) {
      System.out.println("Err: " + ex);
    }
  }
  public static void main(String[] args) {

    HashMap<String, String> usuario = new HashMap<String, String>();

    usuario.put("angelo", "1234");
    int oportunidades = 3;
    boolean accesoPermitido = false;

    Scanner entrada = new Scanner(System.in);
    System.out.println("Acceso");
    System.out.println("=========");
    System.out.print("Introduzca su nombre de usuario: ");
    String nombreUsuario = entrada.nextLine();
    System.out.print("Introduzca contraseña: ");
    String contraseñaIntro = entrada.nextLine();
    do {
      if (!usuario.containsKey(nombreUsuario) || !usuario.containsValue(contraseñaIntro)) {
        System.out.println("Lo siento el usuario o contraseña introducidos no existen");
        System.out.print("Vuelva a introducir su nombre de usuario: ");
        nombreUsuario = entrada.nextLine();
        System.out.print("Vuelva a introducir la contraseña: ");
        contraseñaIntro = entrada.nextLine();

        oportunidades--;
        System.out.println("oportunidades: " + oportunidades);

      } else {
        System.out.println("Bienvenido de nuevo " + usuario.get(nombreUsuario));
        accesoPermitido = true;
      }
      if (oportunidades == 0) {
        System.out.println("Lo siento se quedo sin oportunidades.");
      }
    } while (accesoPermitido == false && oportunidades > 0);
  }
Exemple #26
0
  public static void main(String[] args) throws PatternSyntaxException {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter pattern: ");
    String patternString = in.nextLine();

    Pattern pattern = Pattern.compile(patternString);

    while (true) {
      System.out.println("Enter string to match: ");
      String input = in.nextLine();
      if (input == null || input.equals("")) return;
      Matcher matcher = pattern.matcher(input);
      if (matcher.matches()) {
        System.out.println("Match");
        int g = matcher.groupCount();
        if (g > 0) {
          for (int i = 0; i < input.length(); i++) {
            // Print any empty groups
            for (int j = 1; j <= g; j++)
              if (i == matcher.start(j) && i == matcher.end(j)) System.out.print("()");
            // Print ( for non-empty groups starting here
            for (int j = 1; j <= g; j++)
              if (i == matcher.start(j) && i != matcher.end(j)) System.out.print('(');
            System.out.print(input.charAt(i));
            // Print ) for non-empty groups ending here
            for (int j = 1; j <= g; j++)
              if (i + 1 != matcher.start(j) && i + 1 == matcher.end(j)) System.out.print(')');
          }
          System.out.println();
        }
      } else System.out.println("No match");
    }
  }
Exemple #27
0
  public static void main(String[] args) throws UnknownHostException, IOException {
    Socket sock = new Socket("localhost", 1111);
    Scanner s = new Scanner(System.in);

    OutputStream out = sock.getOutputStream();
    InputStream in = sock.getInputStream();

    out.flush();
    byte[] buffer = new byte[1024];
    int n;
    String index = "";

    if ((n = in.read(buffer)) != -1) {
      System.out.println(new String(buffer, 0, n));
      String name = s.nextLine();
      out.write(name.getBytes());
    }
    while (true) {
      if ((n = in.read(buffer)) != -1) {

        if ((new String(buffer, 0, n)).equals("DONE")) {
          System.out.println("File uploaded successfully");
        } else {
          System.out.println(new String(buffer, 0, n));
          index = s.nextLine();
          out.write(index.getBytes());
          System.out.println(new String(buffer, 0, in.read(buffer)));
        }
      }
    }
  }
  public static void addEvent() {
    System.out.println("Enter a blurb for an Event");

    String userBlurb = "";
    do {
      userBlurb = input.nextLine();
    } while (userBlurb.equals(""));

    System.out.println("Enter an hour for the Event");
    int userHour = -1;
    do {
      userHour = Integer.parseInt(input.nextLine());
      if (userHour < 0 || userHour > 24) System.out.println("Hour must be between 0 and 24");
    } while (userHour < 0 || userHour > 24);

    System.out.println("Enter a minute for the Event");
    int userMinute = -1;
    do {
      userMinute = Integer.parseInt(input.nextLine());
      if (userMinute < 0 || userMinute > 60) System.out.println("Minute must be between 0 and 60");

    } while (userMinute < 0 || userMinute > 60);

    HourEvent hEvent = new HourEvent(userBlurb, userHour, userMinute);
    // Find the first bigger element and place it before that to keep list sorted
    int i = 0;
    while (i < eventsList.size() && hEvent.compareTo(eventsList.get(i)) > 0) {
      i++;
    }

    eventsList.add(i, hEvent);
    menuSelection();
  }
Exemple #29
0
  public static void main(String[] args) {
    try {
      Scanner scanner = new Scanner(new FileInputStream("graph.txt"));
      int v = Integer.parseInt(scanner.nextLine());

      int source = Integer.parseInt(scanner.nextLine());

      int sink = Integer.parseInt(scanner.nextLine());

      ListGraph g = new ListGraph(v, source, sink);
      while (scanner.hasNext()) {
        String edgeLine = scanner.nextLine();

        String[] components = edgeLine.split("\\s+");
        assert components.length == 3;
        int i = Integer.parseInt(components[0]);
        int j = Integer.parseInt(components[1]);
        int capacity = Integer.parseInt(components[2]);

        g.addEdge(i, j, capacity);
      }

      System.out.println("Original matrix");
      g.print();

      ListGraph.maxFlow(g);

      g.print();

    } catch (FileNotFoundException e) {
      System.err.println(e.toString());
      System.exit(1);
    }
  }
Exemple #30
0
  public void addBlock(Block b) {
    if (b != null) {
      try {
        File file = new File("plugins/NerdLocker/blocks.lock");
        Scanner scan = null;
        String str = null;

        if (file.exists()) {
          scan = new java.util.Scanner(file);
          str = scan.nextLine();
          while (scan.hasNextLine()) {
            str = str.concat("\n" + scan.nextLine());
          }
        }

        int x = (int) b.getLocation().getX();
        int y = (int) b.getLocation().getY();
        int z = (int) b.getLocation().getZ();

        str = (x + "," + y + "," + z);

        PrintWriter out = new PrintWriter(new FileWriter(file, true));

        out.println(str);
        out.close();
        scan.close();
      } catch (Exception e) {
        // TODO: solve error not just cover it up :D
      }
    }
  }