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() 

Source Link

Document

Finds and returns the next complete token from this scanner.

Usage

From source file:se.vgregion.portal.cs.util.CryptoUtilImpl.java

private byte[] readKeyFile() {
    Scanner scanner = null;
    try {/*from  w  w  w.j  a  va  2  s  . c o  m*/
        scanner = new Scanner(keyFile).useDelimiter("\\Z");
        String keyValue = scanner.next();
        scanner.close();
        return hexStringToByteArray(keyValue);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return new byte[0];
    }
}

From source file:cz.cuni.mff.ksi.jinfer.autoeditor.BububuEditor.java

/**
 * Draws automaton and waits until user picks two states and clicks
 * 'continue' button./*w  ww  . j a  va2  s.co  m*/
 *
 * @param automaton automaton to be drawn
 * @return if user picks exactly two states returns Pair of them otherwise null
 */
@Override
public List<State<T>> drawAutomatonToPickStates(final Automaton<T> automaton) {

    final DirectedSparseMultigraph<State<T>, Step<T>> graph = new DirectedSparseMultigraph<State<T>, Step<T>>();
    final Map<State<T>, Set<Step<T>>> automatonDelta = automaton.getDelta();

    // Get vertices = states of automaton
    for (Entry<State<T>, Set<Step<T>>> entry : automatonDelta.entrySet()) {
        graph.addVertex(entry.getKey());
    }

    // Get edges of automaton
    for (Entry<State<T>, Set<Step<T>>> entry : automatonDelta.entrySet()) {
        for (Step<T> step : entry.getValue()) {
            graph.addEdge(step, step.getSource(), step.getDestination());
        }
    }

    Map<State<T>, Point2D> positions = new HashMap<State<T>, Point2D>();

    ProcessBuilder p = new ProcessBuilder(Arrays.asList("/usr/bin/dot", "-Tplain"));
    try {
        Process k = p.start();
        k.getOutputStream().write((new AutomatonToDot<T>()).convertToDot(automaton, symbolToString).getBytes());
        k.getOutputStream().flush();
        BufferedReader b = new BufferedReader(new InputStreamReader(k.getInputStream()));
        k.getOutputStream().close();

        Scanner s = new Scanner(b);
        s.next();
        s.next();
        double width = s.nextDouble();
        double height = s.nextDouble();
        double windowW = 500;
        double windowH = 300;

        while (s.hasNext()) {
            if (s.next().equals("node")) {
                int nodeName = s.nextInt();
                double x = s.nextDouble();
                double y = s.nextDouble();
                for (State<T> state : automatonDelta.keySet()) {
                    if (state.getName() == nodeName) {
                        positions.put(state,
                                new Point((int) (windowW * x / width), (int) (windowH * y / height)));
                        break;
                    }
                }
            }
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    Transformer<State<T>, Point2D> trans = TransformerUtils.mapTransformer(positions);

    // TODO rio find suitable layout
    final Layout<State<T>, Step<T>> layout = new StaticLayout<State<T>, Step<T>>(graph, trans);

    //layout.setSize(new Dimension(300,300)); // sets the initial size of the space

    visualizationViewer = new VisualizationViewer<State<T>, Step<T>>(layout);
    //visualizationViewer.setPreferredSize(new Dimension(350,350)); //Sets the viewing area size

    visualizationViewer.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<State<T>>());
    visualizationViewer.getRenderContext().setEdgeLabelTransformer(new Transformer<Step<T>, String>() {
        @Override
        public String transform(Step<T> i) {
            return BububuEditor.this.symbolToString.toString(i.getAcceptSymbol());
        }
    });

    final PluggableGraphMouse gm = new PluggableGraphMouse();
    gm.add(new PickingUnlimitedGraphMousePlugin<State<T>, Step<T>>());
    visualizationViewer.setGraphMouse(gm);

    // Call GUI in a special thread. Required by NB.
    synchronized (this) {
        WindowManager.getDefault().invokeWhenUIReady(new Runnable() {

            @Override
            public void run() {
                // Pass this as argument so the thread will be able to wake us up.
                AutoEditorTopComponent.findInstance().drawAutomatonBasicVisualizationServer(BububuEditor.this,
                        visualizationViewer, "Please select two states to be merged together.");
            }
        });

        try {
            // Sleep on this.
            this.wait();
        } catch (InterruptedException e) {
            return null;
        }
    }

    /* AutoEditorTopComponent wakes us up. Get the result and return it.
     * VisualizationViewer should give us the information about picked vertices.
     */
    final Set<State<T>> pickedSet = visualizationViewer.getPickedVertexState().getPicked();
    List<State<T>> lst = new ArrayList<State<T>>(pickedSet);
    return lst;
}

From source file:simulation.AureoZauleckAnsLab2.java

public static ArrayList GetData() {
    N = 0;//from w ww. ja  v  a 2s.co  m

    ArrayList list = new ArrayList<>();
    Scanner sc = new Scanner(System.in);
    String testN = "";
    int population = 0;
    do {
        System.out.println();
        System.out.println("Enter the maximun number of inputs: ");

        testN = sc.next();

        if (IsNumber(testN)) {
            population = Convert(testN);
        } else {
            do {
                System.out.println("Please enter a number only.");
                testN = sc.next();
            } while (!IsNumber(testN));

            population = Convert(testN);
        }
        N = population;
    } while (N <= 1);

    int type = 0, testT = 0;
    String typeTest = "";

    do {
        System.out.println();
        System.out.println("** INPUT OPTIONS **");
        System.out.println("[1] Numeric");
        System.out.println("[2] Alphabetic Character ");
        System.out.println("[3] String");

        System.out.println();
        System.out.println("Please pick a number from the choices above.");

        typeTest = sc.next();

        if (IsNumber(typeTest)) {
            testT = Convert(typeTest);
        } else {
            do {
                System.out.println("Please enter a number only.");
                typeTest = sc.next();
            } while (!IsNumber(typeTest));

            testT = Convert(typeTest);
        }
        type = testT;
    } while (type < 1 || type > 3);

    if (type == 1) {
        System.out.println();
        System.out.println("ENTER MEMBERS OF THE SAMPLING FRAME: ");
        sc.nextLine();
        System.out.println("Numbers only");

        for (int i = 1; i <= N; i++) {
            String test = "";
            do {
                System.out.print("[" + i + "]" + " ");
                Object member = sc.next();
                test = member.toString();
                if (!IsNumber(test)) {
                    System.out.println("Oops. Numbers only");
                }
            } while (!IsNumber(test));

            list.add(test);
        }
    } else if (type == 2) {
        System.out.println();
        System.out.println("ENTER MEMBERS OF THE SAMPLING FRAME: ");
        sc.nextLine();
        System.out.println("Alphabetic Characters only");
        for (int i = 1; i <= N; i++) {
            String test;
            do {
                System.out.print("[" + i + "]" + " ");
                Object member = sc.next();
                test = member.toString();
                if (IsNumber(test)) {
                    System.out.println("Oops. Characters only");
                } else if (test.length() > 1) {
                    System.out.println("Oops. We only accept one character");
                } else if (test.charAt(0) >= 'A' && test.charAt(0) <= 'Z') {
                    System.out.println("Oops. We accept lowercase only");
                }
            } while (IsNumber(test) || test.length() > 1 || (test.charAt(0) >= 'A' && test.charAt(0) <= 'Z'));

            list.add(test);
        }
    } else {
        for (int i = 1; i <= N; i++) {
            String test = "";
            Scanner j = new Scanner(System.in);
            System.out.print("[" + i + "]" + " ");
            Object member;
            member = j.nextLine();
            test = member.toString();
            list.add(test);
        }

    }

    System.out.println("this is the list" + list);
    return list;
}

From source file:org.mcxiaoke.commons.http.util.URIUtilsEx.java

/**
 * Adds all parameters within the Scanner to the list of
 * <code>parameters</code>, as encoded by <code>encoding</code>. For
 * example, a scanner containing the string <code>a=1&b=2&c=3</code> would
 * add the {@link NameValuePair NameValuePairs} a=1, b=2, and c=3 to the
 * list of parameters./*ww w. j  a  va  2 s . c om*/
 * 
 * @param parameters
 *            List to add parameters to.
 * @param scanner
 *            Input that contains the parameters to parse.
 * @param charset
 *            Encoding to use when decoding the parameters.
 */
public static void parse2(final Map<String, String> parameters, final Scanner scanner, final String charset) {
    scanner.useDelimiter(PARAMETER_SEPARATOR);
    while (scanner.hasNext()) {
        String key = null;
        String value = null;
        String token = scanner.next();
        int i = token.indexOf(NAME_VALUE_SEPARATOR);
        if (i != -1) {
            key = decodeFormFields(token.substring(0, i).trim(), charset);
            value = decodeFormFields(token.substring(i + 1).trim(), charset);
        } else {
            key = decodeFormFields(token.trim(), charset);
        }
        parameters.put(key, value);
    }
}

From source file:Javafile.java

void readWords(HashMap<String, Integer> words) {
    try {/*ww  w . j a v a 2s.c o m*/
        Scanner me = new Scanner(new File("E:/Sample Projects/ValidateWords/words.txt"));
        String word;
        while (me.hasNext()) {
            word = me.next();
            words.put(word, word.length());
        }
    } catch (Exception e) {

    }
}

From source file:cz.cuni.mff.ksi.jinfer.autoeditor.automatonvisualizer.layouts.graphviz.GraphvizLayoutFactory.java

@SuppressWarnings("PMD")
private <T> Map<State<T>, Point2D> getGraphvizPositions(final byte[] graphInDotFormat,
        final Set<State<T>> automatonStates) throws GraphvizException, IOException {
    final Map<State<T>, Point2D> result = new HashMap<State<T>, Point2D>();

    // creates new dot process.
    final ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(GraphvizUtils.getPath(), "-Tplain"));
    final Process process = processBuilder.start();

    // write our graph into dot binary standart input
    process.getOutputStream().write(graphInDotFormat);
    process.getOutputStream().flush();/*w w w.ja  v a 2s. com*/

    // read from dot binary standard output
    final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    process.getOutputStream().close();

    final Scanner scanner = new Scanner(reader);
    // jumps some unnecessary information from output
    scanner.next();
    scanner.next();

    // get width and height of graph
    windowWidth = 100 + (int) Double.parseDouble(scanner.next());
    windowHeight = 100 + (int) Double.parseDouble(scanner.next());

    // parse output for graph vertex positions
    while (scanner.hasNext()) {
        final String n = scanner.next();
        if (n.equals("node")) {
            final int nodeName = Integer.parseInt(scanner.next());
            final double x = Double.parseDouble(scanner.next());
            final double y = Double.parseDouble(scanner.next());
            boolean found = false;
            for (State<T> state : automatonStates) {
                if (state.getName() == nodeName) {
                    result.put(state, new Point(50 + (int) (x), 50 + (int) (y)));
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new GraphvizException("Node with name " + nodeName + " was not found in automaton.");
            }
        }
    }

    return result;
}

From source file:org.apache.tajo.storage.TestRowFile.java

@Test
public void test() throws IOException {
    Schema schema = new Schema();
    schema.addColumn("id", Type.INT4);
    schema.addColumn("age", Type.INT8);
    schema.addColumn("description", Type.TEXT);

    TableMeta meta = CatalogUtil.newTableMeta("ROWFILE");

    FileTablespace sm = (FileTablespace) TablespaceManager.get(cluster.getDefaultFileSystem().getUri()).get();

    Path tablePath = new Path("/test");
    Path metaPath = new Path(tablePath, ".meta");
    Path dataPath = new Path(tablePath, "test.tbl");
    FileSystem fs = sm.getFileSystem();
    fs.mkdirs(tablePath);/*from   w  w w. ja  v a2s  .  c  om*/

    FileUtil.writeProto(fs, metaPath, meta.getProto());

    Appender appender = sm.getAppender(meta, schema, dataPath);
    appender.enableStats();
    appender.init();

    int tupleNum = 200;
    Tuple tuple;
    Datum stringDatum = DatumFactory.createText("abcdefghijklmnopqrstuvwxyz");
    Set<Integer> idSet = Sets.newHashSet();

    tuple = new VTuple(3);
    long start = System.currentTimeMillis();
    for (int i = 0; i < tupleNum; i++) {
        tuple.put(0, DatumFactory.createInt4(i + 1));
        tuple.put(1, DatumFactory.createInt8(25l));
        tuple.put(2, stringDatum);
        appender.addTuple(tuple);
        idSet.add(i + 1);
    }
    appender.close();

    TableStats stat = appender.getStats();
    assertEquals(tupleNum, stat.getNumRows().longValue());

    FileStatus file = fs.getFileStatus(dataPath);
    TableProto proto = (TableProto) FileUtil.loadProto(cluster.getDefaultFileSystem(), metaPath,
            TableProto.getDefaultInstance());
    meta = new TableMeta(proto);
    FileFragment fragment = new FileFragment("test.tbl", dataPath, 0, file.getLen());

    int tupleCnt = 0;
    start = System.currentTimeMillis();
    Scanner scanner = sm.getScanner(meta, schema, fragment);
    scanner.init();
    while ((tuple = scanner.next()) != null) {
        tupleCnt++;
    }
    scanner.close();

    assertEquals(tupleNum, tupleCnt);

    tupleCnt = 0;
    long fileStart = 0;
    long fileLen = file.getLen() / 13;

    for (int i = 0; i < 13; i++) {
        fragment = new FileFragment("test.tbl", dataPath, fileStart, fileLen);
        scanner = new RowFile.RowFileScanner(conf, schema, meta, fragment);
        scanner.init();
        while ((tuple = scanner.next()) != null) {
            if (!idSet.remove(tuple.getInt4(0)) && LOG.isDebugEnabled()) {
                LOG.debug("duplicated! " + tuple.getInt4(0));
            }
            tupleCnt++;
        }
        scanner.close();
        fileStart += fileLen;
        if (i == 11) {
            fileLen = file.getLen() - fileStart;
        }
    }
    assertEquals(tupleNum, tupleCnt);
}

From source file:com.liferay.arquillian.container.LiferayContainer.java

private String getBodyAsString(HttpResponse response) throws IOException {
    HttpEntity responseEntity = response.getEntity();

    InputStream content = responseEntity.getContent();

    Header contentEncoding = responseEntity.getContentEncoding();

    String encoding = contentEncoding != null ? contentEncoding.getValue() : "ISO-8859-1";

    Scanner scanner = new Scanner(content, encoding).useDelimiter("\\A");

    return scanner.hasNext() ? scanner.next() : "";
}

From source file:com.greenpepper.html.HtmlExample.java

private String firstPattern(String tags) {
    Scanner scanner = new Scanner(tags);
    try {//from  ww  w  .  ja v a2 s .c  o m
        return scanner.next();
    } finally {
        scanner.close();
    }
}

From source file:csns.importer.parser.csula.RosterParserImpl.java

@Override
public List<ImportedUser> parse(String text) {
    Scanner scanner = new Scanner(text);
    scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n");
    String first = scanner.next();
    scanner.close();//from ww w . ja v a  2 s . c om

    return first.equals("1") ? parse1(text) : parse2(text);
}