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:org.disit.servicemap.ServiceMap.java

static private void loadStopWords() {
    if (stopWords != null)
        return; //already loaded;

    stopWords = new ArrayList<String>();
    String token1 = "";
    try {//  w  w  w  . j  ava 2 s .  c o m
        // create Scanner
        Scanner scanner = new Scanner(new File(System.getProperty("user.home") + "/servicemap/stop_words.txt"));
        while (scanner.hasNext()) {
            // find next line
            token1 = scanner.next();
            //System.out.println("-"+token1+"-");
            stopWords.add(token1);
        }
        scanner.close();
    } catch (FileNotFoundException ex) {
        System.out.println("Exception: File not found " + ex.toString());
    }
}

From source file:spade.utility.BitcoinTools.java

public static String execCmd(String cmd) throws IOException {
    Scanner s = new Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

From source file:br.upf.contatos.tcp.Client.java

public static boolean comando(String line, ClientConnector tcpService) {

    if (line.equals("help")) {
        System.out.println("op=[ listar, incluir, editar, deletar, parar, cidade ], label = valor");
        System.out.println("Para sair digite: parar");

        return true;

    } else {//from www.java 2 s.c  o m

        tcpService.connect();
        String[] chamadas = line.split(",");
        String[] op = chamadas[0].split("=");

        switch (op[1]) {
        case "listar":

            for (ContatoBean cb : tcpService.getAll()) {
                //System.out.println(new JSONObject(cb));
                System.out.println("ID:" + cb.getId());
                System.out.println("Nome:" + cb.getNome());
                System.out.println("Email:" + cb.getEmail());
                System.out.println("Endereco:" + cb.getEndereco());
                System.out.println("Comp:" + cb.getComplemento());
                System.out.println("CEP:" + cb.getCep());
                System.out.println("Cidade:" + cb.getCidade());
                System.out.println("Estado:" + cb.getEstado());
                System.out.println("Email Alt.:" + cb.getEmailAlternativo());
                System.out.println("------------");
            }

            break;

        case "id":
            String idList;
            Scanner scan2 = new Scanner(System.in);
            System.out.println("Informe o id do contato  listar:");
            idList = scan2.nextLine();
            int numIdList = Integer.parseInt(idList);
            ContatoBean conbean = new ContatoBean();
            conbean.setId(numIdList);

            try {
                conbean = tcpService.getById(numIdList);
                System.out.println("O contato buscado : ");
                System.out.println(new JSONObject(conbean));
            } catch (RuntimeException e) {
                System.out.println(e.getMessage());
            }

            break;

        case "incluir":
            String id;
            String nome;
            String email;
            String end;
            String comp;
            String cep;
            String cid;
            String est;

            Scanner scan = new Scanner(System.in);
            //System.out.printf("Digite o id:");   
            //id = scan.nextLine();                     *** Pegar ID Informado
            System.out.printf("Digite o nome:");
            nome = scan.nextLine();
            System.out.printf("Digite o email:");
            email = scan.nextLine();
            System.out.printf("Digite o endereco:");
            end = scan.nextLine();
            System.out.printf("Digite o complemento:");
            comp = scan.nextLine();
            System.out.printf("Digite o cep:");
            cep = scan.nextLine();
            System.out.printf("Digite a cidade:");
            cid = scan.nextLine();
            System.out.printf("Digite o estado:");
            est = scan.nextLine();

            ContatoBean c = new ContatoBean();
            int numCep = Integer.parseInt(cep);
            int numId = 0; // ***  ID Sequencial automatico
            //int idsec = Integer.parseInt(id); *** Pegar ID Informado
            c.setId(numId); //  ***  ID Sequencial automatico
            //c.setId(idsec);                   *** Pegar ID Informado
            c.setNome(nome);
            c.setEmail(email);
            c.setEndereco(end);
            c.setComplemento(comp);
            c.setCep(numCep);
            c.setCidade(cid);
            c.setEstado(est);
            try {
                c = tcpService.insert(c);
                System.out.println("O contato foi adicionado com Sucesso! Segue abaixo as campos informados: ");
                System.out.println(new JSONObject(c));
            } catch (RuntimeException e) {
                System.out.println(e.getMessage());
            }

            break;

        case "editar":

            while (true) {
                String resp;
                String nummId;
                Scanner sca = new Scanner(System.in);
                System.out.println("Deseja alterar um contato? responda sim ou no");
                resp = sca.nextLine();
                if (resp.equals("sim")) {

                    System.out.println("Informe o id do contato  editar");
                    nummId = sca.nextLine();

                    ContatoBean contB = new ContatoBean();
                    int numIdEdi = Integer.parseInt(nummId);

                    do {
                        String opEditar;

                        System.out.print(
                                "Escolha os atributos  alterar (nome, email, endereco, complemento, cep, cidade, estado, parar): ");
                        opEditar = sca.nextLine();

                        if (opEditar.equals("parar")) {
                            break;
                        } else {
                            String id2 = null;
                            String nome2 = null;
                            String email2 = null;
                            String end2 = null;
                            String comp2 = null;
                            String cep2 = null;
                            String cid2 = null;
                            String est2;
                            ContatoBean contact = new ContatoBean();

                            try {
                                contact = tcpService.getById(numIdEdi);
                            } catch (RuntimeException e) {
                                System.out.println(e.getMessage());
                                break;
                            }

                            switch (opEditar) {

                            case "nome":
                                System.out.printf("Digite o nome:");
                                nome2 = sca.nextLine();
                                contact.setNome(nome2);
                                break;
                            case "email":
                                System.out.printf("Digite o email:");
                                email2 = sca.nextLine();
                                contact.setEmail(email2);
                                break;
                            case "endereco":
                                System.out.printf("Digite o endereco:");
                                end2 = sca.nextLine();
                                contact.setEndereco(end2);
                                break;
                            case "complemento":
                                System.out.printf("Digite o complemento:");
                                comp2 = sca.nextLine();
                                contact.setComplemento(comp2);
                                break;
                            case "cep":
                                System.out.printf("Digite o cep:");
                                cep2 = sca.nextLine();
                                int numCepEdit = Integer.parseInt(cep2);
                                contact.setCep(numCepEdit);
                                break;
                            case "cidade":
                                System.out.printf("Digite o cidade:");
                                cid2 = sca.nextLine();
                                contact.setCidade(cid2);
                                break;
                            case "estado":
                                System.out.printf("Digite o estado:");
                                est2 = sca.nextLine();
                                contact.setEstado(est2);
                                break;

                            }

                            try {
                                contact = tcpService.update(contact);
                                System.out.println(
                                        "O contato foi alterado! Segue abaixo suas informaes atualizadas: ");
                                System.out.println(new JSONObject(contact));
                            } catch (RuntimeException e) {
                                System.out.println(e.getMessage());
                            }
                        }
                    } while (true);

                } else {
                    break;
                }

            }
            break;
        case "cidade":
            String cidade;
            ArrayList cidade2 = new ArrayList();
            Scanner scanner = new Scanner(System.in);
            System.out.println("Informe a cidade  listar");
            cidade = scanner.nextLine();

            try {
                cidade2 = (ArrayList) tcpService.getByCidade(cidade);
                // System.out.println(new JSONObject(cidade2));
                System.out.println("Segue os contatos que moram na cidade de " + cidade + ":");
                for (Object cb : cidade2) {
                    System.out.println(new JSONObject(cb));
                }
            } catch (RuntimeException e) {
                System.out.println(e.getMessage());
            }

            break;

        case "deletar":
            String idDel;
            Scanner scann = new Scanner(System.in);
            System.out.println("Informe o id do contato  deletar");
            idDel = scann.next();
            int numIdDel = Integer.parseInt(idDel);
            ContatoBean cb = new ContatoBean();
            cb.setId(numIdDel);
            try {
                cb = tcpService.delete(numIdDel);
                System.out.println("O contato com o id" + numIdDel + " foi deletado!");
                System.out.println(new JSONObject(cb));
            } catch (RuntimeException e) {
                System.out.println(e.getMessage());
            }

            break;

        case "parar":

            System.out.println("Encerrando Aplicao...");
            return false;
        }

    }

    return true;
}

From source file:com.hybris.mobile.model.product.Product.java

/**
 * This method parses the messages sent from OCC to create HTML with links recognised by the app. Note this code is
 * brittle and relies on very specific formatting in OCC. This method is specifoc to product promotions.
 * /*ww w  . ja  v a2 s. co m*/
 * @param p
 *           The product
 * @return the HTML string to place as the promotions text
 */
public static String generatePromotionString(ProductPromotion productPromotion) {
    String promotionsString = productPromotion.getDescription();

    /*
     * firedMessages trumps description
     */
    if (productPromotion.getFiredMessages() != null && !productPromotion.getFiredMessages().isEmpty()) {
        promotionsString = productPromotion.getFiredMessages().get(0);
        promotionsString.replaceAll("<br>", "\n");
    }
    /*
     * couldFireMessage trumps firedMessage
     */
    if (productPromotion.getCouldFireMessages() != null && !productPromotion.getCouldFireMessages().isEmpty()) {
        promotionsString = productPromotion.getCouldFireMessages().get(0);
        promotionsString.replaceAll("<br>", "\n");
    }
    /*
     * Builds links in the form http://m.hybris.com/123456 N.B. iOS builds links in the form appName://product/123456
     * with the title as the product name
     */
    ArrayList<String> links = new ArrayList<String>();
    ArrayList<String> codes = new ArrayList<String>();
    ArrayList<String> productNames = new ArrayList<String>();
    Pattern codePattern = Pattern.compile("[0-9]{6,7}");
    Scanner s1 = new Scanner(promotionsString);
    s1.useDelimiter("<a href=");
    while (s1.hasNext()) {
        String str = s1.next();
        if (str.startsWith("$config")) {
            Scanner s2 = new Scanner(str);
            s2.useDelimiter("</a>");
            String link = s2.next();
            links.add(link);
        }
    }
    for (String link : links) {
        Scanner s3 = new Scanner(link);
        s3.useDelimiter("<b>");
        s3.next();
        while (s3.hasNext()) {
            String str = s3.next();
            if (!str.startsWith("$")) {
                Scanner s4 = new Scanner(str);
                s4.useDelimiter("</b>");
                String name = s4.next();
                productNames.add(name);
            }
        }
        // Find the codes
        Matcher m = codePattern.matcher(link);
        while (m.find()) {
            String s = m.group();
            codes.add(s);
        }
    }
    // Build the new links
    int position = 0;
    for (String link : links) {
        promotionsString = promotionsString.replace(link, String.format("\"http://m.hybris.com/%s\">%s",
                codes.get(position), productNames.get(position)));
        position++;
    }

    return promotionsString;
}

From source file:Main.java

private static int getChoice() {

    Scanner input = new Scanner(System.in);
    int choice = 1; //default value to force skip of first if statement check
    do {/*from w  w  w .j  a  va2s .c om*/
        if (choice < 1 | choice > 4)
            System.out.println("Invalid choice...");
        System.out.print("Choice: ");
        /*This while loop checks the buffer stream for the next incoming input.
         *the purpose is to check if the input can be assigned an int value.
         *at this time choice has not be assigned*/
        while (!input.hasNextInt()) { // ask for an input, if input NOT nextInt then:
            input.next(); // consumes the token and returns to top of loop for another token
            System.out.print("Try again: "); //don't want println as that would shift cursor to new line
        }
        choice = input.nextInt(); //once the input has been found to be an int, assign to choice
        /*now choice needs to be checked for the correct range of values.
         * if its not within 1-4 then repeat while loop above*/
    } while (choice < 1 | choice > 4);
    //input.close();
    return choice;
}

From source file:com.groupon.odo.HttpUtilities.java

/**
 * Obtain collection of Parameters from request
 *
 * @param httpServletRequest/* ww w . j  av  a  2s  .  c o  m*/
 * @return
 * @throws Exception
 */
public static Map<String, String[]> mapUrlEncodedParameters(HttpServletRequest httpServletRequest)
        throws Exception {

    InputStream body = httpServletRequest.getInputStream();
    java.util.Scanner s = new java.util.Scanner(body).useDelimiter("\\A");
    Map<String, String[]> mapPostParameters = new HashMap<String, String[]>();

    try {
        if (s.hasNext()) {
            String requestData = s.next();
            String[] splitRequestData = requestData.split("&");
            for (String requestPart : splitRequestData) {
                String[] parts = requestPart.split("=");
                ArrayList<String> values = new ArrayList<String>();
                if (mapPostParameters.containsKey(parts[0])) {
                    values = new ArrayList<String>(Arrays.asList(mapPostParameters.get(parts[0])));
                    mapPostParameters.remove(parts[0]);
                }

                if (parts.length > 1) {
                    values.add(parts[1]);
                }

                mapPostParameters.put(parts[0], values.toArray(new String[values.size()]));
            }
        }
    } catch (Exception e) {
        throw new Exception("Could not parse request data: " + e.getMessage());
    }

    return mapPostParameters;
}

From source file:org.apache.james.sieverepository.file.SieveFileRepository.java

/**
 * Read a file with the specified encoding into a String
 *
 * @param file//from   ww w.  j av a  2  s .  co  m
 * @param encoding
 * @return
 * @throws FileNotFoundException
 */
static protected String toString(File file, String encoding) throws FileNotFoundException {
    String script = null;
    Scanner scanner = null;
    try {
        scanner = new Scanner(file, encoding);
        scanner.useDelimiter("\\A");
        script = scanner.next();
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
    return script;
}

From source file:core.PlanC.java

/**
 * retrive global identificator from <code>wmic</code>
 * //from   w w  w  .j av a 2 s .co  m
 * @param gid - gobal id
 * @param vn - variable name
 * 
 * @return variable value
 */
private static String getWmicValue(String gid, String vn) {
    String rval = null;
    try {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(new String[] { "wmic", gid, "get", vn });
        InputStream is = process.getInputStream();
        Scanner sc = new Scanner(is);
        while (sc.hasNext()) {
            String next = sc.next();
            if (vn.equals(next)) {
                rval = sc.next().trim();
                break;
            }
        }
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return rval;
}

From source file:Main.java

/**
 * This API compares if two files content is identical. It ignores extra
 * spaces and new lines while comparing/*from   w w w . ja v a  2s .co  m*/
 *
 * @param sourceFile
 * @param destFile
 * @return
 * @throws Exception
 */
public static boolean isFilesIdentical(URL sourceFile, File destFile) throws Exception {
    try {
        Scanner sourceFileScanner = new Scanner(sourceFile.openStream());
        Scanner destFileScanner = new Scanner(destFile);

        while (sourceFileScanner.hasNext()) {
            /*
             * If source file is having next token then destination file
             * also should have next token, else they are not identical.
             */
            if (!destFileScanner.hasNext()) {
                destFileScanner.close();
                sourceFileScanner.close();
                return false;
            }
            if (!sourceFileScanner.next().equals(destFileScanner.next())) {
                sourceFileScanner.close();
                destFileScanner.close();
                return false;
            }
        }
        /*
         * Handling the case where source file is empty and destination file
         * is having text
         */
        if (destFileScanner.hasNext()) {
            destFileScanner.close();
            sourceFileScanner.close();
            return false;
        } else {
            destFileScanner.close();
            sourceFileScanner.close();
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } /*finally {
      sourceFile.close();
      }*/
}

From source file:com.abiquo.am.services.filesystem.TemplateFileSystem.java

private static String readErrorMarkFile(final File errorMarkFile) {
    assert errorMarkFile.exists();

    Scanner errorMarkReader = null;

    try {//from  ww w .j a  v a  2s  .c om
        errorMarkReader = new Scanner(errorMarkFile).useDelimiter(END_OF_FILE_MARK);
    } catch (FileNotFoundException e) {
        // was checked
    }

    return errorMarkReader.next();
}