Example usage for java.util Scanner Scanner

List of usage examples for java.util Scanner Scanner

Introduction

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

Prototype

public Scanner(ReadableByteChannel source) 

Source Link

Document

Constructs a new Scanner that produces values scanned from the specified channel.

Usage

From source file:mx.uaq.facturacion.enlace.system.EmailSystemTest.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args/*from  w w  w .  j  av a2 s .  com*/
 *            - command line arguments
 */
public static void main(final String... args) {

    LOGGER.info(HORIZONTAL_LINE + "\n" + "\n          Welcome to Spring Integration!                 " + "\n"
            + "\n    For more information please visit:                   "
            + "\n    http://www.springsource.org/spring-integration       " + "\n" + HORIZONTAL_LINE);

    final AbstractApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:email-facturas.poller.xml", "classpath:facturacion-integration.xml");

    context.registerShutdownHook();

    final Scanner scanner = new Scanner(System.in);

    LOGGER.info(HORIZONTAL_LINE + "\n" + "\n    Please press 'q + Enter' to quit the application.    " + "\n"
            + HORIZONTAL_LINE);

    while (true) {

        final String input = scanner.nextLine();

        if ("q".equals(input.trim())) {
            break;
        }

    }

    LOGGER.info("Exiting application...bye.");

    System.exit(0);
}

From source file:com.cjtotten.example.si.Main.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments/*from   w  w w.ja va 2 s  .c om*/
 */
public static void main(final String... args) {

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("\n========================================================="
                + "\n                                                         "
                + "\n          Welcome to Spring Integration!                 "
                + "\n                                                         "
                + "\n    For more information please visit:                   "
                + "\n    http://www.springsource.org/spring-integration       "
                + "\n                                                         "
                + "\n=========================================================");
    }

    final AbstractApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:META-INF/spring/integration/*-context.xml");

    context.registerShutdownHook();

    final Scanner scanner = new Scanner(System.in);

    final StringConversionService service = context.getBean(StringConversionService.class);

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("\n========================================================="
                + "\n                                                         "
                + "\n    Please press 'q + Enter' to quit the application.    "
                + "\n                                                         "
                + "\n=========================================================");
    }

    System.out.print("Please enter a string and press <enter>: ");

    while (true) {

        final String input = scanner.nextLine();

        if ("q".equals(input.trim())) {
            break;
        }

        try {

            System.out.println("Converted to upper-case: " + service.convertToUpperCase(input));

        } catch (Exception e) {
            LOGGER.error("An exception was caught: " + e);
        }

        System.out.print("Please enter a string and press <enter>:");

    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Exiting application...bye.");
    }

    System.exit(0);

}

From source file:net.jmhertlein.alphonseirc.MSTDeskEngRunner.java

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    loadConfig();//  w  ww. j a  va  2 s .c om

    AlphonseBot bot = new AlphonseBot(nick, pass, server, channels, maxXKCD, noVoiceNicks, masters,
            dadLeaveTimes);
    bot.setMessageDelay(500);
    try {
        bot.startConnection();
    } catch (IOException | IrcException ex) {
        Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex);
    }

    boolean quit = false;
    while (!quit) {
        String curLine = scan.nextLine();

        switch (curLine) {
        case "exit":
            System.out.println("Quitting.");
            bot.onPreQuit();
            bot.disconnect();
            bot.dispose();
            writeConfig();
            quit = true;
            System.out.println("Quit'd.");
            break;
        case "msg":
            Scanner lineScan = new Scanner(scan.nextLine());
            try {
                bot.sendMessage(lineScan.next(), lineScan.nextLine());
            } catch (Exception e) {
                System.err.println(e.getClass().toString());
                System.err.println("Not enough args");
            }
            break;
        default:
            System.out.println("Invalid command.");
        }
    }
}

From source file:se.berazy.api.examples.App.java

/**
 * Operation examples.// w  w w. ja va  2s.  c om
 * @param args
 */
public static void main(String[] args) {
    Scanner scanner = null;
    try {
        client = new BookkeepingClient();
        System.out.println("Choose operation to invoke:\n");
        System.out.println("1. Create invoice");
        System.out.println("2. Credit invoice");
        scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            line = (line != null) ? line.trim().toLowerCase() : "";
            if (line.equals("1")) {
                outPutResponse(createInvoice());
            } else if (line.equals("2")) {
                outPutResponse(creditInvoice());
            } else if (line.equals("q") || line.equals("quit") || line.equals("exit")) {
                System.exit(0);
            } else {
                System.out.println("\nPlease choose an operation from 1-7.");
            }
        }
        scanner.close();
    } catch (Exception ex) {
        System.out.println(String.format(
                "\nAn exception occured, press CTRL+C to exit or enter 'q', 'quit' or 'exit'.\n\nException: %s %s",
                ex.getMessage(), ex.getStackTrace()));
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
}

From source file:com.hillert.spring.validation.Main.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments//from   www. j  a va 2 s  .  c  o  m
 */
public static void main(final String... args) {

    LOGGER.info("\n========================================================="
            + "\n                                                         "
            + "\n          Welcome!                                       "
            + "\n                                                         "
            + "\n    For more information please visit:                   "
            + "\n    http://blog.hillert.com                              "
            + "\n                                                         "
            + "\n=========================================================");

    final AbstractApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:META-INF/spring/*-context.xml");

    context.registerShutdownHook();

    final Scanner scanner = new Scanner(System.in).useDelimiter("\n");

    final BusinessService service = context.getBean(BusinessService.class);

    LOGGER.info("\n========================================================="
            + "\n                                                         "
            + "\n    Please press 'q + Enter' to quit the application.    "
            + "\n                                                         "
            + "\n=========================================================");

    System.out.println("Please enter a string and press <enter>: ");

    while (true) {

        System.out.print("$ ");
        String input = scanner.nextLine();

        LOGGER.debug("Input string: '{}'", input);

        if ("q".equalsIgnoreCase(input)) {
            break;
        } else if ("null".equals(input)) {
            input = null;
        }

        try {
            System.out.println("Converted to upper-case: " + service.convertToUpperCase(input));
        } catch (MethodConstraintViolationException e) {
            Set<MethodConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
            LOGGER.info("Method Validation failed with {} error(s).", constraintViolations.size());

            for (MethodConstraintViolation<?> violation : e.getConstraintViolations()) {
                LOGGER.info("Method Validation: {}", violation.getConstraintDescriptor());
            }

        }
    }

    LOGGER.info("Exiting application...bye.");

    System.exit(0);

}

From source file:com.somnus.spring.validation.Main.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments/* w w  w.j ava  2 s  . c  o  m*/
 */
public static void main(final String... args) {

    LOGGER.info("\n========================================================="
            + "\n                                                         "
            + "\n          Welcome!                                       "
            + "\n                                                         "
            + "\n    For more information please visit:                   "
            + "\n    http://blog.hillert.com                              "
            + "\n                                                         "
            + "\n=========================================================");

    final AbstractApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:META-INF/spring/*-context.xml");

    context.registerShutdownHook();

    final Scanner scanner = new Scanner(System.in).useDelimiter("\n");

    final BusinessService service = context.getBean(BusinessService.class);

    LOGGER.info("\n========================================================="
            + "\n                                                         "
            + "\n    Please press 'q + Enter' to quit the application.    "
            + "\n                                                         "
            + "\n=========================================================");

    System.out.println("Please enter a string and press <enter>: ");

    while (true) {

        System.out.print("$ ");
        String input = scanner.nextLine();

        LOGGER.debug("Input string: '{}'", input);

        if ("q".equalsIgnoreCase(input)) {
            break;
        } else if ("null".equals(input)) {
            input = null;
        }

        try {
            System.out.println("Converted to upper-case: " + service.convertToUpperCase(input));
        } catch (MethodConstraintViolationException e) {
            Set<MethodConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
            LOGGER.info("Method Validation failed with {} error(s).", constraintViolations.size());

            for (MethodConstraintViolation<?> violation : e.getConstraintViolations()) {
                LOGGER.info("Method Validation: {}", violation.getPropertyPath().toString());
                LOGGER.info("Method Validation: {}", violation.getConstraintDescriptor());
                LOGGER.info("Method Validation: {}", violation.getMessage());
            }

        }
    }

    LOGGER.info("Exiting application...bye.");

    System.exit(0);

}

From source file:br.usp.poli.lta.cereda.spa2run.Main.java

public static void main(String[] args) {

    Utils.printBanner();//from ww w. j  a  v a  2 s  . co m
    CommandLineParser parser = new DefaultParser();

    try {
        CommandLine line = parser.parse(Utils.getOptions(), args);
        List<Spec> specs = Utils.fromFilesToSpecs(line.getArgs());
        List<Metric> metrics = Utils.fromFilesToMetrics(line);
        Utils.setMetrics(metrics);
        Utils.resetCalculations();
        AdaptiveAutomaton automaton = Utils.getAutomatonFromSpecs(specs);

        System.out.println("SPA generated successfully:");
        System.out.println("- " + specs.size() + " submachine(s) found.");
        if (!Utils.detectEpsilon(automaton)) {
            System.out.println("- No empty transitions.");
        }
        if (!metrics.isEmpty()) {
            System.out.println("- " + metrics.size() + " metric(s) found.");
        }

        System.out.println("\nStarting shell, please wait...\n" + "(press CTRL+C or type `:quit'\n"
                + "to exit the application)\n");

        String query = "";
        Scanner scanner = new Scanner(System.in);
        String prompt = "[%d] query> ";
        String result = "[%d] result> ";
        int counter = 1;
        do {

            try {
                String term = String.format(prompt, counter);
                System.out.print(term);
                query = scanner.nextLine().trim();
                if (!query.equals(":quit")) {
                    boolean accept = automaton.recognize(Utils.toSymbols(query));
                    String type = automaton.getRecognitionPaths().size() == 1 ? " (deterministic)"
                            : " (nondeterministic)";
                    System.out.println(String.format(result, counter) + accept + type);

                    if (!metrics.isEmpty()) {
                        System.out.println(StringUtils.repeat(" ", String.format("[%d] ", counter).length())
                                + Utils.prettyPrintMetrics());
                    }

                    System.out.println();

                }
            } catch (Exception exception) {
                System.out.println();
                Utils.printException(exception);
                System.out.println();
            }

            counter++;
            Utils.resetCalculations();

        } while (!query.equals(":quit"));
        System.out.println("That's all folks!");

    } catch (ParseException nothandled) {
        Utils.printHelp();
    } catch (Exception exception) {
        Utils.printException(exception);
    }
}

From source file:drpc.KMeansDrpcQuery.java

public static void main(final String[] args)
        throws IOException, TException, DRPCExecutionException, DecoderException, ClassNotFoundException {
    if (args.length < 3) {
        System.err.println("Where are the arguments? args -- DrpcServer DrpcFunctionName folder");
        return;//from   w  ww.j av a  2 s. c  o  m
    }

    final DRPCClient client = new DRPCClient(args[0], 3772, 1000000 /*timeout*/);
    final Queue<String> featureFiles = new ArrayDeque<String>();
    SpoutUtils.listFilesForFolder(new File(args[2]), featureFiles);

    Scanner scanner = new Scanner(featureFiles.peek());
    int i = 0;
    while (scanner.hasNextLine() && i++ < 10) {
        List<Map<String, List<Double>>> dict = SpoutUtils.pythonDictToJava(scanner.nextLine());
        for (Map<String, List<Double>> map : dict) {
            i++;

            Double[] features = map.get("chi2").toArray(new Double[0]);
            Double[] moreFeatures = map.get("chi1").toArray(new Double[0]);
            Double[] rmsd = map.get("rmsd").toArray(new Double[0]);
            Double[] both = (Double[]) ArrayUtils.addAll(features, moreFeatures);
            String parameters = serializeFeatureVector(ArrayUtils.toPrimitive(both));

            String centroidsSerialized = runQuery(args[1], parameters, client);

            Gson gson = new Gson();
            Object[] deserialized = gson.fromJson(centroidsSerialized, Object[].class);

            for (Object obj : deserialized) {
                // result we get is of the form List<result>
                List l = ((List) obj);
                centroidsSerialized = (String) l.get(0);

                String[] centroidSerializedArrays = centroidsSerialized
                        .split(MlStormClustererQuery.KmeansClustererQuery.CENTROID_DELIM);
                List<double[]> centroids = new ArrayList<double[]>();
                for (String centroid : centroidSerializedArrays) {
                    centroids.add(MlStormFeatureVectorUtils.deserializeToFeatureVector(centroid));
                }

                double[] rmsdPrimitive = ArrayUtils.toPrimitive(both);
                double[] rmsdKmeans = new double[centroids.size()];

                for (int k = 0; k < centroids.size(); k++) {
                    System.out.println("centroid        -- " + Arrays.toString(centroids.get(k)));
                    double[] centroid = centroids.get(k);
                    rmsdKmeans[k] = computeRootMeanSquare(centroid);
                }

                System.out.println("1 rmsd original -- " + Arrays.toString(rmsd));
                System.out.println("2 rmsd k- Means -- " + Arrays.toString(rmsdKmeans));
                System.out.println();
            }

        }
    }
    client.close();
}

From source file:com.github.xbn.examples.testdev.ReplaceAllIndentTabsWithSpacesXmpl.java

public static final void main(String[] directoryRoot_paramIdxZero) {
    //Setup and protection
    String dirRoot = GetFromCommandLineAtIndex.text(directoryRoot_paramIdxZero, 0, "directoryRoot_paramIdxZero",
            null);//from  www.j  a  va  2s  . c  om

    System.out.println("This example code will overwrite the files in \"" + dirRoot
            + "\". Enter the number 1234567890 to proceed.");
    if (!new Scanner(System.in).nextLine().equals("1234567890")) {
        System.out.println("Abort.");
        return;
    }

    Path dirPath = new PathMustBe().existing().writable().directory().noFollowLinks().getOrCrashIfBad(dirRoot,
            "directoryRoot_paramIdxZero[0]");

    File fileRootDir = new File(dirRoot);

    //Go

    IOFileFilter allFileTypesKeepFilter = FileFilterUtils.and(FileFilterUtils.suffixFileFilter(".java"),
            FileFilterUtils.suffixFileFilter(".html"));

    Iterator<File> fileItr = FileUtils.iterateFiles(fileRootDir, allFileTypesKeepFilter, null);

    new ReplaceAllIndentTabsWithSpaces(3, System.out, TabToSpaceDebugLevel.FILE_SUMMARIES)
            .overwriteDirectory(fileItr);
}

From source file:com.japp.Main.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments//from www . j  a  va2  s  . c o m
 */
public static void main(final String... args) {

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("\n========================================================="
                + "\n                                                         "
                + "\n       SFTP-File Transfer POC                 "
                + "\n                                                         "
                + "\n=========================================================");
    }

    final AbstractApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:/launch-context.xml");

    context.registerShutdownHook();

    SpringIntegrationUtils.displayDirectories(context);

    final Scanner scanner = new Scanner(System.in);

    JobLauncher jobLauncher = context.getBean("jobLauncher", JobLauncher.class);
    Job job = context.getBean("job1", Job.class);

    try {
        jobLauncher.run(job, new JobParameters());
    } catch (JobExecutionAlreadyRunningException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (JobRestartException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (JobInstanceAlreadyCompleteException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (JobParametersInvalidException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("\n========================================================="
                + "\n                                                         "
                + "\n    Please press 'q + Enter' to quit the application.    "
                + "\n                                                         "
                + "\n=========================================================");
    }

    while (!scanner.hasNext("q")) {
        //Do nothing unless user presses 'q' to quit.
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Exiting application...bye.");
    }

    System.exit(0);

}