コード例 #1
1
  /**
   * Connects to the remote machine by establishing a tunnel through a HTTP proxy with Basic
   * authentication. It issues a CONNECT request and authenticates with the HTTP proxy with Basic
   * protocol.
   *
   * @param address remote machine to connect to
   * @return a TCP/IP socket connected to the remote machine
   * @throws IOException if an I/O error occurs during handshake (a network problem)
   */
  private Socket authenticateBasic(InetSocketAddress address, ConnectivitySettings cs)
      throws IOException {
    Socket proxy = new Socket(cs.getProxyHost(), cs.getProxyPort());
    BufferedReader r =
        new BufferedReader(
            new InputStreamReader(new InterruptibleInputStream(proxy.getInputStream())));
    DataOutputStream dos = new DataOutputStream(proxy.getOutputStream());

    String username = cs.getProxyUsername() == null ? "" : cs.getProxyUsername();
    String password = cs.getProxyPassword() == null ? "" : String.valueOf(cs.getProxyPassword());
    String credentials = username + ":" + password;
    String basicCookie = Base64Encoder.encode(credentials.getBytes("US-ASCII"));

    dos.writeBytes("CONNECT ");
    dos.writeBytes(address.getHostName() + ":" + address.getPort());
    dos.writeBytes(" HTTP/1.0\r\n");
    dos.writeBytes("Connection: Keep-Alive\r\n");
    dos.writeBytes("Proxy-Authorization: Basic " + basicCookie + "\r\n");
    dos.writeBytes("\r\n");
    dos.flush();

    String line = r.readLine();
    if (sConnectionEstablishedPattern.matcher(line).find()) {
      for (; ; ) {
        line = r.readLine();
        if (line.length() == 0) break;
      }
      return proxy;
    }
    throw new IOException("Basic authentication failed: " + line);
  }
コード例 #2
0
 private static String getConfigurationAsString(final String configArg) throws IOException {
   if (configArg.equalsIgnoreCase("-")) {
     return configArg;
   }
   StringBuilder stringBuilder = new StringBuilder();
   String line;
   String ls = System.getProperty("line.separator");
   if (configArg.startsWith("http")) {
     URL oracle = new URL(configArg);
     BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
     while ((line = in.readLine()) != null) {
       stringBuilder.append(line);
       stringBuilder.append(ls);
     }
     in.close();
   } else {
     File configFile = new File(configArg);
     BufferedReader reader = null;
     try {
       reader = new BufferedReader(new FileReader(configFile));
       while ((line = reader.readLine()) != null) {
         stringBuilder.append(line);
         stringBuilder.append(ls);
       }
     } finally {
       if (reader != null) reader.close();
     }
   }
   return stringBuilder.toString();
 }
コード例 #3
0
  public static void main(String[] args) throws IOException {
    BufferedReader f = new BufferedReader(new FileReader("beads.in"));
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("beads.out")));
    int n = Integer.parseInt(f.readLine());
    String s = f.readLine();
    int max = Integer.MIN_VALUE;

    for (int i = 0; i < n; i++) {
      String straight = s.substring(i + 1) + s.substring(0, i + 1);
      char[] beads = straight.toCharArray();
      int temp = 0;
      char color = ' ';
      for (int j = 0; j < n; j++) {
        char currColor = beads[j];
        if (color == ' ' && currColor != 'w') color = currColor;
        if (currColor == color || currColor == 'w') temp++;
        else break;
      }

      color = ' ';
      for (int j = n - 1; j > -1; j--) {
        char currColor = beads[j];
        if (color == ' ' && currColor != 'w') color = currColor;
        if (currColor == color || currColor == 'w') temp++;
        else break;
      }
      max = Math.max(temp, max);
    }
    if (max > n) max = n;
    out.println(max);
    out.close();
    System.exit(0);
  }
コード例 #4
0
  public void processFile(String inputFileName) {

    try {
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(new FileInputStream(new File(inputFileName))));
      String[] headers = reader.readLine().split(SEPARATOR);

      for (String s : headers) {
        attrByValue.put(s, new HashSet<String>());
      }

      String line = null;
      while ((line = reader.readLine()) != null) {
        String[] columnValues = line.split(SEPARATOR);
        if (columnValues.length != headers.length) {
          System.err.println("There is a huge problem with data file");
        }

        for (int i = 0; i < columnValues.length; i++) {
          attrByValue.get(headers[i]).add(columnValues[i]);
        }
      }

      reader.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #5
0
  /** Metodo que le os clientes de um ficheiro */
  public void lerLocalidades(String fileLocalidades, String fileLigacoes, int nrlocalidades)
      throws FileNotFoundException, IOException {
    BufferedReader readLoc = new BufferedReader(new FileReader(fileLocalidades));
    BufferedReader readLig = new BufferedReader(new FileReader(fileLigacoes));
    int nrligacoes;

    while (readLoc.ready() && nrlocalidades > 0) {

      String linhaLoc = readLoc.readLine();
      StringTokenizer stLoc = new StringTokenizer(linhaLoc, "|");
      nrligacoes = stLoc.countTokens() - 2;
      Localidade localidade = new Localidade(stLoc.nextToken(), stLoc.nextToken());

      while (nrligacoes > 0 && readLig.ready()) {
        String linhaLig = readLig.readLine();
        StringTokenizer stLig = new StringTokenizer(linhaLig, "|");
        stLig.nextToken();
        Ligacao lig =
            new Ligacao(
                stLig.nextToken(),
                Double.valueOf(stLig.nextToken()),
                Double.valueOf(stLig.nextToken()));
        localidade.addLigacao(lig);
        nrligacoes--;
      }
      this.addLocalidade(localidade);
      nrlocalidades--;
    }
    readLoc.close();
    readLig.close();
  }
コード例 #6
0
ファイル: nlp13.java プロジェクト: m-note/100knock2015
  public static void main(String[] args) {
    try {
      BufferedReader br1 =
          new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), "UTF-8"));

      BufferedReader br2 =
          new BufferedReader(new InputStreamReader(new FileInputStream(args[1]), "UTF-8"));

      OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("merge.txt"), "UTF-8");

      String cell1 = br1.readLine();
      String cell2 = br2.readLine();
      while (cell1 != null && cell2 != null) {

        String merge = cell1 + "\t" + cell2;
        System.out.println(merge);
        out.write(merge);
        out.write("\n");
        out.flush();

        cell1 = br1.readLine();
        cell2 = br2.readLine();
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #7
0
  // **********************************************************************************
  //
  // Theoretically, you shouldn't have to alter anything below this point in this file
  //      unless you want to change the color of your agent
  //
  // **********************************************************************************
  public void getConnected(String args[]) {
    try {
      // initial connection
      int port = 3000 + Integer.parseInt(args[1]);
      s = new Socket(args[0], port);
      sout = new PrintWriter(s.getOutputStream(), true);
      sin = new BufferedReader(new InputStreamReader(s.getInputStream()));

      // read in the map of the world
      numNodes = Integer.parseInt(sin.readLine());
      int i, j;
      for (i = 0; i < numNodes; i++) {
        world[i] = new node();
        String[] buf = sin.readLine().split(" ");
        world[i].posx = Double.valueOf(buf[0]);
        world[i].posy = Double.valueOf(buf[1]);
        world[i].numLinks = Integer.parseInt(buf[2]);
        // System.out.println(world[i].posx + ", " + world[i].posy);
        for (j = 0; j < 4; j++) {
          if (j < world[i].numLinks) {
            world[i].links[j] = Integer.parseInt(buf[3 + j]);
            // System.out.println("Linked to: " + world[i].links[j]);
          } else world[i].links[j] = -1;
        }
      }
      currentNode = Integer.parseInt(sin.readLine());

      String myinfo =
          args[2] + "\n" + "0.7 0.45 0.45\n"; // name + rgb values; i think this is color is pink
      // send the agents name and color
      sout.println(myinfo);
    } catch (IOException e) {
      System.out.println(e);
    }
  }
コード例 #8
0
 public void cutPlaylist() throws Exception {
   if (logger.isDebugEnabled()) logger.debug("Cut Playlist.");
   String st;
   PrintWriter pw =
       new PrintWriter(new BufferedWriter(new FileWriter(new File(this.NAME + ".dec"))));
   BufferedReader br = new BufferedReader(new FileReader(new File(this.NAME)));
   if ((st = br.readLine()) != null) {
     String st2[];
     st = new File(st).toURL().toString();
     st2 = st.split("/");
     StringBuffer stb = new StringBuffer(st2[st2.length - 1]);
     StringBuffer stb2 = stb.reverse();
     String st3 = new String(stb2);
     int i = 0;
     while (st3.charAt(i) != '.') i++;
     String a = st3.substring(i + 1, st3.length());
     pw.print(new StringBuffer(a).reverse());
   }
   while ((st = br.readLine()) != null) {
     pw.println();
     String st2[];
     st = new File(st).toURL().toString();
     st2 = st.split("/");
     StringBuffer stb = new StringBuffer(st2[st2.length - 1]);
     StringBuffer stb2 = stb.reverse();
     String st3 = new String(stb2);
     int i = 0;
     while (st3.charAt(i) != '.') i++;
     String a = st3.substring(i + 1, st3.length());
     pw.print(new StringBuffer(a).reverse());
   }
   pw.close();
   br.close();
 }
コード例 #9
0
ファイル: WhereIsTheMarble.java プロジェクト: allegea/UVA
 public static void main(String[] args) throws IOException {
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   int[] marbles;
   HashMap<Integer, Integer> positions;
   int n, m;
   StringTokenizer r;
   int cases = 1;
   StringBuilder output = new StringBuilder();
   while (true) {
     r = new StringTokenizer(in.readLine());
     n = Integer.parseInt(r.nextToken());
     m = Integer.parseInt(r.nextToken());
     if (n == 0 && m == 0) break;
     marbles = new int[n];
     positions = new HashMap<Integer, Integer>();
     for (int i = 0; i < n; i++) marbles[i] = Integer.parseInt(in.readLine());
     Arrays.sort(marbles);
     for (int i = n - 1; i >= 0; i--) positions.put(marbles[i], i + 1);
     output.append("CASE# ").append(cases++).append(":").append("\n");
     for (int i = 0; i < m; i++) {
       n = Integer.parseInt(in.readLine());
       if (positions.containsKey(n))
         output.append(n).append(" found at ").append(positions.get(n)).append("\n");
       else output.append(n).append(" not found").append("\n");
     }
   }
   System.out.print(output);
   in.close();
   System.exit(0);
 }
コード例 #10
0
 public static void main(String[] args) throws IOException {
   BufferedReader in = new BufferedReader(new FileReader("new_years_resolution.txt"));
   PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("resolution.out")));
   int t = Integer.parseInt(in.readLine());
   for (int i = 1; i <= t; i++) {
     StringTokenizer line = new StringTokenizer(in.readLine());
     gp = Integer.parseInt(line.nextToken());
     gc = Integer.parseInt(line.nextToken());
     gf = Integer.parseInt(line.nextToken());
     n = Integer.parseInt(in.readLine());
     p = new int[n];
     c = new int[n];
     f = new int[n];
     for (int j = 0; j < n; j++) {
       line = new StringTokenizer(in.readLine());
       p[j] = Integer.parseInt(line.nextToken());
       c[j] = Integer.parseInt(line.nextToken());
       f[j] = Integer.parseInt(line.nextToken());
     }
     found = false;
     recurse(0, 0, 0, 0);
     out.println("Case #" + i + ": " + (found ? "yes" : "no"));
   }
   in.close();
   out.close();
   System.exit(0);
 }
コード例 #11
0
  public static ProjectParams fromStdIn() throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int numTeams = Integer.parseInt(in.readLine());
    // System.out.println("Reading in " + numTeams + " teams...");

    List<Team> teams = new ArrayList<Team>(numTeams);
    List<Set<Employee>> employees = new ArrayList<Set<Employee>>(NUM_LOCATIONS);
    employees.add(new HashSet<Employee>());
    employees.add(new HashSet<Employee>());

    String currLine = in.readLine();

    // Could use while on readLine(), but this handles empty lines at the end better
    for (int currTeam = 0; currTeam < numTeams; currTeam++) {
      String[] idStrings = currLine.split(" ");
      assert (idStrings.length == 2);

      Employee e1 = Employee.getEmployeeFromId(Integer.parseInt(idStrings[0]));
      Employee e2 = Employee.getEmployeeFromId(Integer.parseInt(idStrings[1]));
      assert (e1 != e2 && !e1.equals(e2));
      employees.get(0).add(e1);
      employees.get(1).add(e2);

      teams.add(new Team(e1, e2));

      currLine = in.readLine();
    }
    in.close();

    assert (teams.size() == uniqueTeams(teams));

    return new ProjectParams(teams, employees);
  }
コード例 #12
0
  public static void processPSOutput(Process psProcess, Processor<String> processor)
      throws IOException {
    @SuppressWarnings({"IOResourceOpenedButNotSafelyClosed"})
    BufferedReader stdOutput =
        new BufferedReader(new InputStreamReader(psProcess.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(psProcess.getErrorStream()));

    try {
      String s;
      stdOutput.readLine(); // ps output header
      while ((s = stdOutput.readLine()) != null) {
        processor.process(s);
      }

      StringBuilder errorStr = new StringBuilder();
      while ((s = stdError.readLine()) != null) {
        errorStr.append(s).append("\n");
      }
      if (errorStr.length() > 0) {
        throw new IllegalStateException("error:" + errorStr.toString());
      }
    } finally {
      stdOutput.close();
      stdError.close();
    }
  }
コード例 #13
0
  // Deze method leest alle vakken in
  public void getCourses() {
    try {
      BufferedReader csvVakkenGegevens =
          new BufferedReader(new FileReader("resources/vakken_roostering.csv"));
      String course;
      csvVakkenGegevens.readLine();

      while ((course = csvVakkenGegevens.readLine()) != null) {
        List<String> gegevensVak = Arrays.asList(course.split(";"));
        String name = gegevensVak.get(0);
        int numberLectures = Integer.parseInt(gegevensVak.get(1));
        int numberWorkgroups = Integer.parseInt(gegevensVak.get(2));
        int maxStudentsGroups = Integer.parseInt(gegevensVak.get(3));
        int numberPracticum = Integer.parseInt(gegevensVak.get(4));
        int maxStudentsPracticum = Integer.parseInt(gegevensVak.get(5));

        List<Student> courseStudents = new ArrayList<Student>();

        Course newCourse =
            new Course(
                name,
                numberLectures,
                numberWorkgroups,
                maxStudentsGroups,
                numberPracticum,
                maxStudentsPracticum,
                courseStudents,
                1);
        courses.add(newCourse);
      }
      csvVakkenGegevens.close();
    } catch (IOException e) {
      System.out.println("File Read Error Course ");
    }
  }
コード例 #14
0
  // Deze method maakt alle studenten aan
  public void getStudents() {
    try {
      BufferedReader csvStudentGegevens =
          new BufferedReader(new FileReader("resources/studenten_roostering.csv"));
      String student;
      csvStudentGegevens.readLine();

      while ((student = csvStudentGegevens.readLine()) != null) {
        List<String> gegevens = Arrays.asList(student.split(";"));
        String lastName = gegevens.get(0);
        String firstName = gegevens.get(1);
        int studentNumber = Integer.parseInt(gegevens.get(2));
        List<String> studentCourses = gegevens.subList(3, gegevens.size());
        List<Activity> studentActivities = new ArrayList<>();
        Student newStudent = new Student(lastName, firstName, studentNumber, studentCourses);
        students.add(newStudent);

        // Voeg student toe aan course
        for (int i = 0; i < courses.size(); i++) {
          Course course = courses.get(i);
          if (studentCourses.contains(course.name)) {
            course.courseStudents.add(newStudent);
          }
        }
      }
      csvStudentGegevens.close();
    } catch (IOException e) {
      System.out.println("File Read Error Students");
    }
  }
コード例 #15
0
  // Deze method leest alle zalen in en bepaald hun capaciteit
  public void getRooms() {
    try {
      BufferedReader csvZaalGegevens =
          new BufferedReader(new FileReader("resources/zalen_roostering.csv"));
      String room;
      csvZaalGegevens.readLine();

      while ((room = csvZaalGegevens.readLine()) != null) {
        List<String> gegevensZaal = Arrays.asList(room.split(";"));
        String roomName = gegevensZaal.get(0);
        int capacity = Integer.parseInt(gegevensZaal.get(1));
        if (capacity > 100) {
          List<Activity> list = new ArrayList<>(25);
          for (int i = 0; i < 25; i++) {
            list.add(null);
          }
          Room newRoom = new Room(roomName, capacity, true, list);
          rooms.add(newRoom);
        } else {
          List<Activity> list = new ArrayList<>(2);
          for (int i = 0; i < 20; i++) {
            list.add(null);
          }
          Room newRoom = new Room(roomName, capacity, false, list);
          rooms.add(newRoom);
        }
      }
      csvZaalGegevens.close();
    } catch (IOException e) {
      System.out.println("File Read Error Rooms");
    }
  }
コード例 #16
0
 public static void main(String[] args) throws IOException {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   N = Integer.parseInt(br.readLine());
   StringTokenizer st = new StringTokenizer(br.readLine());
   for (int i = 1; i <= 200003; i++) SegmentTree[i] = new node();
   for (int i = 1; i <= N; i++) a[i] = Integer.parseInt(st.nextToken());
   build(1, 1, N);
   int M = Integer.parseInt(br.readLine());
   StringBuilder op = new StringBuilder();
   while (M-- > 0) {
     String inp[] = br.readLine().split(" ");
     int type = Integer.parseInt(inp[0]);
     if (type == 1) {
       int left = Integer.parseInt(inp[1]);
       int right = Integer.parseInt(inp[2]);
       int ans = query(1, 1, N, left, right).maxSum;
       op.append(ans).append("\n");
     } else {
       int x = Integer.parseInt(inp[1]);
       int y = Integer.parseInt(inp[2]);
       update(1, 1, N, x, y);
     }
   }
   System.out.println(op);
 }
コード例 #17
0
ファイル: ConfigFile.java プロジェクト: jimtoner/grape
  public ConfigFile(String path) throws IOException {
    filePath = path;
    charset = Charset.forName("UTF-8");
    if (!new File(path).exists()) return;

    Collection<Line> currentLines = globalLines;
    InputStreamReader isr = new InputStreamReader(new FileInputStream(path), charset);
    BufferedReader br = new BufferedReader(isr);
    try {
      String l = br.readLine();
      while (l != null) {
        // 解决跨平台文本文件换行符不同的问题
        while (!l.isEmpty()
            && (l.charAt(l.length() - 1) == '\r' || l.charAt(l.length() - 1) == '\n'))
          l = l.substring(0, l.length() - 1);

        Sector sec = parseSectorName(l);
        if (sec != null) {
          currentLines = sec.lines;
          sectors.add(sec);
        } else {
          Line line = parseLine(l);
          currentLines.add(line);
        }

        l = br.readLine();
      }
    } finally {
      br.close();
      isr.close();
    }
  }
コード例 #18
0
  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();
  }
コード例 #19
0
 public static void main(String[] args) throws IOException {
   BufferedReader f = new BufferedReader(new FileReader("barn1.in"));
   out = new PrintWriter(new BufferedWriter(new FileWriter("barn1.out")));
   StringTokenizer nstr = new StringTokenizer(f.readLine());
   int m = Integer.parseInt(nstr.nextToken());
   int s = Integer.parseInt(nstr.nextToken());
   occupied = new ArrayList<ArrayList<Integer>>();
   occupied.add(new ArrayList<Integer>());
   for (int i = 0; i < s; i++) {
     try {
       nstr = new StringTokenizer(f.readLine());
       occupied.get(0).add(Integer.parseInt(nstr.nextToken()));
     } catch (NullPointerException e) {
       break;
     }
   }
   Collections.sort(occupied.get(0));
   int bound = m - 1;
   if (occupied.get(0).size() - 1 < bound) {
     bound = occupied.get(0).size() - 1;
   }
   for (int i = 0; i < bound; i++) {
     findMaxCut();
   }
   int total = 0;
   int len = occupied.size();
   for (int i = 0; i < len; i++) {
     ArrayList<Integer> arr = occupied.get(i);
     int len2 = arr.size();
     total += arr.get(len2 - 1) - arr.get(0) + 1;
   }
   out.println(total);
   out.close();
   System.exit(0);
 }
コード例 #20
0
ファイル: HelpWindow.java プロジェクト: colombbus/tangara
  private String getTitle(File f) {
    String result = "";
    if (!f.getName().endsWith(".html")) return "not HTML";
    else {
      try {
        BufferedReader reader = new BufferedReader(new FileReader(f));
        String ligne = reader.readLine();
        while (ligne != null && !ligne.contains("<TITLE>") && !ligne.contains("<title>")) {
          ligne = reader.readLine();
        }
        reader.close();
        if (ligne == null) return "No TITLE in page " + f.getName();
        else {
          String fin = "";
          String debut = "";
          if (ligne.contains("</TITLE>")) {
            debut = "<TITLE>";
            fin = "</TITLE>";
          } else if (ligne.contains("</title>")) {
            debut = "<title>";
            fin = "</title>";
          } else return "No title in page " + f.getName();

          int fin_index = ligne.lastIndexOf(fin);
          result = ligne.substring(ligne.indexOf(debut) + 7, fin_index);
          return result;
        }
      } catch (Exception e) {
        LOG.error("Error while reading file " + e);
        return "Error for file " + f.getName();
      }
    }
  }
コード例 #21
0
ファイル: exemplo.java プロジェクト: bellopcl/Glauco
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner ler = new Scanner(System.in);
    System.out.printf("informe o nome do arquivo de texto: \n");
    String nome = ler.nextLine();
    System.out.printf("\nconteudo do arquivo texto");

    try {
      FileReader arq = new FileReader(nome);
      BufferedReader lerArq = new BufferedReader(arq);
      String linha = lerArq.readLine();

      while (linha != null) {
        System.out.printf("%s\n", linha);
        linha = lerArq.readLine();

        String val1 = linha.substring(0, linha.indexOf(','));
        int a = Integer.parseInt(val1);
        String val2 = linha.substring(linha.indexOf(',') + 1, linha.lastIndexOf(','));
        int b = Integer.parseInt(val2);
        String val3 = linha.substring(linha.lastIndexOf(',') + 1, linha.length());
        int c = Integer.parseInt(val3);
        setValida(new ValidaTriangulo(a, b, c));
      }
      arq.close();
    } catch (IOException e) {
      System.out.printf("erra na abertura do arquivo: %s.n", e.getMessage());
    }
    System.out.println();
  }
コード例 #22
0
  public void run() {
    try {
      File f2 = new File(MATCH_LOG_FILE);
      if (f2.exists() && !f2.isDirectory()) {
        matchReader = new BufferedReader(new FileReader(MATCH_LOG_FILE));
        String sCurrentLine;

        for (int i = 0; i < logCount; i++) {
          matchReader.readLine();
        }

        while ((sCurrentLine = matchReader.readLine()) != null) {
          if (sendToBackOffice(sCurrentLine)) {
            System.out.println("Updating log count");
            logWriter = new PrintWriter(new FileWriter("c:\\temp\\countBackOffice.log"));
            logWriter.print(++logCount);
            logWriter.close();
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (matchReader != null) matchReader.close();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
コード例 #23
0
ファイル: TheTwinTowers.java プロジェクト: allegea/UVA
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st;
    int cases = 1;
    while (true) {
      st = new StringTokenizer(in.readLine());
      n = Integer.parseInt(st.nextToken());
      m = Integer.parseInt(st.nextToken());
      if (n == 0 && m == 0) break;
      a = new int[n];
      b = new int[m];
      dp = new int[n + 1][m + 1];
      st = new StringTokenizer(in.readLine());
      for (int i = 0; i < n; i++) {
        a[i] = Integer.parseInt(st.nextToken());
        Arrays.fill(dp[i], -1);
      }
      Arrays.fill(dp[n], -1);
      st = new StringTokenizer(in.readLine());
      for (int i = 0; i < m; i++) b[i] = Integer.parseInt(st.nextToken());

      System.out.println("Twin Towers #" + cases);
      System.out.println("Number of Tiles : " + LCS(0, 0));
      System.out.println();
      cases++;
    }
    in.close();
    System.exit(0);
  }
コード例 #24
0
ファイル: Chart.java プロジェクト: feihugis/NetCDF
  public Chart(String filename) {
    try {
      // Get Stock Symbol
      this.stockSymbol = filename.substring(0, filename.indexOf('.'));

      // Create time series
      TimeSeries open = new TimeSeries("Open Price", Day.class);
      TimeSeries close = new TimeSeries("Close Price", Day.class);
      TimeSeries high = new TimeSeries("High", Day.class);
      TimeSeries low = new TimeSeries("Low", Day.class);
      TimeSeries volume = new TimeSeries("Volume", Day.class);

      BufferedReader br = new BufferedReader(new FileReader(filename));
      String key = br.readLine();
      String line = br.readLine();
      while (line != null && !line.startsWith("<!--")) {
        StringTokenizer st = new StringTokenizer(line, ",", false);
        Day day = getDay(st.nextToken());
        double openValue = Double.parseDouble(st.nextToken());
        double highValue = Double.parseDouble(st.nextToken());
        double lowValue = Double.parseDouble(st.nextToken());
        double closeValue = Double.parseDouble(st.nextToken());
        long volumeValue = Long.parseLong(st.nextToken());

        // Add this value to our series'
        open.add(day, openValue);
        close.add(day, closeValue);
        high.add(day, highValue);
        low.add(day, lowValue);

        // Read the next day
        line = br.readLine();
      }

      // Build the datasets
      dataset.addSeries(open);
      dataset.addSeries(close);
      dataset.addSeries(low);
      dataset.addSeries(high);
      datasetOpenClose.addSeries(open);
      datasetOpenClose.addSeries(close);
      datasetHighLow.addSeries(high);
      datasetHighLow.addSeries(low);

      JFreeChart summaryChart = buildChart(dataset, "Summary", true);
      JFreeChart openCloseChart = buildChart(datasetOpenClose, "Open/Close Data", false);
      JFreeChart highLowChart = buildChart(datasetHighLow, "High/Low Data", true);
      JFreeChart highLowDifChart =
          buildDifferenceChart(datasetHighLow, "High/Low Difference Chart");

      // Create this panel
      this.setLayout(new GridLayout(2, 2));
      this.add(new ChartPanel(summaryChart));
      this.add(new ChartPanel(openCloseChart));
      this.add(new ChartPanel(highLowChart));
      this.add(new ChartPanel(highLowDifChart));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #25
0
ファイル: chalice.java プロジェクト: p473lr/i-urge-mafia-gear
  public static void main(String[] args) throws IOException, FileNotFoundException {
    FileReader file = new FileReader("chalice.in");
    BufferedReader reader = new BufferedReader(file);

    int cases =
        Integer.parseInt(reader.readLine()); // Input the number of cases and store it in cases
    for (int i = 0; i < cases; i++) { // Loop through all the cases
      int weight =
          Integer.parseInt(
              reader.readLine()); // Input the weight of the accused and store it in weight

      int geese =
          Integer.parseInt(reader.readLine()); // Input the number of geese and store it in geese
      int sum = 0; // Stores the total weight of the flock of geese
      StringTokenizer tokens =
          new StringTokenizer(
              reader.readLine()); // Read in the line with the weight of the geese and tokenize it
      for (int j = 0; j < geese; j++) { // Loop through all the geese
        sum +=
            Integer.parseInt(
                tokens.nextToken()); // Add the weight of one goose to the weight of the flock
      }

      System.out.print("Trial #" + (i + 1) + ": "); // Output trial number

      // Based on weight comparison output whether she is or isn't a witch
      if (weight <= sum) System.out.println("SHE'S A WITCH! BURN HER!");
      else System.out.println("She's not a witch. BURN HER ANYWAY!");
    }
  }
コード例 #26
0
ファイル: CryptFile.java プロジェクト: helma-next/helma-next
  private synchronized void readFile() {
    BufferedReader reader = null;

    this.users = new Properties();

    try {
      reader = new BufferedReader(new FileReader(this.file));

      String line = reader.readLine();

      while (line != null) {
        StringTokenizer st = new StringTokenizer(line, ":"); // $NON-NLS-1$

        if (st.countTokens() > 1) {
          this.users.put(st.nextToken(), st.nextToken());
        }

        line = reader.readLine();
      }
    } catch (Exception ignore) {
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (Exception x) {
        }
      }

      this.lastRead = System.currentTimeMillis();
    }
  }
コード例 #27
0
  public static void main(String args[]) throws Exception {
    BufferedReader in = new BufferedReader(new FileReader("important.in"));
    PrintWriter out = new PrintWriter("important.out");

    int n = rInt(in.readLine(), 1, MaxN);

    boolean[] t = new boolean[26];

    for (int i = 0; i < n; i++) {
      String s = in.readLine();
      if (s.length() > MaxL) throw new Exception("String is too long");
      char f = checkFormula(s.trim());
      t[f - 'A'] = true;
    }
    ;

    out.println("Yes");

    boolean flag = false;
    for (int i = 0; i < 26; i++)
      if (t[i]) {
        if (flag) out.print(" | ");
        String let = "" + (char) (i + 'A');
        out.print(let + " | ~" + let);
        flag = true;
      }
    ;

    out.close();
  };
コード例 #28
0
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String[] str;
    str = in.readLine().split(" ");
    int N = Integer.parseInt(str[0]);

    long[] A = new long[N];
    long[] B = new long[N];
    long[] C = new long[N];
    long[] D = new long[N];
    for (int i = 0; i < N; i++) {
      str = in.readLine().split(" ");
      A[i] = Long.parseLong(str[0]);
      B[i] = Long.parseLong(str[1]);
      C[i] = Long.parseLong(str[2]);
      D[i] = Long.parseLong(str[3]);
    }

    long[] CD = new long[N * N];
    for (int i = 0; i < N; i++) {
      for (int j = 0; j < N; j++) {
        CD[i * N + j] = C[i] + D[j];
      }
    }
    Arrays.sort(CD);
    long count = 0;
    for (int i = 0; i < N; i++) {
      for (int j = 0; j < N; j++) {
        long sum = A[i] + B[j];
        count += upperbound(CD, -sum) - lowerbound(CD, -sum) + 1;
      }
    }
    System.out.println(count);
  }
  public static void main(String[] args) throws Exception {

    /*  BufferedReader br=new BufferedReader(new FileReader("input.txt"));
        BufferedWriter out=new BufferedWriter(new FileWriter("output.txt"));
    */
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 2000);
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out), 2000);
    String[] s = br.readLine().split(" ");
    int n = Integer.parseInt(s[0]);
    int q = Integer.parseInt(s[1]);
    int num[] = new int[n + 1];
    int[] m = new int[3 * n + 1]; // size = 2*n+1
    Arrays.fill(num, -1);
    s = br.readLine().split(" ");
    for (int i = 1; i <= n; i++) num[i] = Integer.parseInt(s[i - 1]);
    /// build tree
    maketree(1, 1, n, m, num);

    for (int qq = 1; qq <= q; qq++) {
      s = br.readLine().split(" ");
      int i = Integer.parseInt(s[0]);
      int j = Integer.parseInt(s[1]);
      int ans = query(1, 1, n, m, num, i, j);
      out.write("" + num[ans] + "\n");
      out.flush();
    }
  }
コード例 #30
0
ファイル: Main.java プロジェクト: AaskaShah/Java-Programs
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String[] x = in.readLine().trim().split(" ");
    int n = Integer.parseInt(x[0]);
    int t = Integer.parseInt(x[1]);
    int count = 0;

    int[] a = new int[n * t];
    int dp[] = new int[n];
    x = in.readLine().trim().split(" ");
    for (int i = 0; i < n * t; i++) {
      if (i < n) a[i] = Integer.parseInt(x[i]);
      else {
        a[n * (i / n)] = a[i % n];
      }
    }
    for (int i = 1; i < n * t; i++) {

      dp[i] = dp[i - 1];
      if (a[i] > a[i - 1]) dp[i]++;
      else {
        dp[i] = 0;
      }
    }

    System.out.println();
  }