Example usage for java.util Scanner nextInt

List of usage examples for java.util Scanner nextInt

Introduction

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

Prototype

public int nextInt() 

Source Link

Document

Scans the next token of the input as an int .

Usage

From source file:MainClass.java

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

    int x;//ww  w.  j av a  2 s .  com
    int y;
    int z;
    int result;

    System.out.print("Enter first integer: ");
    x = input.nextInt();

    System.out.print("Enter second integer: ");
    y = input.nextInt();

    System.out.print("Enter third integer: ");
    z = input.nextInt();

    result = x * y * z;

    System.out.printf("Product is %d\n", result);

}

From source file:LotteryDrawing.java

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

    System.out.print("How many numbers do you need to draw? ");
    int k = in.nextInt();

    System.out.print("What is the highest number you can draw? ");
    int n = in.nextInt();

    // fill an array with numbers 1 2 3 . . . n
    int[] numbers = new int[n];
    for (int i = 0; i < numbers.length; i++)
        numbers[i] = i + 1;/*  w  w  w  . j  a  v  a2s . c  o  m*/

    // draw k numbers and put them into a second array
    int[] result = new int[k];
    for (int i = 0; i < result.length; i++) {
        // make a random index between 0 and n - 1
        int r = (int) (Math.random() * n);

        // pick the element at the random location
        result[i] = numbers[r];

        // move the last element into the random location
        numbers[r] = numbers[n - 1];
        n--;
    }

    // print the sorted array
    Arrays.sort(result);
    System.out.println("Bet the following combination. It'll make you rich!");
    for (int r : result)
        System.out.println(r);
}

From source file:MainClass.java

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

    int number1;//from www.j  a v a  2  s  .c  om
    int number2;

    System.out.print("Enter first integer: "); // prompt 
    number1 = input.nextInt(); // read first number from user 

    System.out.print("Enter second integer: "); // prompt 
    number2 = input.nextInt(); // read second number from user 

    if (number1 == number2)
        System.out.printf("%d == %d\n", number1, number2);

    if (number1 != number2)
        System.out.printf("%d != %d\n", number1, number2);

    if (number1 < number2)
        System.out.printf("%d < %d\n", number1, number2);

    if (number1 > number2)
        System.out.printf("%d > %d\n", number1, number2);

    if (number1 <= number2)
        System.out.printf("%d <= %d\n", number1, number2);

    if (number1 >= number2)
        System.out.printf("%d >= %d\n", number1, number2);

}

From source file:Main.java

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

    System.out.print("Username: ");
    String username = scanner.nextLine();

    System.out.print("Password: ");
    String password = scanner.nextLine();

    System.out.print("What is 2 + 2: ");
    int result = scanner.nextInt();

    if (username.equals("admin") && password.equals("secret") && result == 4) {
        System.out.println("Welcome");
    } else {//w w  w . j a  v a  2s  .com
        System.out.println("Invalid username or password!");
    }
}

From source file:bundestagswahl.benchmark.BWBenchmark.java

public static void main(String[] args) throws Exception {

    resultTime = new double[6];

    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter URL: ");
    serverUrl = scanner.nextLine();/*  w  w w  .  ja  va 2  s . co  m*/
    System.out.print("Please enter number of terminals: ");
    numberTerminals = scanner.nextInt();
    System.out.print("Please enter number of requests: ");
    numberRequests = scanner.nextInt();
    System.out.print("Please enter delay between two requests in seconds: ");
    requestDelay = scanner.nextDouble();
    scanner.close();

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    cm.setMaxTotal(numberTerminals);
    HttpClient httpclient = new DefaultHttpClient(cm);
    httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 300000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 300000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
    try {
        final CountDownLatch latch = new CountDownLatch(numberTerminals);
        for (int i = 0; i < numberTerminals; i++) {
            BenchmarkTerminal terminal = new BenchmarkTerminal(httpclient, latch, serverUrl, numberRequests,
                    requestDelay);
            terminal.start();
        }
        latch.await();
        httpclient.getConnectionManager().shutdown();
    } finally {

    }

    printResultTimes();
    System.out.println(" ");
    System.out.println("Done");
}

From source file:view.CLVideoPublisher.java

/**
 * Launch the application.// w  w w.j  a  v a2s  .  c  om
 * @throws DecoderException 
 * @throws UnsupportedEncodingException 
 * @throws NoSuchAlgorithmException 
 */
public static void main(String[] args)
        throws DecoderException, NoSuchAlgorithmException, UnsupportedEncodingException {
    CLVideoPublisher pub = new CLVideoPublisher();

    //      Implement the command line interface.
    while (true) {
        // print out commands
        System.err.println(pub.commandList());
        // wait for input
        Scanner sc = new Scanner(System.in);
        int i = sc.nextInt();
        // deal with input
        switch (i) {
        case 1: // Print the list
            // refresh the list.
            pub.populatePublishList();
            System.err.println("\n\n----------Publications----------");
            System.err.println(pub.getList());
            break;
        case 2: // Add a publication
            System.err.println("\nEnter location of publication in folder ("
                    + ProjectPropertiesSingleton.getInstance().getProperty("DefaultMovieFolder") + ")");
            String pubPath = ProjectPropertiesSingleton.getInstance().getProperty("DefaultMovieFolder")
                    + sc.next();
            // Check the file exists.
            File file = new File(pubPath);
            if (!file.exists()) {
                System.err.println("File does not exist. Returning...");
                break;
            }
            // publish the event. Under root for now...
            String newPubIDString = pub.rootGenerator.getNextID(pubPath, IDStrategy.RANDOM);
            pub.videoPublisher.publishVideo(newPubIDString, pubPath);
            pub.populatePublishList();
            System.err.println("done...");
            break;
        case 3: // Remove a publication
            // refresh the list.
            pub.populatePublishList();
            System.err.println("\n\n----------Publications----------");
            System.err.println(pub.getList());
            System.err.println("Enter the number of the publication to remove...");
            // check something has been selected
            int selected = sc.nextInt();
            String selectedS = pub.listMappings.get(selected);
            if (selectedS == null) {
                System.err.println("Not a valid selection. Returning...");
                break;
            }
            System.err.println("You have selected " + selectedS + " for removal. Continue... (Y or N)");
            String response = sc.next();
            if (response.equalsIgnoreCase("n")) {
                System.err.println("Returning...");
                break;
            } else if (response.equalsIgnoreCase("y")) {
                // unpublish the item.
                String rid = pub.ridMappings.get(selectedS);
                try {
                    pub.videoPublisher.unpublishVideo(rid);
                } catch (DecoderException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            } else {
                System.err.println("Did not understand. Returning...");
                break;
            }
            break;
        case 4: // Exit
            System.err.println("Exiting...");
            pub.getClient().disconnect();
            System.exit(0);
            break;
        }
    }
}

From source file:com.left8.evs.evs.EvS.java

/**
 * Main method that provides a simple console input interface for the user,
 * if she wishes to execute the tool as a .jar executable.
 * @param args A list of arguments./*w w w .j  a v  a 2s .  c  om*/
 * @throws org.apache.commons.cli.ParseException ParseExcetion
 */
public static void main(String[] args) throws ParseException {

    Config config = null;
    try {
        config = new Config();
    } catch (IOException ex) {
        Utilities.printMessageln("Configuration file 'config.properties' " + "not in classpath!");
        Logger.getLogger(EvS.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(1);
    }

    if (args.length != 0) { //If the user supplied arguments
        Console console = new Console(args, config); //Read the console

        showMongoLogging = console.showMongoLogging();
        showInlineInfo = console.showInlineInfo();
        hasExtCommands = console.hasExternalCommands();
        choice = console.getChoiceValue();
    }

    if (!showMongoLogging) {
        //Stop reporting logging information
        Logger mongoLogger = Logger.getLogger("org.mongodb.driver");
        mongoLogger.setLevel(Level.SEVERE);
    }

    System.out.println("\n----EvS----");

    if (!hasExtCommands) {
        System.out.println("Select one of the following options");
        System.out.println("1. Run Offline Peak Finding experiments.");
        System.out.println("2. Run EDCoW experiments.");
        System.out.println("3. Run each of the above methods without " + "the sentiment annotations.");
        System.out.println("Any other key to exit.");
        System.out.println("");
        System.out.print("Your choice: ");

        Scanner keyboard = new Scanner(System.in);
        choice = keyboard.nextInt();
    }

    switch (choice) {
    case 1: { //Offline Peak Finding
        int window = 10;
        double alpha = 0.85;
        int taph = 1;
        int pi = 5;
        Dataset ds = new Dataset(config);
        PeakFindingCorpus corpus = new PeakFindingCorpus(config, ds.getTweetList(), ds.getSWH());
        corpus.createCorpus(window);

        List<BinPair<String, Integer>> bins = BinsCreator.createBins(corpus, config, window);
        PeakFindingSentimentCorpus sCorpus = new PeakFindingSentimentCorpus(corpus);

        SentimentPeakFindingExperimenter exper = new SentimentPeakFindingExperimenter(sCorpus, bins, alpha,
                taph, pi, window, config);

        //Experiment with Taph
        List<String> lines = exper.experimentUsingTaph(1, 10, 1, 0, showInlineInfo);
        exper.exportToFile("stanford.txt", lines);
        lines = exper.experimentUsingTaph(1, 10, 1, 1, showInlineInfo);
        exper.exportToFile("naive_bayes.txt", lines);
        lines = exper.experimentUsingTaph(1, 10, 1, 2, showInlineInfo);
        exper.exportToFile("bayesian_net.txt", lines);

        //Experiment with Alpha
        lines = exper.experimentUsingAlpha(0.85, 0.99, 0.01, 0, showInlineInfo);
        exper.exportToFile("stanford.txt", lines);
        lines = exper.experimentUsingAlpha(0.85, 0.99, 0.01, 1, showInlineInfo);
        exper.exportToFile("naive_bayes.txt", lines);
        lines = exper.experimentUsingAlpha(0.85, 0.99, 0.01, 2, showInlineInfo);
        exper.exportToFile("bayesian_net.txt", lines);

        break;
    }
    case 2: { //EDCoW
        Dataset ds = new Dataset(config);
        SentimentEDCoWCorpus corpus = new SentimentEDCoWCorpus(config, ds.getTweetList(), ds.getSWH(), 10);

        corpus.getEDCoWCorpus().createCorpus();
        corpus.getEDCoWCorpus().setDocTermFreqIdList();
        int delta = 5, delta2 = 11, gamma = 6;
        double minTermSupport = 0.001, maxTermSupport = 0.01;

        SentimentEDCoWExperimenter exper = new SentimentEDCoWExperimenter(corpus, delta, delta2, gamma,
                minTermSupport, maxTermSupport, choice, choice, config);

        //Experiment with delta
        List<String> lines = exper.experimentUsingDelta(1, 20, 1, 0, showInlineInfo);
        exper.exportToFile("stanford.txt", lines);
        lines = exper.experimentUsingDelta(1, 20, 1, 1, showInlineInfo);
        exper.exportToFile("naive_bayes.txt", lines);
        lines = exper.experimentUsingDelta(1, 20, 1, 2, showInlineInfo);
        exper.exportToFile("bayesian_net.txt", lines);

        //Experiment with gamma
        lines = exper.experimentUsingGamma(6, 10, 1, 0, showInlineInfo);
        exper.exportToFile("stanford.txt", lines);
        lines = exper.experimentUsingGamma(6, 10, 1, 1, showInlineInfo);
        exper.exportToFile("naive_bayes.txt", lines);
        lines = exper.experimentUsingGamma(6, 10, 1, 2, showInlineInfo);
        exper.exportToFile("bayesian_net.txt", lines);

        break;
    }
    case 3: {
        EDMethodPicker.selectEDMethod(config, showInlineInfo, 0);
        break;
    }
    case 4: { //Directly run OPF
        EDMethodPicker.selectEDMethod(config, showInlineInfo, 1);
        break;
    }
    case 5: { //Directly run EDCoW
        EDMethodPicker.selectEDMethod(config, showInlineInfo, 2);
        break;
    }
    default: {
        System.out.println("Exiting now...");
        System.exit(0);
    }
    }
}

From source file:org.apache.mahout.classifier.sequencelearning.hmm.ViterbiEvaluator.java

public static void main(String[] args) throws IOException {
    DefaultOptionBuilder optionBuilder = new DefaultOptionBuilder();
    ArgumentBuilder argumentBuilder = new ArgumentBuilder();

    Option inputOption = DefaultOptionCreator.inputOption().create();

    Option outputOption = DefaultOptionCreator.outputOption().create();

    Option modelOption = optionBuilder.withLongName("model").withDescription("Path to serialized HMM model")
            .withShortName("m")
            .withArgument(argumentBuilder.withMaximum(1).withMinimum(1).withName("path").create())
            .withRequired(true).create();

    Option likelihoodOption = optionBuilder.withLongName("likelihood")
            .withDescription("Compute likelihood of observed sequence").withShortName("l").withRequired(false)
            .create();//from w  w w.  j  av  a 2 s  . c o m

    Group optionGroup = new GroupBuilder().withOption(inputOption).withOption(outputOption)
            .withOption(modelOption).withOption(likelihoodOption).withName("Options").create();

    try {
        Parser parser = new Parser();
        parser.setGroup(optionGroup);
        CommandLine commandLine = parser.parse(args);

        String input = (String) commandLine.getValue(inputOption);
        String output = (String) commandLine.getValue(outputOption);

        String modelPath = (String) commandLine.getValue(modelOption);

        boolean computeLikelihood = commandLine.hasOption(likelihoodOption);

        //reading serialized HMM
        DataInputStream modelStream = new DataInputStream(new FileInputStream(modelPath));
        HmmModel model;
        try {
            model = LossyHmmSerializer.deserialize(modelStream);
        } finally {
            Closeables.close(modelStream, true);
        }

        //reading observations
        List<Integer> observations = Lists.newArrayList();
        Scanner scanner = new Scanner(new FileInputStream(input), "UTF-8");
        try {
            while (scanner.hasNextInt()) {
                observations.add(scanner.nextInt());
            }
        } finally {
            scanner.close();
        }

        int[] observationsArray = new int[observations.size()];
        for (int i = 0; i < observations.size(); ++i) {
            observationsArray[i] = observations.get(i);
        }

        //decoding
        int[] hiddenStates = HmmEvaluator.decode(model, observationsArray, true);

        //writing output
        PrintWriter writer = new PrintWriter(
                new OutputStreamWriter(new FileOutputStream(output), Charsets.UTF_8), true);
        try {
            for (int hiddenState : hiddenStates) {
                writer.print(hiddenState);
                writer.print(' ');
            }
        } finally {
            Closeables.close(writer, false);
        }

        if (computeLikelihood) {
            System.out.println("Likelihood: " + HmmEvaluator.modelLikelihood(model, observationsArray, true));
        }
    } catch (OptionException e) {
        CommandLineUtil.printHelp(optionGroup);
    }
}

From source file:OpenDataExtractor.java

public static void main(String[] args) {

    System.out.println("\nSeleziona in che campo fare la ricerca: ");
    System.out.println("Elenco completo delle gare in formato (1)"); // cc16106a-1a65-4c34-af13-cc045d181452
    System.out.println("Composizione delle commissioni giudicatrici (2)"); // c90f1ffb-c315-4f59-b0e3-b0f2f8709127
    System.out.println("Registro delle imprese escluse dalle gare (3)"); // 2ea798cc-1f52-4fc8-a28e-f92a6f409cb8
    System.out.println("Registro delle imprese invitate alle gare (4)"); // a124b6af-ae31-428a-8ac5-bb341feb3c46
    System.out.println("Registro delle imprese che hanno partecipato alle gare (5)");// e58396cf-1145-4cb1-84a4-34311238a0c6
    System.out.println("Anagrafica completa dei contratti per l'acquisizione di beni e servizi (6)"); // aa6a8664-5ef5-43eb-a563-910e25161798
    System.out.println("Fornitori (7)"); // 253c8ac9-8335-4425-84c5-4a90be863c00
    System.out.println("Autorizzazioni subappalti per i lavori  (8)"); // 4f9ba542-5768-4b39-a92a-450c45eabd5d
    System.out.println("Aggiudicazioni delle gare per i lavori (9)"); // 34e298ad-3a99-4feb-9614-b9c4071b9d8e
    System.out.println("Dati cruscotto lavori per area (10)"); // 1ee3ea1b-58e3-48bf-8eeb-36ac313eeaf8
    System.out.println("Dati cruscotto lavori per lotto (11)"); // cbededce-269f-48d2-8c25-2359bf246f42
    int count = 0;
    int scelta;//w w  w .  j  a va 2 s .  c  o m
    String id_ref = "";
    Scanner scanner;

    try {

        do {
            scanner = new Scanner(System.in);
            scelta = scanner.nextInt();
            switch (scelta) {

            case 1:
                id_ref = "cc16106a-1a65-4c34-af13-cc045d181452&q=";
                break;
            case 2:
                id_ref = "c90f1ffb-c315-4f59-b0e3-b0f2f8709127&q=";
                break;
            case 3:
                id_ref = "2ea798cc-1f52-4fc8-a28e-f92a6f409cb8&q=";
                break;
            case 4:
                id_ref = "a124b6af-ae31-428a-8ac5-bb341feb3c46&q=";
                break;
            case 5:
                id_ref = "e58396cf-1145-4cb1-84a4-34311238a0c6&q=";
                break;
            case 6:
                id_ref = "aa6a8664-5ef5-43eb-a563-910e25161798&q=";
                break;
            case 7:
                id_ref = "253c8ac9-8335-4425-84c5-4a90be863c00&q=";
                break;
            case 8:
                id_ref = "4f9ba542-5768-4b39-a92a-450c45eabd5d&q=";
                break;
            case 9:
                id_ref = "34e298ad-3a99-4feb-9614-b9c4071b9d8e&q=";
                break;
            case 10:
                id_ref = "1ee3ea1b-58e3-48bf-8eeb-36ac313eeaf8&q=";
                break;
            case 11:
                id_ref = "cbededce-269f-48d2-8c25-2359bf246f42&q=";
                break;
            default:
                System.out.println("Numero non selezionabile");
                System.out.println("Reinserisci");
                break;

            }
        } while (scelta <= 0 || scelta > 11);

        scanner = new Scanner(System.in);

        System.out.println("Inserisci un parametro di ricerca: ");
        String record = scanner.nextLine();
        String limit = "&limit=10000";
        System.out.println("id di riferimento: " + id_ref);
        System.out.println("___________________________");
        String requestString = "http://dati.openexpo2015.it/catalog/api/action/datastore_search?resource_id="
                + id_ref + record + limit;
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(requestString);
        HttpResponse response = client.execute(request);

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String result = "";
        String resline = "";
        while ((resline = rd.readLine()) != null) {
            result += resline;
        }
        if (result != null) {
            JSONObject jsonObject = new JSONObject(result);
            JSONObject resultJson = (JSONObject) jsonObject.get("result");
            JSONArray resultJsonFields = (JSONArray) resultJson.get("fields");
            ArrayList<TypeFields> type = new ArrayList<TypeFields>();
            TypeFields type1;
            JSONObject temp;

            while (count < resultJsonFields.length()) {

                temp = (JSONObject) resultJsonFields.get(count);
                type1 = new TypeFields(temp.getString("id"), temp.getString("type"));
                type.add(type1);
                count++;
            }

            JSONArray arr = (JSONArray) resultJson.get("records");
            count = 0;

            while (count < arr.length()) {
                System.out.println("Entry numero: " + count);
                temp = (JSONObject) arr.get(count);
                for (TypeFields temp2 : type) {
                    System.out.println(temp2.nameType + ": " + temp.get(temp2.nameType));
                }
                count++;
                System.out.println("--------------------------");

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:zappos.ZapposProblemSolver.java

/**
 * @param args the command line arguments
 *///  ww w  . j  a  va 2 s .  c om

public static void main(String[] args) {

    ZapposProblemSolver problemSolver = new ZapposProblemSolver();
    System.out.println("Enter number of products and total amount ");
    Scanner sin = new Scanner(System.in);
    int no_of_products = sin.nextInt();
    double total_amount = sin.nextDouble();

    if (no_of_products > 0 && total_amount > 0) {
        if (problemSolver.initialize()) {
            problemSolver.getPriceCombinations(no_of_products, total_amount);
            problemSolver.getZapposProductDetails();
            problemSolver.displayZapposProducts();
        }
    } else
        System.out.println("Sorry! No products are found for this input.");

}