Пример #1
1
  /**
   * Draws as much as possible of a given string into a 2d square region in a graphical space.
   *
   * @param g component onto which to draw
   * @param f font to use in drawing the string
   * @param s string to be drawn
   * @param xPos
   * @param yPos
   * @param width
   * @param height
   */
  public static void drawStringMultiline(
      Graphics2D g, Font f, String s, double xPos, double yPos, double width, double height) {
    FontMetrics fm = g.getFontMetrics(f);
    int w = fm.stringWidth(s);
    int h = fm.getAscent();
    // g.setColor(Color.LIGHT_GRAY);
    g.setColor(Color.BLACK);
    g.setFont(f);

    Scanner lineSplitter = new Scanner(s);
    // draw as much as can fit in each item
    // read all content from scanner, storing in string lists (where each string == 1 line), each
    // string should be as long as possible without overflowing the space
    int maxRows = (int) height / h;
    List<String> textRows = new ArrayList<>();
    while (lineSplitter.hasNextLine() && textRows.size() < maxRows) {
      String line = lineSplitter.nextLine();
      // if line is blank, insert to maintain paragraph seps
      if (line.trim().equals("")) {
        textRows.add("");
      }
      // else, pass to inner loop
      StringBuilder currentBuilder = new StringBuilder();
      int currentStrWidth = 0;
      Scanner splitter = new Scanner(line);
      while (splitter.hasNext() && textRows.size() < maxRows) {
        String token = splitter.next() + " ";
        // TODO incorporate weight detection, formatting for token?
        currentStrWidth += fm.stringWidth(token);
        if (currentStrWidth >= width) {
          // if string length >= glyph width, build row
          textRows.add(currentBuilder.toString());
          currentBuilder = new StringBuilder();
          currentBuilder.append(token);
          currentStrWidth = fm.stringWidth(token);
        } else {
          // if not yet at end of row, append to builder
          currentBuilder.append(token);
        }
      }

      // if we've still space and still have things to write, add them here
      if (textRows.size() < maxRows) {
        textRows.add(currentBuilder.toString());
        currentBuilder = new StringBuilder();
        currentStrWidth = 0;
      }
    }

    // write each line to object
    for (int t = 0; t < textRows.size(); t++) {
      String line = textRows.get(t);
      if (fm.stringWidth(line) <= width) {
        // ensure that string doesn't overflow the box
        //                g.drawString(line, (float) (xPos-(width/2.)), (float) (yPos-(height/2.) +
        // h * (t+1)));
        g.drawString(line, (float) xPos, (float) (yPos + h * (t + 1)));
      }
    }
  }
Пример #2
0
 public boolean ok(String out, String reference) {
   // log.fine("out1: " + a);
   // log.fine("out2: " + b);
   Scanner sa = new Scanner(out);
   Scanner sb = new Scanner(reference);
   while (sa.hasNext() && sb.hasNext()) {
     if (sa.hasNextDouble() || sb.hasNextDouble()) {
       if (!sa.hasNextDouble() || !sb.hasNextDouble()) return true;
       double da = sa.nextDouble();
       double db = sb.nextDouble();
       double d_abs = Math.abs(da - db);
       double d_rel = d_abs / Math.abs(db);
       if (!(d_abs < EPS || d_rel < EPS)) {
         log.fine("NOK, " + da + " too far from " + db);
         return false;
       }
     } else {
       String xa = sa.next();
       String xb = sb.next();
       if (!xa.equals(xb)) {
         log.fine("NOK, " + xa + " != " + xb);
         return false;
       }
     }
   }
   if (sa.hasNext() || sb.hasNext()) {
     log.fine("NOK: different number of tokens.");
     return false;
   }
   return true;
 }
Пример #3
0
 public static void main(String args[]) throws IOException {
   Scanner sf = new Scanner(new File("D:\\IB CS\\temp_Aman\\StudentsScores.in.txt"));
   int maxIndx = -1;
   String text[] = new String[1000];
   while (sf.hasNext()) // this allows the program to assign each line in the text file a variable
   {
     maxIndx++;
     text[maxIndx] = sf.nextLine();
   }
   for (int j = 0; j <= 4; j++) {
     Scanner sc = new Scanner(text[j]);
     String name =
         sc.next(); // this helps identify the Strings, which are the names of students, in each
     // line
     double sum =
         0.0; // it starts the sum and count variables with zero because they change as they move
     // along with the while loop
     int count = 0;
     while (sc.hasNext()) {
       sum = sum + sc.nextDouble(); // this while loop helps find out the number of integers in the
       // line and adds all of these numbers as well
       count = count + 1;
     }
     double avg = sum / count;
     int y = (int) Math.round(avg); // this converts the double variable avg to an integer
     System.out.println(name + "," + " average = " + y);
   }
 }
Пример #4
0
  // experimental
  // ====================================================================
  // ====================================================================
  // ====================================================================
  private void readAndDrawBIGGraph(String file) {
    // behövs inte än
    // @TODO
    // hur rita flera linjer mellan 2 noder? (för flera linjer)
    // reading of the graph should be done in the graph itself
    // it should be possible to get an iterator over nodes and one over edges
    // read in all the stops and lines and draw the lmap
    Scanner indata = null;
    // insert into p-queue to get them sorted
    names = new PriorityQueue<String>();
    try {
      // Read stops and put them in the node-table
      // in order to give the user a list of possible stops
      // assume input file is correct
      indata = new Scanner(new File(file + "-stops.txt"), "ISO-8859"); //
      while (indata.hasNext()) {
        String hpl = indata.next().trim();
        int xco = indata.nextInt();
        int yco = indata.nextInt();
        noderna.add(new BusStop(hpl, xco, yco));
        names.add(hpl);
        // Draw
        // this is a fix: fixa att Kålltorp och Torp är samma hållplats
        if (hpl.equals("Torp")) {
          xco += 11;
          hpl = "   / Torp";
        }
        karta.drawString(hpl, xco, yco, DrawGraph.Layer.BASE);
      }
      indata.close();

      //  Read in the lines and add to the graph
      indata = new Scanner(new File(file + "-lines.txt"), "ISO-8859");
      grafen = new DirectedGraph<BusEdge>(noderna.noOfNodes());
      Color color =
          new Color((float) Math.random(), (float) Math.random(), (float) Math.random()); //
      String lineNo = "1"; //
      while (indata.hasNext()) { // assume lines are correct
        int from = noderna.find(indata.next()).getNodeNo();
        int to = noderna.find(indata.next()).getNodeNo();
        grafen.addEdge(new BusEdge(from, to, indata.nextInt(), lineNo));
        indata.nextLine(); // skip rest of line
        // Draw
        BusStop busFrom = noderna.find(from);
        BusStop busTo = noderna.find(to);
        karta.drawLine(
            busFrom.xpos, busFrom.ypos, busTo.xpos, busTo.ypos, color, 2.0f, DrawGraph.Layer.BASE);
      }
      indata.close();
    } catch (FileNotFoundException fnfe) {
      throw new RuntimeException(" Indata till busshållplatserna saknas");
    }
    karta.repaint();
  } // end readAndDrawBIGGraph
 public static int initializeCentroids() throws FileNotFoundException {
   int i, k, index, numClust = 0;
   Review rv;
   String reviews = new String();
   String singleRv = new String();
   String reviewer = new String();
   String rating = new String();
   for (i = 0; i < maxClusters; i++) {
     centroids[i] = new Cluster();
     centroids_ref[i] = new Cluster();
   }
   File modelFile = new File(strModelFile);
   Scanner opnScanner = new Scanner(modelFile);
   while (opnScanner.hasNext()) {
     k = opnScanner.nextInt();
     centroids_ref[k].similarity = opnScanner.nextFloat();
     centroids_ref[k].movie_id = opnScanner.nextLong();
     centroids_ref[k].total = opnScanner.nextShort(); // Leo
     centroids_ref[k].total = attrNum + 1;
     reviews = opnScanner.next();
     Scanner revScanner = new Scanner(reviews).useDelimiter(",");
     // while(revScanner.hasNext()){ //Leo
     int attrCnt = 0;
     while (revScanner.hasNext() && attrCnt < attrNum) {
       singleRv = revScanner.next();
       index = singleRv.indexOf("_");
       // reviewer = new String(singleRv.substring(0,index)); //Leo
       reviewer = new String(String.valueOf(attrCnt));
       rating = new String(singleRv.substring(index + 1));
       rv = new Review();
       rv.rater_id = Integer.parseInt(reviewer);
       rv.rating = (byte) Integer.parseInt(rating);
       centroids_ref[k].reviews.add(rv);
       attrCnt++;
     }
   }
   // implementing naive bubble sort as maxClusters is small
   // sorting is done to assign top most cluster ids in each iteration
   for (int pass = 1; pass < maxClusters; pass++) {
     for (int u = 0; u < maxClusters - pass; u++) {
       if (centroids_ref[u].movie_id < centroids_ref[u + 1].movie_id) {
         Cluster temp = new Cluster(centroids_ref[u]);
         centroids_ref[u] = centroids_ref[u + 1];
         centroids_ref[u + 1] = temp;
       }
     }
   }
   for (int l = 0; l < maxClusters; l++) {
     if (centroids_ref[l].movie_id != -1) {
       numClust++;
     }
   }
   return numClust;
 }
Пример #6
0
 public Editor(File file) throws FileNotFoundException {
   this.file = file;
   Scanner fileScanner = new Scanner(file);
   while (fileScanner.hasNext()) {
     text += fileScanner.nextLine() + '\n';
   }
 }
Пример #7
0
  /**
   * The read admin list reads in admin objects from a readfile
   *
   * @return
   * @throws FileNotFoundException
   */
  public LinkedList<Admin> readAdminList() throws FileNotFoundException {
    FileInputStream fstream = new FileInputStream("adminList.csv");
    LinkedList<Admin> adminList = new LinkedList<Admin>();
    Scanner input = new Scanner(fstream);
    input.useDelimiter(",");

    try {
      // reads file
      while (input.hasNext()) {
        String firstName = input.next();
        String lastName = input.next();
        String userName = input.next();
        String password = input.next();
        String email = input.next();
        String office = input.next();
        String phoneNumber = input.nextLine();

        // creates admin
        Admin newAdmin =
            new Admin(userName, password, email, firstName, lastName, office, phoneNumber);

        adminList.add(newAdmin);
      }
      fstream.close();
    } catch (Exception e) {
      adminList = null;
    }

    Collections.sort(adminList);

    return adminList;
  }
Пример #8
0
  /**
   * Method reads file of name 'fileName' into Scanner object. Method reads each line into a String,
   * then tokenizes the String. Integer values from the String are output to the screen, while any
   * other tokens are skipped. Method assumes that integers are printed on same line as original
   * text.
   *
   * @throws FileNotFoundException
   */
  public static void printIntegersFromFile() throws FileNotFoundException {

    String fileName = "src/Question1.txt";
    Scanner input = new Scanner(new File(fileName));

    // process line by line
    while (input.hasNextLine()) {

      // read each line into String
      String line = input.nextLine();

      // tokenize String line by reading into new Scanner object
      Scanner tokens = new Scanner(line);

      // read until no tokens left on line
      while (tokens.hasNext()) {

        if (tokens.hasNextInt()) {

          // set nextInt and print to console
          int someNumber = tokens.nextInt();
          System.out.print(someNumber + " ");
        } else {
          // skip non integer tokens
          tokens.next();
        }
      }

      // insert blank line
      System.out.println();
    }
  }
  private int generateIndex(String content, int docid) {
    Scanner s = new Scanner(content); // Uses white space by default.
    int totalcount = 0;
    while (s.hasNext()) {
      ++_totalTermFrequency;
      ++totalcount;
      String token = s.next();
      // decrement the size() by 1 as the real doc id
      // int did=_documents.size()-1;

      Vector<Integer> plist = _index.get(token);
      if (plist != null) {
        if (plist.lastElement() != docid) {
          plist.add(docid);
          _index.put(token, plist);
        }
      } else {
        // _terms.add(token);
        Vector<Integer> p = new Vector<Integer>();
        p.add(docid);
        _index.put(token, p);
      }
    }

    return totalcount;
  }
Пример #10
0
  /**
   * @param args
   * @throws FileNotFoundException
   */
  public static void main(String[] args) throws FileNotFoundException {
    // TODO Auto-generated method stub
    System.out.println("Swim Meet Planner");

    // scanner to read file
    Scanner fileReader = new Scanner(new File("src/Finalprojectinput"));

    // create results Map
    HashMap<String, ArrayList<Integer>> results = new HashMap<String, ArrayList<Integer>>();

    // adding names and times to results Map
    while (fileReader.hasNext()) {
      String name = fileReader.next();
      int time = fileReader.nextInt();
      // does swimmer exist in map?
      if (results.containsKey(name)) {
        results.get(name).add(time);

      } else {
        ArrayList<Integer> times = new ArrayList<Integer>();
        times.add(time);
        results.put(name, times);
      }
    }
    fileReader.close();
    Average a = new Average();
    a.average(results);
  }
Пример #11
0
  /** Creates hashtable to store all the words in the dictionary */
  public static void createHashTable() {
    try {
      Scanner fileReader = new Scanner(new File("largedictionary.txt"));

      // read in every word from the dictionary file
      while (fileReader.hasNext()) {
        String theWord = fileReader.next();
        // create hash index for the word
        int index = toHash(theWord);

        // linear probing if the hashtable cell is occupied
        while (hashtable[index] != null) {
          index += 1;

          // if we somehow hit the end of the hashtable, go back to the beginning
          if (index == TABLE_SIZE) {
            index = 0;
          }
        }

        hashtable[index] = theWord;
      }
    } catch (FileNotFoundException e) {
      System.out.println("File not found.");
    }
  }
 public static String openFile(String nameProgram) throws FileNotFoundException {
   Scanner scanner = new Scanner(new File(nameProgram));
   String programString = "";
   while (scanner.hasNext()) programString += scanner.next();
   scanner.close();
   return programString;
 }
Пример #13
0
  public static void main(String[] args) {
    Scanner cin = new Scanner(System.in);
    int input;
    int[][] count = new int[10000][2];
    int length = 0, flag = 0;

    while (cin.hasNext()) {
      boolean check = false;
      input = cin.nextInt();

      for (int a = 0; a < length; a++) {
        if (check == false && input == count[a][0]) {
          check = true;
          flag = a;
        }
        if (check == true) {
          break;
        }
      }
      if (check == true) {
        count[flag][1]++;
      }
      if (check == false) {
        count[length][0] = input;
        count[length][1]++;
        length++;
      }
    }
    for (int b = 0; b < length; b++) {
      System.out.println(count[b][0] + " " + count[b][1]);
    }
  }
  public static void main(String args[]) throws Exception {
    HashSet<String> hs = new HashSet<String>();

    FileReader fr1 = new FileReader("sample.txt");
    BufferedReader br = new BufferedReader(fr1);
    String s;
    while ((s = br.readLine()) != null) {
      hs.add(s);
    }
    fr1.close();
    FileReader fr2 = new FileReader("input.txt");
    br = new BufferedReader(fr2);
    while ((s = br.readLine()) != null) {

      Scanner ip = new Scanner(s);

      String word;
      while (ip.hasNext()) {
        word = ip.next();
        if (hs.contains(word)) ;
        else System.out.print(word + " ");
      }
    }
    fr2.close();
  }
Пример #15
0
  /** @param args the command line arguments */
  public static void main(String[] args) {
    logger.setLevel(Level.OFF);

    Scanner scanner = new Scanner(System.in);

    String currentWord;
    HashMap<String, List<String>> dict = new HashMap<String, List<String>>();
    while ((scanner.hasNext()) && !(currentWord = scanner.next()).equals("#")) {
      char[] reduc = currentWord.toLowerCase().toCharArray();
      Arrays.sort(reduc);
      String sreduc = new String(reduc);
      if (dict.get(sreduc) == null) {
        dict.put(sreduc, new ArrayList<String>());
      }
      dict.get(sreduc).add(currentWord);
    }
    TreeSet<String> result = new TreeSet<String>();
    for (String key : dict.keySet()) {
      if (dict.get(key).size() == 1) {
        result.add(dict.get(key).get(0));
      }
    }
    for (String key : result) {
      System.out.println(key);
    }
  }
Пример #16
0
 public void load(Scanner s) {
   myWords.clear();
   while (s.hasNext()) {
     myWords.add(s.next().toLowerCase());
   }
   Collections.sort(myWords);
 }
Пример #17
0
  // execute command to access file and command to modify its content
  private static void executeFileCommand(String command) {

    String fileAction = getFirstWord(command);
    String fileName = getSecondWord(command);
    ArrayList<String> arrayList = new ArrayList<String>();

    if (fileAction.equalsIgnoreCase("TextBuddy")) {

      File newTextFile = new File(fileName);
      arrayList = prepareSystem(arrayList, newTextFile);
      waitCommandInput();
      while (sc.hasNext()) {
        String userCommand = sc.nextLine().trim();
        String feedback = executeUserCommand(arrayList, newTextFile, userCommand);
        if (feedback.equals(EXIT_STRING)) {
          break;
        }
        feedbackToUser(feedback);
        waitCommandInput();
      }

    } else {
      feedbackToUser(String.format(MESSAGE_INVALID_COMMAND, command));
    }
  }
Пример #18
0
 public static void main(String[] args) {
   Scanner input = new Scanner(System.in);
   System.out.println("Enter name of the file: ");
   String a = input.next();
   File file = new File(a);
   if (!file.exists()) {
     System.out.println("The file does not exist");
     System.exit(1);
   }
   double sum = 0;
   double count = 0;
   double avg = 0;
   try {
     Scanner input2 = new Scanner(file);
     while (input2.hasNext()) {
       double score = input2.nextDouble();
       sum = sum + score;
       count++;
     }
   } catch (Exception e) {
     System.out.println("Error!");
   }
   avg = sum / count;
   System.out.println("Total scores: " + count);
   System.out.println("Sum of all scores: " + sum);
   System.out.println("Average of all scores: " + avg);
   input.close();
 }
Пример #19
0
  public void listaKargatu() {
    try {
      Scanner fitxategia = new Scanner(new FileReader(fitxategiarenHelbidea()));
      String linea;
      System.out.println();
      System.out.println();
      System.out.println("Datuak kargatzen diren bitartean itxaron...");
      while (fitxategia.hasNext()) {
        linea = fitxategia.nextLine();
        String[] items = linea.split("\\s*###\\s*");
        Aktore nireAktorea = new Aktore(items[0]);
        for (int i = 1; i < items.length; i++) {
          if (!listaP.contains(items[i])) {
            Pelikula nirePelikula = new Pelikula(items[i]);
            listaP.addHash(items[i], nirePelikula);
            nireAktorea.gehituPelikula(nirePelikula);
            nirePelikula.geituAktore(nireAktorea);
          } else {
            nireAktorea.gehituPelikula(listaP.getPeli(items[i]));
            listaP.getPeli(items[i]).geituAktore(nireAktorea);
            ;
          }
        }
        listaA.gehituAktorea(nireAktorea);
      }
      fitxategia.close();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Пример #20
0
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int a, b, c;
    int L1, R1, C1;
    while (in.hasNext()) {
      L1 = in.nextInt();
      R1 = in.nextInt();
      C1 = in.nextInt();
      if (L1 == 0 && R1 == 0 && C1 == 0) break;
      a = b = c = 0;

      char map1[][][] = new char[L1][R1][C1];

      for (int i = 0; i < L1; i++)
        for (int j = 0; j < R1; j++) {
          map1[i][j] = in.next().toCharArray();
          for (int k = 0; k < C1; k++) {
            if (map1[i][j][k] == 'S') {
              a = i;
              b = j;
              c = k;
            }
          }
        }

      Main m = new Main(map1, L1, R1, C1);

      int sum = m.bfs(a, b, c);
      if (sum != -1) System.out.printf("Escaped in %d minute(s).\n", sum);
      else System.out.printf("Trapped!\n");
    }
  }
Пример #21
0
  public static void main(final String[] args) throws FileNotFoundException {
    if (args.length == 0) {
      System.out.println(usage);
      return;
    }

    Scanner sc = new Scanner(new File(dictFile));
    ArrayList<String> dict = new ArrayList<String>();
    while (sc.hasNext()) {
      dict.add(sc.next());
    }

    if (args[0].equals("list") && args.length == 2) {
      String word = args[1];
      System.out.println(fmtList(wordLadder(word, dict)));
    } else if (args[0].equals("top") && args.length == 2) {
      int num = Integer.parseInt(args[1]);
      System.out.println(fmtPairs(mostLadderable(num, dict)));
    } else if (args[0].equals("chain") && args.length == 3) {
      int steps = Integer.parseInt(args[1]);
      List<String> start = new ArrayList<String>();
      start.add(args[2]);
      Set<String> chain = wordChain(steps, start, dict);
      System.out.println(chain.size());
    } else {
      System.out.println(usage);
      return;
    }
  }
Пример #22
0
  public static void main(String[] args) {
    if (args.length < 2)
      throw new IllegalArgumentException("Not enough arguments present on initial program run");

    LinkedList<LinkedList<Anagram>>[] dictList = new LinkedList[199967];
    int wordCount = 0, collisions = 0;
    Scanner dictScanner = createInputScanner("words.txt");
    Scanner queryScanner = createInputScanner(args[0]);
    PrintWriter fout = createPrintWriter(args[1]);
    Pattern matchMaker = Pattern.compile("[A-Za-z0-9]+");

    while (dictScanner.hasNext()) {
      String line = dictScanner.nextLine();
      if (matchMaker.matcher(line).matches()) {
        collisions += hashStash(line, dictList);
        wordCount++;
      }
    }

    hashQuery(dictList, queryScanner, fout);
    /* for(int i = 0; i < dictList.length; i++){
        if(dictList[i] != null){
            fout.println(dictList[i].toString());
            System.out.print(dictList[i].size());
        }
    }*/
    System.out.println("Words: " + wordCount + " Collisions:" + collisions);

    fout.close();
    dictScanner.close();
    queryScanner.close();
  }
Пример #23
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);
    }
  }
Пример #24
0
 public Graph(String s) {
   nodes = new Node[MAX_NODES];
   input = new Scanner(s);
   System.out.println("#Create graph: ");
   while (input.hasNext()) {
     char from, to;
     int cost;
     from = input.next().charAt(0);
     to = input.next().charAt(0);
     cost = input.nextInt();
     int fromIndex = from - 'A';
     int toIndex = to - 'A';
     // Create nodes if data is new; no checking for now.
     if (nodes[fromIndex] == null) {
       nodes[fromIndex] = new Node(from);
     }
     if (nodes[toIndex] == null) {
       nodes[toIndex] = new Node(to);
     }
     // Create edge, add edge to list of edges for the "from" node
     edges[edgeIndex] = new Edge(nodes[fromIndex], nodes[toIndex], cost);
     nodes[fromIndex].addEdge(edges[edgeIndex]);
     Edge e = edges[edgeIndex];
     System.out.println(
         "edges[" + edgeIndex + "]: " + e.from.data + " -> " + e.to.data + "; cost: " + e.cost);
     edgeIndex++;
   }
 }
Пример #25
0
  /** Reads in the letter location data for the word hunt puzzle */
  public static void readPuzzle() {
    letters = new String[3][3][2];

    try {
      Scanner reader = new Scanner(new File("graph.txt"));

      while (reader.hasNext()) {
        String temp = reader.next();
        // if the String is not a number it is a character
        if (!NUMBERS.contains(temp)) {
          // find the coordinates of the letter/String
          int x = reader.nextInt();
          int y = reader.nextInt();
          int z = reader.nextInt();
          letters[x][y][z] = temp;
        }
      }

      // prints out the word hunt set up, in separate squares that represent the 2D arrays at each
      // depth
      for (int k = 0; k < 2; k++) {
        for (int i = 0; i < 3; i++) {
          for (int j = 0; j < 3; j++) {
            System.out.print(letters[i][j][k] + " ");
          }
          System.out.print("\n");
        }
        System.out.print("\n");
      }
    } catch (FileNotFoundException e) {
      System.out.println("No such file.");
    }
  }
Пример #26
0
 public static void main(String[] args) throws Exception {
   Scanner s = new Scanner(new FileReader("pb.in"));
   while (s.hasNext()) {
     String line = s.nextLine();
     String[] rep = line.split("\\(");
     String[] nonrep = (rep[0] + "0").split("\\.");
     long num1 = Integer.parseInt(rep[1].substring(0, rep[1].length() - 1));
     String nine = "";
     while (nine.length() != rep[1].length() - 1) nine += "9";
     for (int i = 0; i < nonrep[1].length() - 1; i++) nine += "0";
     String ten = "";
     while (nonrep[1].length() != ten.length()) ten += "0";
     ten = "1" + ten;
     String nr = nonrep[0] + nonrep[1];
     long den1 = Long.parseLong(nine);
     long den2 = Long.parseLong(ten);
     long num2 = Long.parseLong(nr);
     long num = num1 * den2 + num2 * den1;
     long den = den1 * den2;
     long gcd = new BigInteger("" + num).gcd(new BigInteger("" + den)).longValue();
     num /= gcd;
     den /= gcd;
     System.out.println(line + " = " + num + " / " + den);
   }
 }
Пример #27
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) throws IOException {
    in = new Scanner(new FileReader("wordFreq.in"));
    out = new PrintWriter(new FileWriter("wordFreq.out"));

    WordInfo[] wordTable = new WordInfo[N + 1];
    for (int h = 1; h <= N; h++) wordTable[h] = new WordInfo();

    int first = -1; // points to first word in alphabetical order
    int numWords = 0;

    in.useDelimiter("[^a-zA-Z]+");
    while (in.hasNext()) {
      String word = in.next().toLowerCase();
      int loc = search(wordTable, word);
      if (loc > 0) wordTable[loc].freq++;
      else // this is a new word
      if (numWords < MaxWords) { // if table is not full
        first = addToTable(wordTable, word, -loc, first);
        ++numWords;
      } else out.printf("'%s' not added to table\n", word);
    }
    printResults(wordTable, first);
    in.close();
    out.close();
  } // end main
 @Override
 public int corpusDocFrequencyByTerm(String term) {
   String indexFile = _options._indexPrefix + "/merge.txt";
   try {
     BufferedReader reader = new BufferedReader(new FileReader(indexFile));
     String line;
     while ((line = reader.readLine()) != null) {
       int termDocFren = 0;
       String title = "";
       String data = "";
       Scanner s = new Scanner(line).useDelimiter("\t");
       while (s.hasNext()) {
         title = s.next();
         data = s.next();
       }
       if (title.equals(term)) {
         String[] docs = data.split("\\|");
         termDocFren = docs.length;
       }
       reader.close();
       return termDocFren;
     }
     reader.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return 0;
 }
Пример #30
0
  /**
   * reads faculty list file
   *
   * @return LinkedList<Faculty>
   * @throws FileNotFoundException
   */
  public LinkedList<Faculty> readFacultyList() throws FileNotFoundException {
    FileInputStream fstream = new FileInputStream("facultyList.csv");
    LinkedList<Faculty> facultyList = new LinkedList<Faculty>();
    Scanner input = new Scanner(fstream);
    input.useDelimiter(",");

    try {
      // reads file
      while (input.hasNext()) {
        String firstName = input.next();
        String lastName = input.next();
        String userName = input.next();
        String password = input.next();
        String email = input.next();
        String office = input.next();
        String phoneNumber = input.nextLine();
        // creates faculty member
        Faculty newFaculty =
            new Faculty(userName, password, email, firstName, lastName, office, phoneNumber);

        facultyList.add(newFaculty);
      }
      fstream.close();
    } catch (Exception e) {
      facultyList = null;
    }

    Collections.sort(facultyList);

    return facultyList;
  }