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:Main.java

public static void main(String[] args) {

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

    Scanner scanner = new Scanner(s);

    while (scanner.hasNext()) {

        // if the next is byte with radix 7, print found and the byte
        if (scanner.hasNextByte()) {
            System.out.println("Found :" + scanner.nextByte(7));
        }//from  w w w  .ja  v  a2  s .com

        // if a Byte is not found, print "Not Found" and the token
        System.out.println("Not Found :" + scanner.next());
    }

    scanner.close();
}

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

    while (scanner.hasNext()) {

        // if the next is BigDecimal, print found and the decimal
        if (scanner.hasNextBigDecimal()) {
            System.out.println("Found :" + scanner.nextBigDecimal());
        }/*from   w w w  .j  a v a 2s .c om*/

        // if a BigDecimal is not found, print "Not Found" and the token
        System.out.println("Not Found :" + scanner.next());
    }

    scanner.close();
}

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

    while (scanner.hasNext()) {

        // if the next is BigInteger, print "Found" and the Integer
        if (scanner.hasNextBigInteger()) {
            System.out.println("Found :" + scanner.nextBigInteger());
        }//w w w  . ja  va  2  s  . co  m

        // if a BigInteger is not found, print "Not Found" and the token
        System.out.println("Not Found :" + scanner.next());
    }
    scanner.close();
}

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

    scanner.useLocale(Locale.US);

    while (scanner.hasNext()) {

        // if the next is a double, print found and the double
        if (scanner.hasNextDouble()) {
            System.out.println("Found :" + scanner.nextDouble());
        }/*  w  ww. j a v  a2 s.co m*/

        // if a double is not found, print "Not Found" and the token
        System.out.println("Not Found :" + scanner.next());
    }

    scanner.close();
}

From source file:MainClass.java

public static void main(String args[]) throws IOException {
    // Write output to a file.
    FileWriter fout = new FileWriter("test.txt");
    fout.write("int: 1  double 1.0  boolean true");
    fout.close();/*from   w w w.jav a 2  s .c  o m*/

    FileReader fin = new FileReader("Test.txt");

    Scanner src = new Scanner(fin);

    while (src.hasNext()) {
        if (src.hasNextInt()) {
            System.out.println("int: " + src.nextInt());
        } else if (src.hasNextDouble()) {
            System.out.println("double: " + src.nextDouble());
        } else if (src.hasNextBoolean()) {
            System.out.println("boolean: " + src.nextBoolean());
        } else {
            System.out.println(src.next());
        }
    }
    fin.close();
}

From source file:ScanMixed.java

public static void main(String args[]) throws IOException {
    int i;// w w w .j  a v  a 2s.  c  o m
    double d;
    boolean b;
    String str;

    FileWriter fout = new FileWriter("test.txt");
    fout.write("Testing Scanner 10 12.2 one true two false");
    fout.close();

    FileReader fin = new FileReader("Test.txt");

    Scanner src = new Scanner(fin);

    while (src.hasNext()) {
        if (src.hasNextInt()) {
            i = src.nextInt();
            System.out.println("int: " + i);
        } else if (src.hasNextDouble()) {
            d = src.nextDouble();
            System.out.println("double: " + d);
        } else if (src.hasNextBoolean()) {
            b = src.nextBoolean();
            System.out.println("boolean: " + b);
        } else {
            str = src.next();
            System.out.println("String: " + str);
        }
    }

    fin.close();
}

From source file:MainClass.java

public static void main(String args[]) throws IOException {
    int i;//from   w  w  w.j a  va2s  . co m
    double d;
    boolean b;
    String str;

    FileWriter fout = new FileWriter("test.txt");
    fout.write("string true false 1 2 3 4.12");
    fout.close();

    FileReader fin = new FileReader("Test.txt");

    Scanner src = new Scanner(fin);

    while (src.hasNext()) {
        if (src.hasNextInt()) {
            i = src.nextInt();
            System.out.println("int: " + i);
        } else if (src.hasNextDouble()) {
            d = src.nextDouble();
            System.out.println("double: " + d);
        } else if (src.hasNextBoolean()) {
            b = src.nextBoolean();
            System.out.println("boolean: " + b);
        } else {
            str = src.next();
            System.out.println("String: " + str);
        }
    }

    fin.close();
}

From source file:MainClass.java

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

    int i;/*from   www  .  j  a va 2s .c  o  m*/
    double d;
    boolean b;
    String str;

    FileWriter fout = new FileWriter("test.txt");
    fout.write("Testing Scanner 10 12.2 one true two false");
    fout.close();

    FileReader fin = new FileReader("Test.txt");

    Scanner src = new Scanner(fin);

    while (src.hasNext()) {
        if (src.hasNextInt()) {
            i = src.nextInt();
            System.out.println("int: " + i);
        } else if (src.hasNextDouble()) {
            d = src.nextDouble();
            System.out.println("double: " + d);
        } else if (src.hasNextBoolean()) {
            b = src.nextBoolean();
            System.out.println("boolean: " + b);
        } else {
            str = src.next();
            System.out.println("String: " + str);
        }
    }

    fin.close();
}

From source file:org.slc.sli.encryption.tool.Encryptor.java

/**
 * New functionality allows encrypting using the same algorithm
 * the api uses for encrypting PII fields in MongoDB.
 *
 * for example:// www  .j  ava  2  s. c o  m
  java -jar encryption-tool.java --decrypt
  ../data-access/dal/keyStore/localKeyStore.jks
  ../data-access/dal/keyStore/localEncryption.properties
  aDvgicSt81j/YdPUhvr4Ig==
        
 * or to encrypt:
  java -jar encryption-tool.java
  ../data-access/dal/keyStore/localKeyStore.jks
  ../data-access/dal/keyStore/localEncryption.properties
  Lauretta
        
 * you can also exclude the message at the end, then this program works
 * in streaming mode: every line received from System.in is en/decrypted
 * and returned to System.out
        
 * @param args
 * @throws Exception
 */

public static void main(String[] args) throws Exception {
    PrintStream out = System.out;
    if (args.length < 2 || args.length > 6) {
        out.println("For encryption:");
        out.println(
                "Usage: java -jar encryption-tool.jar <keystore_location> <keystore_password> <key_alias> <key_password> <string>");
        out.println("For decryption");
        out.println(
                "Usage: java -jar encryption-tool.jar --decrypt <keystore_location> <keystore_password> <key_alias> <key_password> <string>");
        out.println();
        out.println("Using a properties file: \n  Property names must end with the following values. ");
        out.println("  " + KEYSTOREPASS + " (required)");
        out.println("  " + DALKEYALIAS + " (required)");
        out.println("  " + DALKEYPASS + " (required) ");
        out.println("  " + DALINITVEC + " (optional)");
        out.println("  " + DALALGORITHM + "(optional, defaults to \"AES/CBC/PKCS5Padding\")");

        out.println("Encryption:");
        out.println(
                "  Usage: java jar encyption-tool-1.0-jar <keystore_location> <properties_file> [<string>]");
        out.println("Decryption:");
        out.println(
                "  Usage: java jar encyption-tool-1.0-jar -decrypt <keystore_location> <properties_file> [<string>]");

        return;
    }

    boolean decrypt = false;
    String[] effectiveArgs = args;
    if (args[0].equals("--decrypt")) {
        decrypt = true;
        effectiveArgs = new String[args.length - 1];
        System.arraycopy(args, 1, effectiveArgs, 0, args.length - 1);
    }

    String propertiesLocation = null;
    String keystoreLocation = null;
    String keystorePassword = null;
    String keyAlias = null;
    String keyPassword = null;
    String message = null;
    String initVector = null;
    String algorithm = "AES/CBC/PKCS5Padding";

    if (args.length == 5 || args.length == 6) {
        //OLDER FUNCTIONALITY
        keystoreLocation = effectiveArgs[0];
        keystorePassword = effectiveArgs[1];
        keyAlias = effectiveArgs[2];
        keyPassword = effectiveArgs[3];
        message = effectiveArgs[4];

        Encryptor encryptor = new Encryptor(keystoreLocation, keystorePassword);

        if (!decrypt) {
            String encryptedString = encryptor.encrypt(keyAlias, keyPassword, message);
            out.println("Encrypted string for " + message + " is: " + encryptedString + "\n");
        } else {
            String decryptedString = encryptor.decrypt(keyAlias, keyPassword, message);
            out.println("Descrypted string for " + message + " is: " + decryptedString + "\n");
        }

    } else {
        //NEWER FUNCTIONALITY
        keystoreLocation = effectiveArgs[0];
        propertiesLocation = effectiveArgs[1];

        if (effectiveArgs.length == 3) {
            message = effectiveArgs[2];
        } else {
            message = null;
        }

        Map<String, String> properties = parsePropertiesFile(propertiesLocation);

        keystorePassword = properties.get(KEYSTOREPASS);
        keyPassword = properties.get(DALKEYPASS);
        keyAlias = properties.get(DALKEYALIAS);

        if (properties.containsKey(DALINITVEC)) {
            initVector = properties.get(DALINITVEC);
        }
        if (properties.containsKey(DALALGORITHM)) {
            algorithm = properties.get(DALALGORITHM);
        }

        Encryptor encryptor = new Encryptor(keystoreLocation, keystorePassword);

        if (!decrypt) {
            if (message != null) {
                String encrypted = encryptor.encrypt(keyAlias, keyPassword, algorithm, initVector, message);
                out.println(encrypted);
            } else {
                Scanner s = new Scanner(System.in);
                s.useDelimiter("\n");
                while (s.hasNext()) {
                    String cleartext = s.next();
                    String encrypted = encryptor.encrypt(keyAlias, keyPassword, algorithm, initVector,
                            cleartext);
                    out.println(encrypted);
                }
            }
        } else {
            if (message != null) {
                String decrypted = encryptor.decrypt(keyAlias, keyPassword, algorithm, initVector, message);
                out.println(decrypted);
            } else {
                Scanner s = new Scanner(System.in);
                s.useDelimiter("\n");
                while (s.hasNext()) {
                    String ciphertext = s.next().trim();
                    String decrypted = encryptor.decrypt(keyAlias, keyPassword, algorithm, initVector,
                            ciphertext);
                    out.println(decrypted);
                }
            }
        }
    }
}

From source file:AwsConsoleApp.java

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

    System.out.println("===========================================");
    System.out.println("Welcome to the AWS VPN connection creator");
    System.out.println("===========================================");

    init();/*from ww  w  .  j a v  a  2  s  . c  om*/
    List<String> CIDRblocks = new ArrayList<String>();
    String vpnType = null;
    String vpnGatewayId = null;
    String customerGatewayId = null;
    String customerGatewayInfoPath = null;
    String routes = null;

    options.addOption("h", "help", false, "show help.");
    options.addOption("vt", "vpntype", true, "Set vpn tunnel type e.g. (ipec.1)");
    options.addOption("vgw", "vpnGatewayId", true, "Set AWS VPN Gateway ID e.g. (vgw-eca54d85)");
    options.addOption("cgw", "customerGatewayId", true, "Set AWS Customer Gateway ID e.g. (cgw-c16e87a8)");
    options.addOption("r", "staticroutes", true, "Set static routes e.g. cutomer subnet 10.77.77.0/24");
    options.addOption("vi", "vpninfo", true, "path to vpn info file c:\\temp\\customerGatewayInfo.xml");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    // Parse command line options
    try {
        cmd = parser.parse(options, args);

        if (cmd.hasOption("h"))
            help();

        if (cmd.hasOption("vt")) {
            log.log(Level.INFO, "Using cli argument -vt=" + cmd.getOptionValue("vt"));

            vpnType = cmd.getOptionValue("vt");

            // Whatever you want to do with the setting goes here
        } else {
            log.log(Level.SEVERE, "Missing vt option");
            help();
        }

        if (cmd.hasOption("vgw")) {
            log.log(Level.INFO, "Using cli argument -vgw=" + cmd.getOptionValue("vgw"));
            vpnGatewayId = cmd.getOptionValue("vgw");
        } else {
            log.log(Level.SEVERE, "Missing vgw option");
            help();
        }

        if (cmd.hasOption("cgw")) {
            log.log(Level.INFO, "Using cli argument -cgw=" + cmd.getOptionValue("cgw"));
            customerGatewayId = cmd.getOptionValue("cgw");

        } else {
            log.log(Level.SEVERE, "Missing cgw option");
            help();
        }

        if (cmd.hasOption("r")) {
            log.log(Level.INFO, "Using cli argument -r=" + cmd.getOptionValue("r"));
            routes = cmd.getOptionValue("r");

            String[] routeItems = routes.split(",");
            CIDRblocks = Arrays.asList(routeItems);

        } else {
            log.log(Level.SEVERE, "Missing r option");
            help();
        }

        if (cmd.hasOption("vi")) {
            log.log(Level.INFO, "Using cli argument -vi=" + cmd.getOptionValue("vi"));
            customerGatewayInfoPath = cmd.getOptionValue("vi");

        } else {
            log.log(Level.SEVERE, "Missing vi option");
            help();
        }

    } catch (ParseException e) {
        log.log(Level.SEVERE, "Failed to parse comand line properties", e);
        help();
    }

    /*
     * Amazon VPC
     * Create and delete VPN tunnel to customer VPN hardware
     */
    try {

        //String vpnType = "ipsec.1";
        //String vpnGatewayId = "vgw-eca54d85";
        //String customerGatewayId = "cgw-c16e87a8";
        //List<String> CIDRblocks = new ArrayList<String>();
        //CIDRblocks.add("10.77.77.0/24");
        //CIDRblocks.add("172.16.1.0/24");
        //CIDRblocks.add("172.18.1.0/24");
        //CIDRblocks.add("10.66.66.0/24");
        //CIDRblocks.add("10.8.1.0/24");

        //String customerGatewayInfoPath = "c:\\temp\\customerGatewayInfo.xml";

        Boolean staticRoutesOnly = true;

        List<String> connectionIds = new ArrayList<String>();
        List<String> connectionIdList = new ArrayList<String>();

        connectionIdList = vpnExists(connectionIds);

        if (connectionIdList.size() == 0) {
            CreateVpnConnectionRequest vpnReq = new CreateVpnConnectionRequest(vpnType, customerGatewayId,
                    vpnGatewayId);
            CreateVpnConnectionResult vpnRes = new CreateVpnConnectionResult();

            VpnConnectionOptionsSpecification vpnspec = new VpnConnectionOptionsSpecification();
            vpnspec.setStaticRoutesOnly(staticRoutesOnly);
            vpnReq.setOptions(vpnspec);

            System.out.println("Creating VPN connection");
            vpnRes = ec2.createVpnConnection(vpnReq);
            String vpnConnId = vpnRes.getVpnConnection().getVpnConnectionId();
            String customerGatewayInfo = vpnRes.getVpnConnection().getCustomerGatewayConfiguration();

            //System.out.println("Customer Gateway Info:" + customerGatewayInfo);

            // Write Customer Gateway Info to file
            System.out.println("Writing Customer Gateway Info to file:" + customerGatewayInfoPath);
            try (PrintStream out = new PrintStream(new FileOutputStream(customerGatewayInfoPath))) {
                out.print(customerGatewayInfo);
            }

            System.out.println("Creating VPN routes");
            for (String destCIDR : CIDRblocks) {
                CreateVpnConnectionRouteRequest routeReq = new CreateVpnConnectionRouteRequest();
                CreateVpnConnectionRouteResult routeRes = new CreateVpnConnectionRouteResult();

                routeReq.setDestinationCidrBlock(destCIDR);
                routeReq.setVpnConnectionId(vpnConnId);

                routeRes = ec2.createVpnConnectionRoute(routeReq);
            }

            // Parse XML file
            File file = new File(customerGatewayInfoPath);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(customerGatewayInfoPath);

            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression exprGetipAddress = xpath
                    .compile("/vpn_connection/ipsec_tunnel/vpn_gateway/tunnel_outside_address/ip_address");
            NodeList vpnGateway = (NodeList) exprGetipAddress.evaluate(document, XPathConstants.NODESET);
            if (vpnGateway != null) {
                for (int i = 0; i < vpnGateway.getLength(); i++) {
                    String vpnGatewayIP = vpnGateway.item(i).getTextContent();
                    System.out
                            .println("AWS vpnGatewayIP for tunnel " + Integer.toString(i) + " " + vpnGatewayIP);
                }
            }

            System.out.println("==============================================");

            XPathExpression exprGetKey = xpath.compile("/vpn_connection/ipsec_tunnel/ike/pre_shared_key");
            NodeList presharedKeyList = (NodeList) exprGetKey.evaluate(document, XPathConstants.NODESET);
            if (presharedKeyList != null) {
                for (int i = 0; i < presharedKeyList.getLength(); i++) {
                    String pre_shared_key = presharedKeyList.item(i).getTextContent();
                    System.out.println(
                            "AWS pre_shared_key for tunnel " + Integer.toString(i) + " " + pre_shared_key);
                }
            }

            System.out.println("Creating VPN creation completed!");

        } else {
            boolean yn;
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter yes or no to delete VPN connection: ");
            String input = scan.next();
            String answer = input.trim().toLowerCase();
            while (true) {
                if (answer.equals("yes")) {
                    yn = true;
                    break;
                } else if (answer.equals("no")) {
                    yn = false;
                    System.exit(0);
                } else {
                    System.out.println("Sorry, I didn't catch that. Please answer yes/no");
                }
            }

            // Delete all existing VPN connections
            System.out.println("Deleting AWS VPN connection(s)");

            for (String vpnConID : connectionIdList) {
                DeleteVpnConnectionResult delVPNres = new DeleteVpnConnectionResult();
                DeleteVpnConnectionRequest delVPNreq = new DeleteVpnConnectionRequest();
                delVPNreq.setVpnConnectionId(vpnConID);

                delVPNres = ec2.deleteVpnConnection(delVPNreq);
                System.out.println("Successfully deleted AWS VPN conntion: " + vpnConID);

            }

        }

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

}