Example usage for java.util Scanner next

List of usage examples for java.util Scanner next

Introduction

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

Prototype

public String next(Pattern pattern) 

Source Link

Document

Returns the next token if it matches the specified pattern.

Usage

From source file:Main.java

public static void main(String[] args) {

    String s = "java2s.com 1 + 1 = 2.0 true ";
    Scanner scanner = new Scanner(s);

    System.out.println(scanner.next("."));

    scanner.close();/*ww  w.j av a2  s.  c o m*/
}

From source file:Main.java

public static void main(String[] args) {

    String s = "java2s.com 1 + 1 = 2.0 ";

    Scanner scanner = new Scanner(s);

    // check if next token matches the pattern and print it
    System.out.println(scanner.next("java2s"));

    // check if next token matches the pattern and print it
    System.out.println(scanner.next("="));

    scanner.close();/* w  w  w.ja va2  s . co m*/
}

From source file:com.rockhoppertech.music.DurationParser.java

/**
 * Copies new events into the TimeSeries parameter - which is also returned.
 * //www.  java  2 s  . co m
 * @param ts
 *            a {@code TimeSeries} that will be added to
 * @param s
 *            a duration string
 * @return the same{@code TimeSeries} that you passed in
 */
public static TimeSeries getDurationAsTimeSeries(TimeSeries ts, String s) {
    String token = null;
    Scanner scanner = new Scanner(s);

    if (s.indexOf(',') != -1) {
        scanner.useDelimiter(",");
    }

    while (scanner.hasNext()) {
        if (scanner.hasNext(dpattern)) {
            token = scanner.next(dpattern);
            double d = getDottedValue(token);
            ts.add(d);
            logger.debug("'{}' is dotted value is {}", token, d);

        } else if (scanner.hasNext(pattern)) {
            token = scanner.next(pattern);
            double d = durKeyMap.get(token);
            ts.add(d);
            logger.debug("'{}' is not dotted value is {}", token, d);
            // } else if (scanner.hasNext(tripletPattern)) {
            // token = scanner.next(tripletPattern);
            // double d = durKeyMap.get(token);
            // ts.add(d);
            // System.out.println(String
            // .format("'%s' is not dotted value is %f",
            // token,
            // d));
        } else if (scanner.hasNextDouble()) {
            double d = scanner.nextDouble();
            ts.add(d);
            logger.debug("{} is a double", d);
        } else {
            // just ignore it. or throw exception?
            String skipped = scanner.next();
            logger.debug("skipped '{}'", skipped);
        }
    }
    scanner.close();
    return ts;
}

From source file:com.rockhoppertech.music.DurationParser.java

public static List<Double> getDurationsAsList(String durations) {
    String token = null;/*from  ww w  . ja  va2 s  .  c o m*/
    List<Double> list = new ArrayList<Double>();
    Scanner scanner = new Scanner(durations);

    if (durations.indexOf(',') != -1) {
        scanner.useDelimiter(",");
    }

    while (scanner.hasNext()) {
        if (scanner.hasNext(dpattern)) {
            token = scanner.next(dpattern);
            double d = getDottedValue(token);
            list.add(d);
            logger.debug("'{}' is dotted value is {}", token, d);

        } else if (scanner.hasNext(pattern)) {
            token = scanner.next(pattern);
            double d = durKeyMap.get(token);
            list.add(d);
            logger.debug("'{}' is not dotted value is {}", token, d);
            // } else if (scanner.hasNext(tripletPattern)) {
            // token = scanner.next(tripletPattern);
            // double d = durKeyMap.get(token);
            // ts.add(d);
            // System.out.println(String
            // .format("'%s' is not dotted value is %f",
            // token,
            // d));
        } else if (scanner.hasNextDouble()) {
            double d = scanner.nextDouble();
            list.add(d);
            logger.debug("{} is a double", d);
        } else {
            // just ignore it. or throw exception?
            String skipped = scanner.next();
            logger.debug("skipped '{}'", skipped);
        }
    }
    scanner.close();
    return list;
}

From source file:de.bstreit.java.oscr.initialdata.LoadInitialDataApp.java

private String readFromPrompt(final Scanner scanner) {

    try {/*from ww  w . jav  a2 s .c o m*/
        return String.valueOf(scanner.next("\\w"));

    } catch (InputMismatchException e) {

        return "";
    }

}

From source file:org.jdal.text.PeriodFormatter.java

/**
 * {@inheritDoc}/*  w  w w  . j  av a  2s .  c o  m*/
 */
public Number parse(String text, Locale locale) throws ParseException {
    long value = 0;
    Scanner scanner = new Scanner(text);

    while (scanner.hasNext())
        value += parse(scanner.nextLong(), scanner.next("[dhms]"));

    scanner.close();

    return value;

}

From source file:logicProteinHypernetwork.analysis.complexes.offline.ComplexPredictionCommand.java

/**
 * Returns predicted complexes for a given undirected graph of proteins.
 *
 * @param g the graph/* ww w .  j a va 2 s  . c o  m*/
 * @return the predicted complexes
 */
public Collection<Complex> transform(UndirectedGraph<Protein, Interaction> g) {
    try {
        Process p = Runtime.getRuntime().exec(command);
        BufferedOutputStream outputStream = new BufferedOutputStream(p.getOutputStream());
        BufferedInputStream inputStream = new BufferedInputStream(p.getInputStream());

        for (Interaction i : g.getEdges()) {
            String out = i.first() + " pp " + i.second();
            outputStream.write(out.getBytes());
        }
        outputStream.close();
        p.waitFor();

        if (!hypernetwork.getProteins().hasIndex()) {
            hypernetwork.getProteins().buildIndex();
        }

        Collection<Complex> complexes = new ArrayList<Complex>();
        Scanner s = new Scanner(inputStream);
        Pattern rowPattern = Pattern.compile(".*?\\n");
        Pattern proteinPattern = Pattern.compile(".*?\\s");
        while (s.hasNext(rowPattern)) {
            Complex c = new Complex();
            while (s.hasNext(proteinPattern)) {
                c.add(hypernetwork.getProteins().getProteinById(s.next(proteinPattern).trim()));
            }
            complexes.add(c);
        }
        inputStream.close();

        return complexes;

    } catch (InterruptedException ex) {
        Logger.getLogger(ComplexPredictionCommand.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ComplexPredictionCommand.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:org.seedstack.shell.internal.AbstractShell.java

List<Command> createCommandActions(String line) {
    if (Strings.isNullOrEmpty(line)) {
        return new ArrayList<>();
    }/*from   www .j a va 2s. co  m*/

    List<Command> commands = new ArrayList<>();

    Scanner scanner = new Scanner(new StringReader(line));

    String qualifiedName = null;
    List<String> args = new ArrayList<>();

    while (scanner.hasNext()) {
        if (qualifiedName == null) {
            if (scanner.hasNext(COMMAND_PATTERN)) {
                qualifiedName = scanner.next(COMMAND_PATTERN);
            } else {
                throw SeedException.createNew(ShellErrorCode.COMMAND_PARSING_ERROR);
            }
        } else {
            // Find next token respecting quoted strings
            String arg = scanner.findWithinHorizon("[^\"\\s]+|\"(\\\\.|[^\\\\\"])*\"", 0);
            if (arg != null) {
                if ("|".equals(arg)) {
                    // unquoted pipe, we execute the command and store the result for the next one
                    commands.add(createCommandAction(qualifiedName, args));

                    qualifiedName = null;
                    args = new ArrayList<>();
                } else {
                    // if it's a quoted string, unquote it
                    if (arg.startsWith("\"")) {
                        arg = arg.substring(1);
                    }
                    if (arg.endsWith("\"")) {
                        arg = arg.substring(0, arg.length() - 1);
                    }

                    // replace any escaped quote by real quote
                    args.add(arg.replaceAll("\\\\\"", "\""));
                }
            } else {
                throw SeedException.createNew(ShellErrorCode.COMMAND_SYNTAX_ERROR).put("value", scanner.next());
            }
        }
    }

    commands.add(createCommandAction(qualifiedName, args));

    return commands;
}

From source file:org.seedstack.seed.shell.internal.AbstractShell.java

protected List<Command> createCommandActions(String line) {
    if (Strings.isNullOrEmpty(line)) {
        return new ArrayList<Command>();
    }//from  w ww . j a v a 2  s. c o  m

    List<Command> commands = new ArrayList<Command>();

    Scanner scanner = new Scanner(new StringReader(line));

    String qualifiedName = null;
    List<String> args = new ArrayList<String>();

    while (scanner.hasNext()) {
        if (qualifiedName == null) {
            if (scanner.hasNext(COMMAND_PATTERN)) {
                qualifiedName = scanner.next(COMMAND_PATTERN);
            } else {
                throw SeedException.createNew(ShellErrorCode.COMMAND_PARSING_ERROR);
            }
        } else {
            // Find next token respecting quoted strings
            String arg = scanner.findWithinHorizon("[^\"\\s]+|\"(\\\\.|[^\\\\\"])*\"", 0);
            if (arg != null) {
                if ("|".equals(arg)) {
                    // unquoted pipe, we execute the command and store the result for the next one
                    commands.add(createCommandAction(qualifiedName, args));

                    qualifiedName = null;
                    args = new ArrayList<String>();
                } else {
                    // if it's a quoted string, unquote it
                    if (arg.startsWith("\"")) {
                        arg = arg.substring(1);
                    }
                    if (arg.endsWith("\"")) {
                        arg = arg.substring(0, arg.length() - 1);
                    }

                    // replace any escaped quote by real quote
                    args.add(arg.replaceAll("\\\\\"", "\""));
                }
            } else {
                throw SeedException.createNew(ShellErrorCode.COMMAND_SYNTAX_ERROR).put("value", scanner.next());
            }
        }
    }

    commands.add(createCommandAction(qualifiedName, args));

    return commands;
}

From source file:com.jayway.maven.plugins.android.AbstractAndroidMojo.java

/**
 * Extracts the package name from an XmlTree dump of AndroidManifest.xml by the <code>aapt</code> tool.
 *
 * @param aaptDumpXmlTree output from <code>aapt dump xmltree &lt;apkFile&gt; AndroidManifest.xml
 * @return the package name from inside the apkFile.
 *///from  w  w  w. j  av a  2  s. c  o m
protected String extractPackageNameFromAndroidManifestXmlTree(String aaptDumpXmlTree) {
    final Scanner scanner = new Scanner(aaptDumpXmlTree);
    // Finds the root element named "manifest".
    scanner.findWithinHorizon("^E: manifest", 0);
    // Finds the manifest element's attribute named "package".
    scanner.findWithinHorizon("  A: package=\"", 0);
    // Extracts the package value including the trailing double quote.
    String packageName = scanner.next(".*?\"");
    // Removes the double quote.
    packageName = packageName.substring(0, packageName.length() - 1);
    return packageName;
}