Example usage for java.util Scanner hasNext

List of usage examples for java.util Scanner hasNext

Introduction

In this page you can find the example usage for java.util Scanner hasNext.

Prototype

public boolean hasNext() 

Source Link

Document

Returns true if this scanner has another token in its input.

Usage

From source file:eu.cassandra.training.entities.Installation.java

/**
 * This is the parser for the measurement file. It parses through the file and
 * creates the arrays of the active and reactive power consumptions.
 *///from w  ww.  j av a2s  .c  o  m
public void parseMeasurementsFile() throws IOException {

    ArrayList<Double> temp = new ArrayList<Double>();
    ArrayList<Double> temp2 = new ArrayList<Double>();

    String extension = measurementsFile.substring(measurementsFile.length() - 3, measurementsFile.length());

    switch (extension) {

    case "csv":

        boolean startFlag = true;

        File file = new File(measurementsFile);
        Scanner scanner = new Scanner(file);

        int counter = 0;

        while (scanner.hasNext()) {

            String line = scanner.nextLine();
            // System.out.println(line);

            if (startFlag) {
                if (line.split(",")[0].equalsIgnoreCase("1")) {

                    startDate = new DateTime(2012, 01, 01, 00, 00);

                } else {

                    int year = Integer.parseInt(line.split(",")[0].substring(0, 4));
                    int month = Integer.parseInt(line.split(",")[0].substring(4, 6));
                    int day = Integer.parseInt(line.split(",")[0].substring(6, 8));
                    int hour = 0;
                    int minute = 0;

                    startDate = new DateTime(year, month, day, hour, minute);

                }

                // System.out.println(startDate.toString());
                startFlag = false;
            }

            temp.add(Double.parseDouble(line.split(",")[1]));

            if (!activeOnly)
                temp2.add(Double.parseDouble(line.split(",")[2]));

            counter++;
        }

        endDate = startDate.plusMinutes(counter);

        // System.out.println(endDate.toString());

        scanner.close();
        break;

    case "xls":

        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(measurementsFile));

        // Get the first sheet.
        HSSFSheet sheet = workbook.getSheetAt(0);
        for (int i = 0; i < sheet.getLastRowNum(); i++) {

            // Set value of the first cell.
            HSSFRow row = sheet.getRow(i + 1);
            temp.add(row.getCell(1).getNumericCellValue());
            if (!activeOnly)
                temp2.add(row.getCell(2).getNumericCellValue());
        }

        break;

    }

    activePower = new double[temp.size()];

    for (int i = 0; i < temp.size(); i++)
        activePower[i] = temp.get(i);

    if (!activeOnly) {
        reactivePower = new double[temp2.size()];
        for (int i = 0; i < temp2.size(); i++)
            reactivePower[i] = temp2.get(i);
    }

}

From source file:mucom.Footing.DirectionGetter.java

public void getRoute()
//public ArrayList<GeoPoint> getRoute()
{
    if (loadcoords == 0) {
        String startc = startp.getLatitudeE6() / 1E6 + "," + startp.getLongitudeE6() / 1E6;
        String endc = endp.getLatitudeE6() / 1E6 + "," + endp.getLongitudeE6() / 1E6;
        String urlString = "http://maps.google.com/maps/api/directions/json?origin=" + startc + "&destination="
                + endc + "&mode=walking&sensor=false";
        Log.i("Coords", urlString);
        String result = "";
        try {/*from   w  w  w . j  a va 2s  . c  o m*/
            Log.i("DGetter", "Connecting..");
            URL url = new URL(urlString);

            Scanner in = new Scanner(new InputStreamReader(url.openStream()));
            Log.i("DGetter", "Connected OK");

            while (in.hasNext()) {
                result += in.nextLine();
            }
            Log.i("DGetter", "Download OK");
        } catch (Exception e) {
            Log.e("DGetter", "Connection Error");
        }

        //parse json data
        try {

            //overlays.clear();
            mpo.removeAllOverlays();
            fa.pnts.clear();

            JSONObject jsonObject = new JSONObject(result); // parse response into json object
            // routesArray contains ALL routes
            JSONArray routesArray = jsonObject.getJSONArray("routes");
            // Grab the first route
            JSONObject route = routesArray.getJSONObject(0);
            // Take all legs from the route
            JSONArray legs = route.getJSONArray("legs");
            // Grab first leg
            JSONObject leg = legs.getJSONObject(0);
            // Grab steps
            JSONArray steps = leg.getJSONArray("steps");
            JSONObject durationObject = leg.getJSONObject("duration");
            JSONObject startObj = leg.getJSONObject("start_location");

            String duration = durationObject.getString("text");
            Log.i("Dirs", "JSon parsing OK");
            double lat;
            double lon;

            //add starting point
            lat = startObj.getDouble("lat");
            lon = startObj.getDouble("lng");
            GeoPoint g = new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));
            fa.pnts.add(g);
            OverlayItem overlayitem = new OverlayItem(g, "Hola, Mundo!", "I'm in Mexico City!");
            mpo.addOverlay(overlayitem, icons[0]);
            Log.i("Dirs", "Added " + lat + ", " + lon);
            //setup segments array
            fa.segments = new GeoPoint[steps.length()][2];
            Log.i("Segments", "array of " + steps.length());
            int i = 0;
            for (i = 0; i < steps.length(); i++) {
                lat = steps.getJSONObject(i).getJSONObject("end_location").getDouble("lat");
                lon = steps.getJSONObject(i).getJSONObject("end_location").getDouble("lng");
                g = new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));
                fa.pnts.add(g);
                overlayitem = new OverlayItem(g, "Hola, Mundo!", "I'm in Mexico City!");
                if (i < steps.length() - 1)
                    mpo.addOverlay(overlayitem, icons[1]);
                else
                    mpo.addOverlay(overlayitem, icons[2]);
                //add to segments array
                //add end location
                fa.segments[i][1] = g;
                //add start location
                lat = steps.getJSONObject(i).getJSONObject("start_location").getDouble("lat");
                lon = steps.getJSONObject(i).getJSONObject("start_location").getDouble("lng");
                g = new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));
                fa.segments[i][0] = g;

                Log.i("Dirs", "Added " + lat + ", " + lon);
            }

            //overlays.add(mpo);
            Log.i("Dirs", "OK, added " + mpo.size() + " overlays pts");

        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
    } else //if asked to load coords
    {

        List<GeoPoint> lpoints = new ArrayList<GeoPoint>();
        switch (loadcoords) {
        //Glasgow map
        case 1:
            lpoints.add(new GeoPoint((int) (55.861706 * 1E6), (int) (-4.251194 * 1E6)));
            lpoints.add(new GeoPoint((int) (55.861427 * 1E6), (int) (-4.248898 * 1E6)));
            lpoints.add(new GeoPoint((int) (55.859901 * 1E6), (int) (-4.249467 * 1E6)));
            lpoints.add(new GeoPoint((int) (55.859730 * 1E6), (int) (-4.247664 * 1E6)));
            lpoints.add(new GeoPoint((int) (55.858677 * 1E6), (int) (-4.247932 * 1E6)));
            lpoints.add(new GeoPoint((int) (55.858353 * 1E6), (int) (-4.245669 * 1E6)));
            break;
        case 2:
            //Patras 1 - prokat - prutaneia
            lpoints.add(new GeoPoint((int) (38.283730 * 1E6), (int) (21.788706 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.284023 * 1E6), (int) (21.788473 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.283794 * 1E6), (int) (21.787975 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.284672 * 1E6), (int) (21.787218 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.284920 * 1E6), (int) (21.787636 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.285336 * 1E6), (int) (21.787300 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.285599 * 1E6), (int) (21.787697 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.286354 * 1E6), (int) (21.787073 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.286205 * 1E6), (int) (21.786655 * 1E6)));
            break;
        case 3:
            //Patras 2 - prutaneia - near prokat
            lpoints.add(new GeoPoint((int) (38.286205 * 1E6), (int) (21.786661 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.286350 * 1E6), (int) (21.787071 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.285618 * 1E6), (int) (21.787687 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.285339 * 1E6), (int) (21.787306 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.284920 * 1E6), (int) (21.787636 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.284504 * 1E6), (int) (21.786835 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.284107 * 1E6), (int) (21.787334 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.283817 * 1E6), (int) (21.787506 * 1E6)));
            lpoints.add(new GeoPoint((int) (38.283390 * 1E6), (int) (21.787561 * 1E6)));
            break;
        }

        mpo.removeAllOverlays();
        fa.pnts.clear();
        //add points to fa plist
        for (GeoPoint p : lpoints) {
            fa.pnts.add(p);
        }
        //add start and end overlay
        OverlayItem overlayitem = new OverlayItem(lpoints.get(0), "Hola, Mundo!", "I'm in Mexico City!");
        mpo.addOverlay(overlayitem, icons[0]);
        overlayitem = new OverlayItem(lpoints.get(lpoints.size() - 1), "Hola, Mundo!", "I'm in Mexico City!");
        mpo.addOverlay(overlayitem, icons[2]);
        fa.startp = lpoints.get(0);
        fa.endp = lpoints.get(lpoints.size() - 1);

        //setup segments array
        fa.segments = new GeoPoint[lpoints.size() - 1][2];
        for (int i = 0; i < lpoints.size() - 1; i++) {
            overlayitem = new OverlayItem(lpoints.get(i), "Hola, Mundo!", "I'm in Mexico City!");
            mpo.addOverlay(overlayitem, icons[1]);
            fa.segments[i][0] = lpoints.get(i);
            fa.segments[i][1] = lpoints.get(i + 1);
        }

    }
}

From source file:com.networknt.light.rule.LoadRuleMojo.java

public void parseRuleFile(final String filePath) {
    System.out.println("Process file = " + filePath);
    String packageName = null;/*from  www .  j  ava2s. co m*/
    StringBuilder sourceCode = new StringBuilder();
    boolean validRule = false;
    try {
        File file = new File(filePath);
        String className = getClassName(file);
        if (".java".equals(getExtension(file))) {
            final Scanner scan = new Scanner(file, encoding);
            String line = scan.nextLine();
            while (scan.hasNext()) {
                if (!line.trim().isEmpty()) {
                    if (line.startsWith("package")) {
                        packageName = line.substring(8, line.length() - 1);
                    }
                    if (!validRule && line.indexOf("implements") != -1 && line.indexOf("Rule") != -1) {
                        validRule = true;
                    }
                }
                sourceCode.append(line);
                sourceCode.append("\n");
                line = scan.nextLine();
            }
            sourceCode.append(line);
            sourceCode.append("\n");
        }
        if (validRule) {
            // connect to example:8080 to upload rule here.
            String ruleClass = packageName + "." + className;

            // only import the rule if source has been changed after comparing with server
            if (!sourceCode.toString().equals(ruleMap.get(ruleClass))) {
                impRule(ruleClass, sourceCode.toString());
                // generate SQL insert statements

                String sql = "INSERT INTO RULE(class_name, source_code) VALUES ('" + ruleClass + "', '"
                        + sourceCode.toString().replaceAll("'", "''") + "');\n";
                sqlString += sql;
            }
        }
    } catch (final IOException e) {
        getLog().error(e.getMessage());
    }

}

From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

public static Double[][] subsetDoubleVectors(InputStream in, Set<Integer> columns, int numCases)
        throws IOException {
    Double[][] retVector = new Double[columns.size()][numCases];
    Scanner scanner = new Scanner(in);
    scanner.useDelimiter("\\n");

    for (int caseIndex = 0; caseIndex < numCases; caseIndex++) {
        if (scanner.hasNext()) {
            String[] line = (scanner.next()).split("\t", -1);
            int j = 0;
            for (Integer i : columns) {
                try {
                    // TODO: verify that NaN and +-Inf are going to be
                    // handled correctly here! -- L.A. 
                    // NO, "+-Inf" is not handled correctly; see the 
                    // comment further down below. 
                    retVector[j][caseIndex] = new Double(line[i]);
                } catch (NumberFormatException ex) {
                    retVector[j][caseIndex] = null; // missing value
                }//from  ww  w. j a v  a2  s. c  om
                j++;
            }
        } else {
            scanner.close();
            throw new IOException("Tab file has fewer rows than the stored number of cases!");
        }
    }

    int tailIndex = numCases;
    while (scanner.hasNext()) {
        String nextLine = scanner.next();
        if (!"".equals(nextLine)) {
            scanner.close();
            throw new IOException("Tab file has more nonempty rows than the stored number of cases (" + numCases
                    + ")! current index: " + tailIndex + ", line: " + nextLine);
        }
        tailIndex++;
    }

    scanner.close();
    return retVector;

}

From source file:eremeykin.pete.plotter.PlotterTopComponent.java

public void update(File home) {
    // for first rpt file
    if (model == null) {
        clear();/*from  w  w  w . ja v  a  2  s.c  o m*/
        return;
    }
    File[] rptFiles = home.listFiles(filter());
    // catch if there is no such file
    if (rptFiles.length == 0) {
        clear();
        return;
    }
    File firstRPT = rptFiles[0];

    Scanner scanner;
    try {
        scanner = new Scanner(firstRPT);
        scanner.useDelimiter("\\s+|\n");
    } catch (FileNotFoundException ex) {
        clear();
        return;
    }
    List<Map.Entry<Double, Double>> tmpList = new ArrayList<>();
    for (int i = 0; scanner.hasNext(); i++) {
        String line = scanner.next();
        try {
            double x1 = Double.valueOf(line);
            line = scanner.next();
            double x2 = Double.valueOf(line);
            //                System.out.println("x1=" + x1 + "\nx2=" + x2);
            tmpList.add(new AbstractMap.SimpleEntry<>(x1, x2));
        } catch (NumberFormatException ex) {
            // only if it is the third or following line
            if (i > 1) {
                LOGGER.error("Error while parsing double from file: " + firstRPT.getAbsolutePath());
                JOptionPane.showMessageDialog(this, "Error while parsing result file.", "Parsing error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }

    }
    if (tmpList.isEmpty()) {
        clear();
        return;
    }
    fillData(tmpList, dataSeries, toleranceSeries);

}

From source file:com.twitter.ambrose.hive.AmbroseHiveFinishHook.java

private String getLastCmd() {
    CliSessionState cliss = (CliSessionState) SessionState.get();
    Scanner scanner = null;
    try {//from   www .  j  a  v a 2 s .  c  o  m
        scanner = new Scanner(new File(cliss.fileName));
    } catch (FileNotFoundException e) {
        LOG.error("Can't find Hive script", e);
    }
    if (scanner == null) {
        return null;
    }
    Pattern delim = Pattern.compile(";");
    scanner.useDelimiter(delim);
    String lastLine = null;
    while (scanner.hasNext()) {
        String line = StringUtils.trim(scanner.next().replaceAll("\\n|\\r", ""));
        if (line.length() != 0 && !line.startsWith("--")) {
            lastLine = line;
        }
    }
    return lastLine;
}

From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

public static Float[] subsetFloatVector(InputStream in, int column, int numCases) {
    Float[] retVector = new Float[numCases];
    Scanner scanner = new Scanner(in);
    scanner.useDelimiter("\\n");

    for (int caseIndex = 0; caseIndex < numCases; caseIndex++) {
        if (scanner.hasNext()) {
            String[] line = (scanner.next()).split("\t", -1);
            // Verified: new Float("nan") works correctly, 
            // resulting in Float.NaN;
            // Float("[+-]Inf") doesn't work however; 
            // (the constructor appears to be expecting it
            // to be spelled as "Infinity", "-Infinity", etc. 
            if ("inf".equalsIgnoreCase(line[column]) || "+inf".equalsIgnoreCase(line[column])) {
                retVector[caseIndex] = java.lang.Float.POSITIVE_INFINITY;
            } else if ("-inf".equalsIgnoreCase(line[column])) {
                retVector[caseIndex] = java.lang.Float.NEGATIVE_INFINITY;
            } else if (line[column] == null || line[column].equals("")) {
                // missing value:
                retVector[caseIndex] = null;
            } else {
                try {
                    retVector[caseIndex] = new Float(line[column]);
                } catch (NumberFormatException ex) {
                    retVector[caseIndex] = null; // missing value
                }// ww  w  .ja  va  2 s .  c o m
            }
        } else {
            scanner.close();
            throw new RuntimeException("Tab file has fewer rows than the stored number of cases!");
        }
    }

    int tailIndex = numCases;
    while (scanner.hasNext()) {
        String nextLine = scanner.next();
        if (!"".equals(nextLine)) {
            scanner.close();
            throw new RuntimeException(
                    "Column " + column + ": tab file has more nonempty rows than the stored number of cases ("
                            + numCases + ")! current index: " + tailIndex + ", line: " + nextLine);
        }
        tailIndex++;
    }

    scanner.close();
    return retVector;

}

From source file:com.twitter.hraven.rest.client.HRavenRestClient.java

public String getCluster(String hostname) throws IOException {
    String urlString = String.format("http://%s/api/v1/getCluster?hostname=%s", apiHostname,
            StringUtil.cleanseToken(hostname));

    if (LOG.isInfoEnabled()) {
        LOG.info("Requesting cluster for " + hostname);
    }//  w ww  .j  av  a  2 s .c o  m
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(this.connectTimeout);
    connection.setReadTimeout(this.readTimeout);
    InputStream input = connection.getInputStream();
    java.util.Scanner s = new java.util.Scanner(input).useDelimiter("\\A");
    String cluster = s.hasNext() ? s.next() : "";
    try {
        input.close();
    } catch (IOException ioe) {
        LOG.error("IOException in closing input stream, returning no error " + ioe.getMessage());
    }
    return cluster;
}

From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

public static Double[] subsetDoubleVector(InputStream in, int column, int numCases) {
    Double[] retVector = new Double[numCases];
    Scanner scanner = new Scanner(in);
    scanner.useDelimiter("\\n");

    for (int caseIndex = 0; caseIndex < numCases; caseIndex++) {
        if (scanner.hasNext()) {
            String[] line = (scanner.next()).split("\t", -1);

            // Verified: new Double("nan") works correctly, 
            // resulting in Double.NaN;
            // Double("[+-]Inf") doesn't work however; 
            // (the constructor appears to be expecting it
            // to be spelled as "Infinity", "-Infinity", etc. 
            if ("inf".equalsIgnoreCase(line[column]) || "+inf".equalsIgnoreCase(line[column])) {
                retVector[caseIndex] = java.lang.Double.POSITIVE_INFINITY;
            } else if ("-inf".equalsIgnoreCase(line[column])) {
                retVector[caseIndex] = java.lang.Double.NEGATIVE_INFINITY;
            } else if (line[column] == null || line[column].equals("")) {
                // missing value:
                retVector[caseIndex] = null;
            } else {
                try {
                    retVector[caseIndex] = new Double(line[column]);
                } catch (NumberFormatException ex) {
                    retVector[caseIndex] = null; // missing value
                }/*from  w  w w  . j a va  2 s  .  co m*/
            }

        } else {
            scanner.close();
            throw new RuntimeException("Tab file has fewer rows than the stored number of cases!");
        }
    }

    int tailIndex = numCases;
    while (scanner.hasNext()) {
        String nextLine = scanner.next();
        if (!"".equals(nextLine)) {
            scanner.close();
            throw new RuntimeException(
                    "Column " + column + ": tab file has more nonempty rows than the stored number of cases ("
                            + numCases + ")! current index: " + tailIndex + ", line: " + nextLine);
        }
        tailIndex++;
    }

    scanner.close();
    return retVector;

}

From source file:org.glite.security.voms.admin.integration.orgdb.tools.OrgDBUtil.java

protected void doCreateFromFile() throws IOException {

    File file = new File(getValueFromConsoleIfOptionUndefined("user_file"));
    Scanner scanner = new Scanner(file);

    while (scanner.hasNext()) {
        String line = scanner.nextLine();
        String[] tokens = line.split(",");

        createUser(tokens[1], tokens[2], tokens[4], tokens[5], tokens[6]);
    }/*from w w  w  . j  a  v a2s. com*/

    scanner.close();
}