/**
   * 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)));
      }
    }
  }
Example #2
0
  /**
   * Opens a file. If the file can be opened, get a drawing time estimate, update recent files list,
   * and repaint the preview tab.
   *
   * @param filename what file to open
   */
  public void LoadGCode(String filename) {
    CloseFile();

    try {
      Scanner scanner = new Scanner(new FileInputStream(filename));
      linesTotal = 0;
      gcode = new ArrayList<String>();
      try {
        while (scanner.hasNextLine()) {
          gcode.add(scanner.nextLine());
          ++linesTotal;
        }
      } finally {
        scanner.close();
      }
    } catch (IOException e) {
      Log("<span style='color:red'>File could not be opened.</span>\n");
      RemoveRecentFile(filename);
      return;
    }

    previewPane.setGCode(gcode);
    fileOpened = true;

    EstimateDrawTime();
    UpdateRecentFiles(filename);
    Halt();
  }
  public static int[] getTextDims(Graphics2D g, Font f, String s) {

    // [0] == max width of all lines
    // [1] == total height
    int[] textDims = new int[2];

    FontMetrics fm = g.getFontMetrics(f);
    int lineH = fm.getAscent();

    Scanner lineSplitter = new Scanner(s);
    int maxW = -1;
    int lineCounter = 0;
    while (lineSplitter.hasNextLine()) {
      String line = lineSplitter.nextLine();
      int w = fm.stringWidth(line);
      if (w > maxW) {
        maxW = w;
      }
      lineCounter++;
    }
    int h = lineH * lineCounter;

    textDims[0] = maxW;
    textDims[1] = h;
    return textDims;
  }
Example #4
0
 /*setup the game */
 private void setup() {
   t0 = System.currentTimeMillis(); /*Times the beginning of the game */
   // int size;
   Scanner in = new Scanner(System.in);
   // System.out.println("Enter the size of available");
   // size = in.nextInt();
   initiateScores();
   placeWalls();
   placeStates();
   placeLabels();
   randomizeOrderRent(); /*randomizes the order of the equipment for the On Rent state */
   System.out.println(
       "How many High Runners at price $" + EQUIPMENTCOSTS[0] + " do you want to buy?");
   int type1Equip = in.nextInt();
   System.out.println(
       "How many Medium Runners at price $" + EQUIPMENTCOSTS[1] + " do you want to buy?");
   int type2Equip = in.nextInt();
   System.out.println(
       "How many Low Runners at price $" + EQUIPMENTCOSTS[2] + " do you want to buy?");
   int type3Equip = in.nextInt();
   capitalInvested =
       EQUIPMENTCOSTS[0] * type1Equip
           + EQUIPMENTCOSTS[1] * type2Equip
           + EQUIPMENTCOSTS[2] * type3Equip;
   capitalLabel.setLabel("Capital Invested: $" + capitalInvested);
   fillAvailable(type1Equip, type2Equip, type3Equip); // fills with the proper number of equipment
   // fillStates(size,INITRENT,INITSHOP);
   placeEquipments();
 }
Example #5
0
 public static String requestName() {
   Scanner keyboard = new Scanner(System.in);
   System.out.print("Name: ");
   String name = keyboard.nextLine();
   keyboard.close();
   return name;
 }
Example #6
0
  public static void main(String[] args) throws IOException {

    // First reads in the lines from the .txt file.  The first and second lines determine the start
    // and ending point of the maze.
    // The rest of the lines give the locations of the corners of each convex polygon in the maze.

    //        Example map input:
    //        1, 3
    //        34, 19
    //        0, 14; 6, 19; 9, 15; 7, 8; 1, 9
    //        2, 6; 17, 6; 17, 1; 2, 1
    //        12, 15; 14, 8; 10, 8
    //        14, 19; 18, 20; 20, 17; 14, 13
    //        18, 10; 23, 6; 19, 3
    //        22, 19; 28, 19; 28, 9; 22, 9
    //        25, 6; 29, 8; 31, 6; 31, 2; 28, 1; 25, 2
    //        31, 19; 34, 16; 32, 8; 29, 17

    // Open specified text file
    List<String> list = new ArrayList<String>();
    File library = new File(args[0]);
    Scanner sc = new Scanner(library);

    // Reads in every line of the text file
    // creates a new String for every line, then adds it to an arraylist
    while (sc.hasNextLine()) {
      String line;
      line = sc.nextLine();
      list.add(line);
    }

    // Takes the first and second lines as the start and goal points
    int count = 0;

    sPoint = list.get(0);
    ePoint = list.get(1);

    sPoint = sPoint.replace(" ", "");
    ePoint = ePoint.replace(" ", "");

    // remove the first line from the polygon list
    list.remove(0);

    // Create a 2 element array for the start point
    String[] Starter = sPoint.split(",");
    String[] Ender = ePoint.split(",");
    Startx = Double.parseDouble(Starter[0]);
    Starty = Double.parseDouble(Starter[1]);

    Polygon[] FinalPolygons = ListPolygons(list);

    // Text Graph of the polygon maze and the Start/End points
    graph(FinalPolygons);

    // A* search algorithm is performed to find the shortest path
    AStarSearch(FinalPolygons);
  }
Example #7
0
 // Reads name popularity rank data from text file into HashMap
 public void readRankData(Scanner input) {
   while (input.hasNextLine()) {
     String dataLine = input.nextLine();
     Person entry = new Person(dataLine);
     Scanner tokens = new Scanner(dataLine);
     String nameGender = tokens.next();
     nameGender += tokens.next();
     persons.put(nameGender, entry);
   }
 }
Example #8
0
 public static void main(String[] args) {
   int a, b, c;
   Scanner reader = new Scanner(System.in);
   System.out.print("请输入两个整数:");
   a = reader.nextInt();
   b = reader.nextInt();
   GcdLcm o = new GcdLcm();
   c = o.getGcd(a, b);
   System.out.println("gcd(" + a + "," + b + ")=" + c);
   System.out.println("lcm(" + a + "," + b + ")=" + (a * b) / c);
 }
Example #9
0
 public static String data(String name) throws FileNotFoundException {
   File names = new File("C:\\Users\\JCrissey97\\Desktop\\HighlineJava1\\Assignment6\\names.txt");
   Scanner scanNames = new Scanner(names);
   String find = name.trim().toLowerCase() + " ";
   String info = "";
   while (scanNames.hasNext()) {
     info = scanNames.nextLine();
     if (info.startsWith(find.substring(0, 1).toUpperCase() + find.substring(1))) break;
   }
   scanNames.close();
   return info;
 }
Example #10
0
 public static String meanings(String name) throws FileNotFoundException {
   File meaningsFile =
       new File("C:\\Users\\JCrissey97\\Desktop\\HighlineJava1\\Assignment6\\meanings.txt");
   Scanner scanMeanings = new Scanner(meaningsFile);
   String find = name.trim().toUpperCase() + " ";
   String meaning = "";
   while (scanMeanings.hasNext()) {
     meaning = scanMeanings.nextLine();
     if (meaning.startsWith(find)) break;
   }
   scanMeanings.close();
   return meaning;
 }
 public void readFile(String name) { // reads the file and puts everything in the stats list
   Scanner inFile = null;
   stats = new ArrayList<String>();
   chars = new ArrayList<String>();
   powerUps = new ArrayList<String>();
   try {
     inFile = new Scanner(new BufferedReader(new FileReader(name + ".txt")));
     while (inFile.hasNextLine()) {
       stats.add(inFile.nextLine());
     }
   } catch (IOException ex) {
     System.out.println("Did you forget to make the" + name + ".txt file?");
   }
 }
Example #12
0
 public CartesianPanel() {
   double data[];
   Scanner in = new Scanner(System.in);
   int rangeAtas[];
   int rangeBawah[];
   xCoordNumbers = in.nextInt();
   int variabelLinguistik = in.nextInt();
   std = new double[variabelLinguistik];
   sig = new int[variabelLinguistik];
   nilaiAwal = new int[variabelLinguistik];
   nilaiAkhir = new int[variabelLinguistik];
   int temp = 0;
   while (temp < variabelLinguistik) {
     int n = in.nextInt();
     data = new double[n];
     int t = 0;
     while (t < n) {
       data[t] = in.nextDouble();
       t++;
     }
     nilaiAwal[temp] = in.nextInt();
     nilaiAkhir[temp] = in.nextInt();
     std[temp] = findSTDEV(data);
     sig[temp] = (int) (nilaiAkhir[temp] + nilaiAwal[temp]) / 2;
     // System.out.println(nilaiAwal[temp]+" "+nilaiAkhir[temp]+" "+std[temp]+" "+sig[temp]);
     temp++;
   }
   this.alfa = in.nextDouble();
   // this.alfa = alfa;
   // this.xCoordNumbers = nilaiAkhir[temp-1];
   // this.nilaiAwal = rangeAtas;
   // System.out.println(alfa);
   this.jumlahGrafik = variabelLinguistik;
 }
Example #13
0
  public static void main(String[] args) {
    System.out.println("Hello World!");

    Scanner input = new Scanner(System.in);

    System.out.print("Enter a number: ");
    double number1 = input.nextDouble();

    System.out.print("Enter second number: ");
    double number2 = input.nextDouble();

    double product = number1 * number2;
    System.out.printf("The product of both numbers is: %f", product);
  }
Example #14
0
  public static void main(String[] args) {
    // read arguments and respond correctly
    File in;
    File out;
    String tileDirectory;
    if (args.length == 0 || args.length > 2) {
      in = null;
      out = null;
      tileDirectory = "";
      System.err.println("Incorrect number of arguments. Required: Filename (tileset path)");
      System.exit(0);
    } else if (args.length == 1) { // load old file
      in = new File(args[0]);
      out = in;
      Scanner s = null;
      try {
        s = new Scanner(in);
      } catch (FileNotFoundException e) {
        System.out.println("Could not find input file.");
        System.exit(0);
      }
      tileDirectory = s.nextLine();
    } else {
      in = null;
      out = new File(args[0]);
      tileDirectory = args[1];
      try {
        File f = new File(tileDirectory);
        if (!f.isDirectory()) {
          throw new IOException("Tileset does not exist");
        }
      } catch (IOException e) {
        System.err.println(e);
        System.out.println("This error is likely thanks to an invalid tileset path");
        System.exit(0);
      }
    }

    MapBuilder test = new MapBuilder("Map Editor", in, out, tileDirectory);

    // Build GUI
    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            test.CreateAndDisplayGUI();
          }
        });
  }
Example #15
0
  public Map loadMap(File input) throws FileNotFoundException {
    Scanner s = new Scanner(input);
    tileDir = s.nextLine();
    int width = s.nextInt();
    int height = s.nextInt();
    Map toReturn = new Map(width, height, tileDir);
    s.nextLine(); // eat up rest of line.
    for (int y = 0; y < height; y++) {
      String line = s.nextLine();
      Scanner lineReader = new Scanner(line);
      List<Tile> tList = new ArrayList<Tile>();
      for (int x = 0; x < width; x++) {
        String[] values = lineReader.next().split("/");
        String name = values[0];
        int[] picLocation = new int[2];
        for (int i = 0; i < picLocation.length; i++) {
          picLocation[i] = Integer.parseInt(values[1].split("_")[i]);
        }
        ImageIcon img = null;
        try {
          img = new ImageIcon(getTile(tileDir, picLocation[0], picLocation[1], DISPLAY_SCALE));
        } catch (IOException e) {
          System.out.println("Could not find image.");
          img =
              new ImageIcon(
                  new BufferedImage(
                      TILE_SIZE * DISPLAY_SCALE,
                      TILE_SIZE * DISPLAY_SCALE,
                      BufferedImage.TYPE_INT_RGB));
        }
        int avoid = Integer.parseInt(values[2]);
        int def = Integer.parseInt(values[3]);
        String[] movString = values[4].split(",");
        int[] moveCost = new int[movString.length];
        for (int i = 0; i < moveCost.length; i++) {
          moveCost[i] = Integer.parseInt(movString[i]);
        }
        String special = values[5];

        Tile t =
            new Tile(
                img,
                name,
                avoid,
                def,
                moveCost,
                special,
                true,
                "" + picLocation[0] + "_" + picLocation[1]);
        tList.add(t);
        t.setMaximumSize(new Dimension(TILE_SIZE * DISPLAY_SCALE, TILE_SIZE * DISPLAY_SCALE));
        t.setPreferredSize(new Dimension(TILE_SIZE * DISPLAY_SCALE, TILE_SIZE * DISPLAY_SCALE));
        t.addMouseListener(new MapButtonListener());
      }
      toReturn.addRow(tList);
    }
    return toReturn;
  }
Example #16
0
  protected void initUI() {
    File f = new File("Top100");
    String Str;
    String WORDS[] = new String[100];
    int FREQ[] = new int[100];
    String shuffle[] = new String[100];
    ArrayList<String> shuffling = new ArrayList<String>();
    int count = 0, i, temp = 1000000;
    try {
      Scanner br = new Scanner(f);

      while (br.hasNextLine()) {
        Str = br.nextLine();
        shuffling.add(Str);
      }
      br.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    Collections.shuffle(shuffling);
    for (String str : shuffling) {

      WORDS[count] = str.substring(0, str.indexOf(' '));
      FREQ[count] = Integer.parseInt(str.substring(str.indexOf(' ') + 1, str.length()));
      if (FREQ[count] < temp) temp = FREQ[count];
      count++;
    }
    JFrame frame = new JFrame(TestOpenCloud.class.getSimpleName());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    // Cloud cloud = new Cloud();
    Random random = new Random();
    for (i = 0; i < 100; i++) {

      final int red = (int) (Math.random() * 150);
      final int green = (int) (Math.random() * 150);
      final int blue = (int) (Math.random() * 150);
      final JLabel label = new JLabel(WORDS[i]);
      label.setOpaque(false);
      label.setFont(new Font("Andalus", Font.PLAIN, ((FREQ[i] * 11) / temp)));
      Color color = new Color(red, green, blue);
      label.setForeground(color);
      panel.add(label);
    }
    frame.add(panel);
    frame.setSize(1366, 768);
    frame.setVisible(true);
  }
  /** Display the file in the text area */
  private void showFile() {
    Scanner input = null;
    try {
      // Use a Scanner to read text from the file
      input = new Scanner(new File(jtfFilename.getText().trim()));

      // Read a line and append the line to the text area
      while (input.hasNext()) jtaFile.append(input.nextLine() + '\n');
    } catch (FileNotFoundException ex) {
      System.out.println("File not found: " + jtfFilename.getText());
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (input != null) input.close();
    }
  }
Example #18
0
  public TreeViewer(String title, int ulx, int uly, int pw, int ph) {
    super(title, ulx, uly, pw, ph);

    // code to initialize instance variables before animation begins:
    // ------------------------------------------------------------------

    state = "regular";

    spread = 1;
    levelHeight = 10; // 10 levels for the camera region height

    tree = new SackBST();
    String fileName = FileBrowser.chooseFile(true);

    try {
      Scanner input = new Scanner(new File(fileName));
      String s;

      while (input.hasNext()) {
        s = input.nextLine();
        if (s != null) {
          tree.add(s);
        }
      }

      input.close();
    } catch (Exception e) {
      System.out.println("File load failed");
      System.exit(1);
    }

    // code to finish setting up entire window:
    // ------------------------------------------------------------------

    setBackgroundColor(new Color(128, 128, 200));

    // code to set up camera(s)
    // ------------------------------------------------------------------

    cameras.add(new Camera(10, 50, camw, camh, 0, 100, 0, new Color(255, 200, 255)));

    cameras.add(new Camera(10, 50 + camh + 10, camw, 20, 0, 100, 0, new Color(255, 255, 255)));

    // ------------------------------------------------------------------
    // start up the animation:
    super.start();
  }
Example #19
0
  // Constructor
  public Ballot(int index, int ID, int numCandidates, String title, ArrayList<String> candidates)
      throws IOException {
    _index = index;
    _ID = ID;
    _numCandidates = numCandidates;
    _votes = new int[_numCandidates];
    _title = title;
    _candidates = candidates;
    _usrVotes = new String[numCandidates];

    // if the ballot file already exists, read in the votes for that ballot
    // otherwise the number of votes for each candidate will default to 0
    file = new File(_ID + ".txt");
    if (file.exists()) {
      Scanner reader = new Scanner(file);
      int i = 0;
      while (reader.hasNextLine()) {
        String strLine = reader.nextLine();
        String arrLine[] = strLine.split(":");
        int vote = Integer.parseInt(arrLine[1]);
        _votes[i] = vote;

        i++;
      }
      reader.close();
    }

    _ballotPanel = new JPanel();
    _ballotPanel.setLayout(new GridLayout(_candidates.size() + 1, 1));

    _titleLabel = new JLabel(_title);
    _titleLabel.setHorizontalAlignment(JLabel.CENTER);
    _titleLabel.setFont(new Font("CourierNew", Font.PLAIN, 15));
    _ballotPanel.add(_titleLabel);

    for (int i = 0; i < _candidates.size(); i++) {
      // Make a JButton for each candidate in the ballot
      // Disable it by default. Will enable when the user logs in
      String cText = _candidates.get(i);
      JButton candidate = new JButton(cText);
      candidate.setEnabled(false);
      candidate.addActionListener(_buttonListener);

      _candidateButtons.add(candidate);
      _ballotPanel.add(candidate);
    }
  }
Example #20
0
  /**
   * Loads into a double[][] a plain text file of numbers, with newlines dividing the numbers into
   * rows and tabs or spaces delimiting columns. The Y dimension is not flipped.
   */
  public static double[][] loadTextFile(InputStream stream) throws IOException {
    Scanner scan = new Scanner(stream);

    ArrayList rows = new ArrayList();
    int width = -1;

    while (scan.hasNextLine()) {
      String srow = scan.nextLine().trim();
      if (srow.length() > 0) {
        int w = 0;
        if (width == -1) // first time compute width
        {
          ArrayList firstRow = new ArrayList();
          Scanner rowScan = new Scanner(new StringReader(srow));
          while (rowScan.hasNextDouble()) {
            firstRow.add(new Double(rowScan.nextDouble())); // ugh, boxed
            w++;
          }
          width = w;
          double[] row = new double[width];
          for (int i = 0; i < width; i++) row[i] = ((Double) (firstRow.get(i))).doubleValue();
          rows.add(row);
        } else {
          double[] row = new double[width];
          Scanner rowScan = new Scanner(new StringReader(srow));
          while (rowScan.hasNextDouble()) {
            if (w == width) // uh oh
            throw new IOException("Row lengths do not match in text file");
            row[w] = rowScan.nextDouble();
            w++;
          }
          if (w < width) // uh oh
          throw new IOException("Row lengths do not match in text file");
          rows.add(row);
        }
      }
    }

    if (width == -1) // got nothing
    return new double[0][0];

    double[][] fieldTransposed = new double[rows.size()][];
    for (int i = 0; i < rows.size(); i++) fieldTransposed[i] = ((double[]) (rows.get(i)));

    // now transpose because we have width first
    double[][] field = new double[width][fieldTransposed.length];
    for (int i = 0; i < field.length; i++)
      for (int j = 0; j < field[i].length; j++) field[i][j] = fieldTransposed[j][i];

    return field;
  }
Example #21
0
 public static void bars(DrawingPanel panel, String nameInfo) {
   Graphics g = panel.getGraphics();
   Scanner s = new Scanner(nameInfo);
   s.next(); // skips name
   String gender = s.next();
   for (int i = startYear; i <= 2010; i += 10) {
     g.setColor(Color.BLACK);
     int rank = s.nextInt();
     int x = ((decadeWidth / 10) * (i - startYear));
     int y = 30 + (rank / 2);
     if (rank == 0) y = 560 - bannerHeight;
     g.drawString("" + rank, x, y);
     if (gender.equals("f")) g.setColor(Color.pink);
     else g.setColor(Color.blue);
     g.fillRect(x, y, decadeWidth / 2, 560 - bannerHeight - y);
   }
   s.close();
 }
 @Override
 public StringBuilder doInBackground() throws IOException, InterruptedException {
   int lineNumber = 0;
   try (Scanner in = new Scanner(new FileInputStream(file))) {
     while (in.hasNextLine()) {
       String line = in.nextLine();
       lineNumber++;
       text.append(line);
       text.append("\n");
       ProgressData data = new ProgressData();
       data.number = lineNumber;
       data.line = line;
       publish(data);
       Thread.sleep(1); // to test cancellation; no need to do this
       // in your programs
     }
   }
   return text;
 }
  // main(): application entry point
  public void disp(String args) {
    // set up scanner
    Scanner scan = new Scanner(System.in);

    // display program's purpose
    System.out.println(
        "This program will draw a Sierpinski Fractal to the user's specified depth.\n");

    // determine desired cycles and color
    System.out.println(
        "How many cycles would you like the Sierpinski Fractal to be taken out to?\n");
    int a = scan.nextInt();
    System.out.println();

    // produce Sierpinski Fractal
    Point p1 = new Point(50, 50);
    Point p2 = new Point(50, 450);
    Point p3 = new Point(450, 50);
    // Color c =new
    // Color((int)((Math.random()*20000)%256),(int)((Math.random()*10000)%256),(int)((Math.random()*30000)%256));
    Color c = Color.BLACK;
    JFrame window = new JFrame("Sierpinski Fractal-" + a + ".");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setSize(500, 500);
    window.setVisible(true);

    Graphics g = window.getGraphics();
    Graphics2D g2d = (Graphics2D) g;
    // Container con=getContentPane();
    // con.setBackground(Color.BLACK);

    // g2d.setBackground(Color.BLACK);
    System.out.println("\nEnter any character when ready.\n");
    Scanner stdin = new Scanner(System.in);
    stdin.nextLine();

    Sierpinski(g, p1, p2, p3, c, a);
    System.out.println("\nEnter any character if you wish to exit!\n");
    stdin = new Scanner(System.in);
    stdin.nextLine();
    System.exit(0);
  }
Example #24
0
  // Loads a Player class
  public void loadPlayer(String file) {
    try {
      Scanner data = new Scanner(new BufferedReader(new FileReader(file + ".txt")));
      level = Integer.parseInt(data.next());
      String charinf = data.next();

      ArrayList<Item> previtems = new ArrayList<Item>();
      while (data.hasNext()) {
        previtems.add(new Item(data.next()));
      }

      player =
          new Creature(
              min(40 + level * 3 / 5, 100) / 2,
              min(40 + level * 3 / 5, 100) / 2,
              charinf,
              previtems);
    } catch (Exception ex) {
      System.out.println(ex);
    }
  }
Example #25
0
  /**
   * Makes a POST request and returns the server response.
   *
   * @param urlString the URL to post to
   * @param nameValuePairs a map of name/value pairs to supply in the request.
   * @return the server reply (either from the input stream or the error stream)
   */
  public static String doPost(String urlString, Map<String, String> nameValuePairs)
      throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());

    boolean first = true;
    for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
      if (first) first = false;
      else out.print('&');
      String name = pair.getKey();
      String value = pair.getValue();
      out.print(name);
      out.print('=');
      out.print(URLEncoder.encode(value, "UTF-8"));
    }

    out.close();

    Scanner in;
    StringBuilder response = new StringBuilder();
    try {
      in = new Scanner(connection.getInputStream());
    } catch (IOException e) {
      if (!(connection instanceof HttpURLConnection)) throw e;
      InputStream err = ((HttpURLConnection) connection).getErrorStream();
      if (err == null) throw e;
      in = new Scanner(err);
    }

    while (in.hasNextLine()) {
      response.append(in.nextLine());
      response.append("\n");
    }

    in.close();
    return response.toString();
  }
Example #26
0
  public void readFile() throws IOException, FileNotFoundException {
    Scanner inp = new Scanner(System.in);
    System.out.print("Enter the name of the file to process:  ");
    String file;
    file = inp.nextLine();
    System.out.println(file);
    Scanner fileScan = new Scanner(new FileReader(file));
    fileScan.useDelimiter(",");

    numBars = fileScan.nextInt();
    values = new int[numBars];
    labels = new String[numBars];
    for (int i = 0; i < numBars - 1; i++) {
      values[i] = fileScan.nextInt();
      labels[i] = fileScan.next();
      System.out.println(values[i] + " " + labels[i]);
    }
    inp.close();
    fileScan.close();
  }
  private String getFileWords(String s) {
    String output = "";
    try {
      // THIS CODE SEGMENT WILL NOT RUN IN AN APPLET THAT IS NOT "SIGNED"
      // By default applets cannot alter files on the hard drive of the user.
      // If the panel is opened in a regular application the save button should work.
      // This can be tested in HomeworkApplication.java through HomeworkRun.java only

      File inputFile = new File(s);
      Scanner inputScanner = new Scanner(inputFile);

      while (inputScanner.hasNext()) {
        output = output + inputScanner.nextLine() + "\n";
      }

      inputScanner.close();
      String numWords = getWords(output);
      return numWords;
    } catch (IOException e) {
      outputLabel.append(e + "");
    }

    return output;
  }
Example #28
0
 public void fileScan(String filename) throws IOException {
   Scanner sf = new Scanner(new File(filename));
   int maxIndex = -1;
   String s = "";
   while (sf.hasNext()) {
     maxIndex++;
     s = sf.nextLine();
     dtr[maxIndex] = s;
     odtr[maxIndex] = s;
     s = sf.nextLine();
     d1[maxIndex] = s;
     od1[maxIndex] = s;
     d2[maxIndex] = sf.nextLine();
     d3[maxIndex] = sf.nextLine();
     d4[maxIndex] = sf.nextLine();
   }
   sf.close();
 }
  public void parseInput(String file, int threads, int limit)
      throws FileNotFoundException, InterruptedException {
    // long startParseTime = System.currentTimeMillis();
    m_jgAdapter = new JGraphModelAdapter<Position, DefaultEdge>(graph);
    jgraph = new JGraph(m_jgAdapter);
    this.threads = threads;

    Scanner input = new Scanner(new File(file));
    try {
      for (int r = 0; input.hasNextLine() && r < limit; r++) {
        Scanner line = new Scanner(input.nextLine());
        try {

          ArrayList<Position> row = new ArrayList<Position>();
          grid.add(row);

          System.out.println("Row " + r);

          for (int c = 0; line.hasNextInt() && c < limit; c++) {
            Position position = new Position(r, c, line.nextInt());
            row.add(position);
            graph.addVertex(position);
            positionVertexAt(position, position.column * 5, position.row * 5);
          }
        } finally {
          line.close();
        }
      }
    } finally {
      input.close();
    }

    graphGrid(grid);

    // ArrayList<ArrayList<Position>> grid2 = transpose(grid);
    // outputGrid(grid2);

  }
  private void insertRows(Connection connection) {
    // Build the SQL INSERT statement
    String sqlInsert = "insert into " + jtfTableName.getText() + " values (";

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

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

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

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

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

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

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

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

        statement.executeBatch();

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

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