List of usage examples for java.lang Integer parseInt
public static int parseInt(String s) throws NumberFormatException
From source file:FactQuoter.java
public static void main(String[] args) throws IOException { // This is how we set things up to read lines of text from the user. BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Loop forever for (;;) {//from www. j a va 2 s . c om // Display a prompt to the user System.out.print("FactQuoter> "); // Read a line from the user String line = in.readLine(); // If we reach the end-of-file, // or if the user types "quit", then quit if ((line == null) || line.equals("quit")) break; // Try to parse the line, and compute and print the factorial try { int x = Integer.parseInt(line); System.out.println(x + "! = " + Factorial4.factorial(x)); } // If anything goes wrong, display a generic error message catch (Exception e) { System.out.println("Invalid Input"); } } }
From source file:com.xpfriend.fixture.runner.example.ExampleJob.java
/** * TEST_FB ???//from w ww . ja va2 s .com * @param args 1:?ID?2:??NAME? */ public static void main(String[] args) throws Exception { if (args.length < 2) { throw new IllegalArgumentException("args.length == " + args.length); } int id = Integer.parseInt(args[0]); String name = args[1]; Connection connection = getConnection(); try { updateDatabase(id, name, connection); connection.commit(); } finally { connection.close(); } }
From source file:example.Publisher.java
public static void main(String[] args) throws Exception { String user = env("ACTIVEMQ_USER", "admin"); String password = env("ACTIVEMQ_PASSWORD", "password"); String host = env("ACTIVEMQ_HOST", "localhost"); int port = Integer.parseInt(env("ACTIVEMQ_PORT", "1883")); final String destination = arg(args, 0, "/topic/event"); int messages = 10000; int size = 256; String DATA = "abcdefghijklmnopqrstuvwxyz"; String body = ""; for (int i = 0; i < size; i++) { body += DATA.charAt(i % DATA.length()); }/*from ww w . j av a2 s.c o m*/ Buffer msg = new AsciiBuffer(body); MQTT mqtt = new MQTT(); mqtt.setHost(host, port); mqtt.setUserName(user); mqtt.setPassword(password); FutureConnection connection = mqtt.futureConnection(); connection.connect().await(); final LinkedList<Future<Void>> queue = new LinkedList<Future<Void>>(); UTF8Buffer topic = new UTF8Buffer(destination); for (int i = 1; i <= messages; i++) { // Send the publish without waiting for it to complete. This allows us // to send multiple message without blocking.. queue.add(connection.publish(topic, msg, QoS.AT_LEAST_ONCE, false)); // Eventually we start waiting for old publish futures to complete // so that we don't create a large in memory buffer of outgoing message.s if (queue.size() >= 1000) { queue.removeFirst().await(); } if (i % 1000 == 0) { System.out.println(String.format("Sent %d messages.", i)); } } queue.add(connection.publish(topic, new AsciiBuffer("SHUTDOWN"), QoS.AT_LEAST_ONCE, false)); while (!queue.isEmpty()) { queue.removeFirst().await(); } connection.disconnect().await(); System.exit(0); }
From source file:io.minimum.minecraft.rbclean.RedisBungeeClean.java
public static void main(String... args) { Options options = new Options(); Option hostOption = new Option("h", "host", true, "Sets the Redis host to use."); hostOption.setRequired(true);//w w w. j a va 2 s . c om options.addOption(hostOption); Option portOption = new Option("p", "port", true, "Sets the Redis port to use."); options.addOption(portOption); Option passwordOption = new Option("w", "password", true, "Sets the Redis password to use."); options.addOption(passwordOption); Option dryRunOption = new Option("d", "dry-run", false, "Performs a dry run (no data is modified)."); options.addOption(dryRunOption); CommandLine commandLine; try { commandLine = new DefaultParser().parse(options, args); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("RedisBungeeClean", options); return; } int port = commandLine.hasOption('p') ? Integer.parseInt(commandLine.getOptionValue('p')) : 6379; try (Jedis jedis = new Jedis(commandLine.getOptionValue('h'), port, 0)) { if (commandLine.hasOption('w')) { jedis.auth(commandLine.getOptionValue('w')); } System.out.println("Fetching UUID cache..."); Map<String, String> uuidCache = jedis.hgetAll("uuid-cache"); Gson gson = new Gson(); // Just in case we need it, compress everything in JSON format. if (!commandLine.hasOption('d')) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); File file = new File("uuid-cache-previous-" + dateFormat.format(new Date()) + ".json.gz"); try { file.createNewFile(); } catch (IOException e) { System.out.println("Can't write backup of the UUID cache, will NOT proceed."); e.printStackTrace(); return; } System.out.println("Creating backup (as " + file.getName() + ")..."); try (OutputStreamWriter bw = new OutputStreamWriter( new GZIPOutputStream(new FileOutputStream(file)))) { gson.toJson(uuidCache, bw); } catch (IOException e) { System.out.println("Can't write backup of the UUID cache, will NOT proceed."); e.printStackTrace(); return; } } System.out.println("Cleaning out the bird cage (this may take a while...)"); int originalSize = uuidCache.size(); for (Iterator<Map.Entry<String, String>> it = uuidCache.entrySet().iterator(); it.hasNext();) { CachedUUIDEntry entry = gson.fromJson(it.next().getValue(), CachedUUIDEntry.class); if (entry.expired()) { it.remove(); } } int newSize = uuidCache.size(); if (commandLine.hasOption('d')) { System.out.println( (originalSize - newSize) + " records would be expunged if a dry run was not conducted."); } else { System.out.println("Expunging " + (originalSize - newSize) + " records..."); Transaction transaction = jedis.multi(); transaction.del("uuid-cache"); transaction.hmset("uuid-cache", uuidCache); transaction.exec(); System.out.println("Expunging complete."); } } }
From source file:Factorial.java
/** * The main method from which the program executes; * it handles all I/O and method execution. * * @param args Arguments received from the command line (one number). * @param factorial The calculated Factorial of args[0]. *//*from w w w .j a va2 s. c o m*/ public static void main(String[] args) { // ensure the user only enters one argument if (args.length == 1) { // ensure the users argument is a number try { // calculate factorial double factorial = calcFactorial(Integer.parseInt(args[0])); System.out.println("The Factorial of " + args[0] + " is " + factorial + "."); } catch (NumberFormatException c) { System.out.println("Your argument must be in " + "the form of an integer when " + "running the program (ex. " + "enter 'java numeric." + "Factorial 5')."); } catch (Exception c) { // used only in GUI } } else { System.out.println("Enter one number as an argument " + "when running the program (ex. " + "enter 'java numeric.Factorial 5')."); } }
From source file:org.eclipse.swt.snippets.Snippet289.java
public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setText("Snippet 289"); shell.setLayout(new FillLayout()); final Combo combo = new Combo(shell, SWT.NONE); combo.setItems("1111", "2222", "3333", "4444"); combo.setText(combo.getItem(0));/*from w w w .j a va 2s.co m*/ combo.addVerifyListener(e -> { String text = combo.getText(); String newText = text.substring(0, e.start) + e.text + text.substring(e.end); try { if (newText.length() != 0) Integer.parseInt(newText); } catch (NumberFormatException ex) { e.doit = false; } }); combo.addTraverseListener(e -> { if (e.detail == SWT.TRAVERSE_RETURN) { e.doit = false; e.detail = SWT.TRAVERSE_NONE; String newText = combo.getText(); try { Integer.parseInt(newText); combo.add(newText); combo.setSelection(new Point(0, newText.length())); } catch (NumberFormatException ex) { } } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
From source file:TreeHeap.java
public static void main(String[] args) { Heap heap = new TreeHeap(5); for (int ai = 0; ai < args.length; ai++) { heap.add(Integer.valueOf(Integer.parseInt(args[ai]))); }//w ww. java 2 s. co m while (!heap.isEmpty()) { System.out.print(heap.extract() + " "); } System.out.println(); }
From source file:org.zaizi.sensefy.api.SensefyResourceApplication.java
public static void main(String[] args) { SpringApplication.run(SensefyResourceApplication.class, args); int port = Integer.parseInt(System.getProperty("jetty.port", "8080")); int requestHeaderSize = Integer.parseInt(System.getProperty("jetty.header.size", "65536")); Server server = new Server(port); server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", -1); ProtectionDomain domain = SensefyResourceApplication.class.getProtectionDomain(); URL location = domain.getCodeSource().getLocation(); // Set request header size // server.getConnectors()[0].setRequestHeaderSize(requestHeaderSize); WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/api"); webapp.setDescriptor(location.toExternalForm() + "/WEB-INF/web.xml"); webapp.setServer(server);/* w w w . j av a 2s . c o m*/ webapp.setWar(location.toExternalForm()); // (Optional) Set the directory the war will extract to. // If not set, java.io.tmpdir will be used, which can cause problems // if the temp directory gets cleaned periodically. // Your build scripts should remove this directory between deployments // webapp.setTempDirectory(new File("/path/to/webapp-directory")); server.setHandler(webapp); try { server.start(); server.join(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:edu.cuhk.hccl.SequenceFileWriter.java
public static void main(String[] args) throws IOException { // Check parameters if (args.length < 3) { System.out.print("Please specify three parameters!"); System.exit(-1);//from www.ja v a 2s . c om } File filesDir = new File(args[0]); String targetDir = args[1]; final int NUM_SPLITS = Integer.parseInt(args[2]); // Remove old target directory first FileUtils.deleteQuietly(new File(targetDir)); File[] dataFiles = filesDir.listFiles(); int total = dataFiles.length; int range = (int) Math.round(total / NUM_SPLITS + 0.5); System.out.printf("[INFO] The number of total files is %d \n.", total); for (int i = 1; i <= NUM_SPLITS; i++) { int start = (i - 1) * range; int end = Math.min(start + range, total); File[] subFiles = Arrays.copyOfRange(dataFiles, start, end); createSeqFile(subFiles, FilenameUtils.normalize(targetDir + "/" + i + ".seq")); } System.out.println("[INFO] All files have been successfully processed!"); }
From source file:com.owly.clnt.OwlyClnt.java
/** * @param args//from w w w .j a v a 2 s .c o m * First argument in the port where webserver is going to start */ public static void main(String[] args) { Logger log = Logger.getLogger(OwlyClnt.class); log.debug("Executing OwlyClnt"); if (args.length == 1) { String clientport = args[0]; setPort(Integer.parseInt(clientport)); log.debug("Port to run :" + clientport); // URL used for generating the VMstat of the server get(new Route("/OwlyClnt/Stats_Vmstat") { @Override public Object handle(Request request, Response response) { Logger log = Logger.getLogger(OwlyClnt.class); log.debug("Calling Stats_Vmstat"); OSValidator osValidator = new OSValidator(); log.debug("operating System " + osValidator.getOS()); JSONObject json = new JSONObject(); if (osValidator.isWindows()) { StatsWinTypeperf testStats = new StatsWinTypeperf(); try { json = testStats.getWinTypeperf(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { if (OSValidator.isUnix()) { StatsVmstat testStats = new StatsVmstat(); try { json = testStats.getJSONVmStat(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { json.put("StatType", "NOK"); } } return json.toString(); } }); // URL used for generating the TopCPU of the server get(new Route("/OwlyClnt/Stats_TopCPU") { @Override public Object handle(Request request, Response response) { Logger log = Logger.getLogger(OwlyClnt.class); log.debug("Calling Stats_Vmstat"); OSValidator osValidator = new OSValidator(); log.debug("operating System " + osValidator.getOS()); JSONObject topCpuStatJson = new JSONObject(); if (OSValidator.isUnix()) { StatsTopCpu testStats = new StatsTopCpu(); try { topCpuStatJson = testStats.getJSONTopCpu(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { topCpuStatJson.put("StatType", "NOK"); } return topCpuStatJson.toString(); } }); // Url used for executing a healthcheck and see if the server is // available get(new Route("/healthCheck") { @Override public Object handle(Request request, Response response) { JSONObject objJSON = new JSONObject(); objJSON.put("StatusServer", "OK"); return objJSON.toString(); } }); } else { System.out.println("ERROR : you need to specify port number -> ./OwlyClnt port "); } }