Example usage for java.lang Integer parseInt

List of usage examples for java.lang Integer parseInt

Introduction

In this page you can find the example usage for java.lang Integer parseInt.

Prototype

public static int parseInt(String s) throws NumberFormatException 

Source Link

Document

Parses the string argument as a signed decimal integer.

Usage

From source file:Connect.java

public static void main(String[] args) {
    try { // Handle exceptions below
        // Get our command-line arguments
        String hostname = args[0];
        int port = Integer.parseInt(args[1]);
        String message = "";
        if (args.length > 2)
            for (int i = 2; i < args.length; i++)
                message += args[i] + " ";

        // Create a Socket connected to the specified host and port.
        Socket s = new Socket(hostname, port);

        // Get the socket output stream and wrap a PrintWriter around it
        PrintWriter out = new PrintWriter(s.getOutputStream());

        // Sent the specified message through the socket to the server.
        out.print(message + "\r\n");
        out.flush(); // Send it now.

        // Get an input stream from the socket and wrap a BufferedReader
        // around it, so we can read lines of text from the server.
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        // Before we start reading the server's response tell the socket
        // that we don't want to wait more than 3 seconds
        s.setSoTimeout(3000);//from  www.ja v  a2s .  com

        // Now read lines from the server until the server closes the
        // connection (and we get a null return indicating EOF) or until
        // the server is silent for 3 seconds.
        try {
            String line;
            while ((line = in.readLine()) != null)
                // If we get a line
                System.out.println(line); // print it out.
        } catch (SocketTimeoutException e) {
            // We end up here if readLine() times out.
            System.err.println("Timeout; no response from server.");
        }

        out.close(); // Close the output stream
        in.close(); // Close the input stream
        s.close(); // Close the socket
    } catch (IOException e) { // Handle IO and network exceptions here
        System.err.println(e);
    } catch (NumberFormatException e) { // Bad port number
        System.err.println("You must specify the port as a number");
    } catch (ArrayIndexOutOfBoundsException e) { // wrong # of args
        System.err.println("Usage: Connect <hostname> <port> message...");
    }
}

From source file:RunMuleClient.java

/**
 * @param args//  w  w w  .j a v a2s .c om
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    if (args.length == 2) {
        MAX = Integer.parseInt(args[0]);
        NUM = Integer.parseInt(args[1]);
    }

    //String path = "./conf/mule-telnet-sample-client.xml";
    String path = "./mule-telnet-sample-client.xml";
    client = new MuleClient(path);
    client.getMuleContext().start();
    Thread[] list = new Thread[NUM];
    for (int i = 0; i < NUM; i++) {
        list[i] = new Thread(new RunMuleClient());
    }
    for (Thread th : list) {
        th.start();
    }
    for (Thread th : list) {
        th.join();
    }
    client.getMuleContext().dispose();
    client.dispose();
    log();
    return;
}

From source file:Main.java

public static void main(String... args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel contentPane = new JPanel();
    contentPane.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
    JTextField tfield1 = new JTextField(10);
    JTextField tfield2 = new JTextField(10);

    FocusListener tfieldListener = new FocusListener() {
        @Override//  w  w  w .  j  av  a 2 s  .  c o  m
        public void focusGained(FocusEvent fe) {
        }

        @Override
        public void focusLost(FocusEvent fe) {
            String num1 = tfield1.getText().trim();
            String num2 = tfield2.getText().trim();
            if (num1 == null || num1.equals(""))
                num1 = "0";
            if (num2 == null || num2.equals(""))
                num2 = "0";
            System.out.println(Integer.toString(Integer.parseInt(num1) + Integer.parseInt(num2)));
        }
    };

    tfield1.addFocusListener(tfieldListener);
    tfield2.addFocusListener(tfieldListener);

    ((AbstractDocument) tfield1.getDocument()).setDocumentFilter(new MyDocumentFilter());
    ((AbstractDocument) tfield2.getDocument()).setDocumentFilter(new MyDocumentFilter());

    contentPane.add(tfield1);
    contentPane.add(tfield2);

    frame.setContentPane(contentPane);
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
}

From source file:UDPSend.java

public static void main(String args[]) {
    try {/*  w  w w.  j a  v  a2  s. com*/
        // Check the number of arguments
        if (args.length < 3)
            throw new IllegalArgumentException("Wrong number of args");

        // Parse the arguments
        String host = args[0];
        int port = Integer.parseInt(args[1]);

        // Figure out the message to send.
        // If the third argument is -f, then send the contents of the file
        // specified as the fourth argument. Otherwise, concatenate the
        // third and all remaining arguments and send that.
        byte[] message;
        if (args[2].equals("-f")) {
            File f = new File(args[3]);
            int len = (int) f.length(); // figure out how big the file is
            message = new byte[len]; // create a buffer big enough
            FileInputStream in = new FileInputStream(f);
            int bytes_read = 0, n;
            do { // loop until we've read it all
                n = in.read(message, bytes_read, len - bytes_read);
                bytes_read += n;
            } while ((bytes_read < len) && (n != -1));
        } else { // Otherwise, just combine all the remaining arguments.
            String msg = args[2];
            for (int i = 3; i < args.length; i++)
                msg += " " + args[i];
            // Convert the message to bytes using UTF-8 encoding
            message = msg.getBytes("UTF-8");
        }

        // Get the internet address of the specified host
        InetAddress address = InetAddress.getByName(host);

        // Initialize a datagram packet with data and address
        DatagramPacket packet = new DatagramPacket(message, message.length, address, port);

        // Create a datagram socket, send the packet through it, close it.
        DatagramSocket dsocket = new DatagramSocket();
        dsocket.send(packet);
        dsocket.close();
    } catch (Exception e) {
        System.err.println(e);
        System.err.println(usage);
    }
}

From source file:Main.java

public static void main(String[] args) {
    int port = Integer.parseInt(args[0]);

    try {//from  w  w  w.  ja  v a2 s  . c om
        Thread t = new Main(port);
        t.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    int port = Integer.parseInt(args[0]);

    try {//from  w  w w.ja v a  2 s. c  o m
        Thread t = new MainClass(port);
        t.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:SimpleDaytimeServer.java

public static void main(String args[]) throws java.io.IOException {
    // RFC867 specifies port 13 for this service. On Unix platforms,
    // you need to be running as root to use that port, so we allow
    // this service to use other ports for testing.
    int port = 13;
    if (args.length > 0)
        port = Integer.parseInt(args[0]);

    // Create a channel to listen for connections on.
    ServerSocketChannel server = ServerSocketChannel.open();

    // Bind the channel to a local port. Note that we do this by obtaining
    // the underlying java.net.ServerSocket and binding that socket.
    server.socket().bind(new InetSocketAddress(port));

    // Get an encoder for converting strings to bytes
    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();

    for (;;) { // Loop forever, processing client connections
        // Wait for a client to connect
        SocketChannel client = server.accept();

        // Build response string, wrap, and encode to bytes
        String date = new java.util.Date().toString() + "\r\n";
        ByteBuffer response = encoder.encode(CharBuffer.wrap(date));

        // Send the response to the client and disconnect.
        client.write(response);//from  w w  w  .j ava2 s. c  o  m
        client.close();
    }
}

From source file:uk.co.techsols.mentis.worker.Main.java

public static void main(String args[]) {

    if (args.length != 3) {
        System.out.println(//from www .j  a v a 2 s  .  c o  m
                "Usage: type url cores\n\ttype:\n\t\tr - renderer\n\t\tt - transformer\n\turl: the url to Eiocha.\n\tcores: the number of cores to use\n\n\te.g. node.jar t http://localhost:8080/server 4\n\n");
        System.exit(1);
        return;
    }

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/applicationContext.xml");
    Worker worker;
    switch (args[0]) {
    case "r":
        worker = applicationContext.getBean("renderWorker", Worker.class);
        break;
    case "t":
        worker = applicationContext.getBean("transformWorker", Worker.class);
        break;
    default:
        System.out.println("Error: unreconised worker type.");
        System.exit(1);
        return;
    }

    worker.setup(URI.create(args[1]), Integer.parseInt(args[2]));
}

From source file:org.eclipse.swt.snippets.Snippet369.java

public static void main(String[] args) throws Exception {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 369");
    shell.setLayout(new FillLayout());
    shell.setText("Line spacing provider in action");

    StyledText text = new StyledText(shell, SWT.BORDER | SWT.V_SCROLL);
    text.setText("// Type your custom line spacing \n10\n5\nabcd\n20\nefgh");

    text.setLineSpacingProvider(lineIndex -> {
        String line = text.getLine(lineIndex).trim();
        try {/*w  w w .  jav a  2s .  c  o  m*/
            return Integer.parseInt(line);
        } catch (NumberFormatException e) {
            return null;
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:mosaicsimulation.MosaicLockstepServer.java

public static void main(String[] args) {
    Options opts = new Options();
    opts.addOption("s", "serverPort", true, "Listening TCP port used to initiate handshakes");
    opts.addOption("n", "nClients", true, "Number of clients that will participate in the session");
    opts.addOption("t", "tickrate", true, "Number of transmission session to execute per second");
    opts.addOption("m", "maxUDPPayloadLength", true, "Max number of bytes per UDP packet");
    opts.addOption("c", "connectionTimeout", true, "Timeout for UDP connections");

    DefaultParser parser = new DefaultParser();
    CommandLine commandLine = null;/*from w  w  w.  j av  a  2s  .c o m*/
    try {
        commandLine = parser.parse(opts, args);
    } catch (ParseException ex) {
        ex.printStackTrace();
        System.exit(1);
    }

    int serverPort = Integer.parseInt(commandLine.getOptionValue("serverPort"));
    int nClients = Integer.parseInt(commandLine.getOptionValue("nClients"));
    int tickrate = Integer.parseInt(commandLine.getOptionValue("tickrate"));
    int maxUDPPayloadLength = Integer.parseInt(commandLine.getOptionValue("maxUDPPayloadLength"));
    int connectionTimeout = Integer.parseInt(commandLine.getOptionValue("connectionTimeout"));

    Thread serverThread = LockstepServer.builder().clientsNumber(nClients).tcpPort(serverPort)
            .tickrate(tickrate).maxUDPPayloadLength(maxUDPPayloadLength).connectionTimeout(connectionTimeout)
            .build();

    serverThread.setName("Main-server-thread");
    serverThread.start();

    try {
        serverThread.join();
    } catch (InterruptedException ex) {
        LOG.error("Server interrupted while joining");
    }
}