Posted By

bcmoney on 08/17/12


Tagged

Shell java output batch system standalone


Versions (?)

Learning JAVA (with basic standalone code snippets)


 / Published in: Java
 

URL: http://bcmoney-mobiletv.com/blog/2012/09/24/the-getting-started-in-java-guide-that-i-wish-i-had-in-university/

Just some random stuff I worked through myself and used a long time ago to get up to speed with Java in University.

If you can understand these basic samples by actually running them and experimenting, then you'll be set to do more in-depth programming.

Includes an updated version of this File Reader, which was deprecated in JAVA v1.4: http://www.java-tips.org/java-se-tips/java.io/how-to-read-file-in-java.html

  1. //////////////////////////////////////////////////////////
  2. /**
  3.  * HelloWorld.java
  4.  * The first program anyone should write in any language.
  5.  */
  6. public class HelloWorld {
  7.  
  8. public static void main(String[] args) {
  9. System.out.println("Hello World");
  10. }
  11. }
  12.  
  13.  
  14. //////////////////////////////////////////////////////////
  15. /**
  16.  * HelloFromCommandLine.java
  17.  * The second program anyone should write in any language.
  18.  * This teaches you to accept input to your program as parameters
  19.  * at run-time. The Program will say your name when you provide
  20.  * an input.
  21.  * args[0] is the program name
  22.  * args[1] is the first parameter
  23.  * args[n] is the Nth parameter
  24.  * EXAMPLE
  25.  * Call the program as follows (from the command-line):
  26.  * java HelloFromCommandLine Michael
  27.  * For special characters and spaces, enclose the parameter "in quotes":
  28.  * java HelloFromCommandLine "Michael Jackson"
  29.  */
  30. public class HelloFromCommandLine {
  31. public static void main(String[] args) {
  32. String name = "";
  33. //check that the input is valid (i.e. not missing or empty space)
  34. if (args[1] == null || args[1].equals("")) {
  35. System.exit(1);
  36. }
  37. else {
  38. name = args[1];
  39. }
  40. System.out.println("Hello " + name);
  41. }
  42. }
  43.  
  44.  
  45.  
  46. //////////////////////////////////////////////////////////
  47. /**
  48.  * HelloFromConsole.java
  49.  * The first program anyone writes in any language.
  50.  */
  51. public class HelloFromConsole {
  52.  
  53. public static void main(String[] args) {
  54. System.out.print("Please enter username: ");
  55. System.out.println(" ");
  56. ConsoleReader console = new ConsoleReader(System.in);
  57. String username = console.readLine();
  58. System.out.println("Hello: " + username);
  59. }
  60. }
  61.  
  62. //////////////////////////////////////////////////////////
  63. /**
  64.  * Multiples.java
  65.  * Used to calculate N multiples of 2.
  66.  */
  67. public class Multiples() {
  68.  
  69. public static void printMultsOf2(int multiples) {
  70. int runningTotal = 2;
  71. for (int i = 0; i < multiples; i++) {
  72. System.out.print(runningTotal + " ");
  73. runningTotal += 2;
  74. }
  75. }
  76.  
  77. public static void main(String[] args) {
  78. printMultsOf2(10);
  79. }
  80. }
  81.  
  82.  
  83. //////////////////////////////////////////////////////////
  84. /**
  85.  * NumberToBinary.java
  86.  * Convert a Decimal Number to a Binary Number (i.e. "2" becomes "10").
  87.  * Serves as a very easy first example on how to "import" internal Java
  88.  * API libraries, to enhance the basic capabilities of the Java core language.
  89.  */
  90. import java.io.*;
  91. import java.lang.*;
  92.  
  93. public class NumberToBinary {
  94. public static void main(String[] args) throws IOException {
  95. System.out.println("Enter any number:");
  96. String sn = bf.readLine();
  97. int i = Integer.parseInt(sn);
  98. String s = Integer.toBinaryString(i);
  99. System.out.println("Binary number is:" + s);
  100. }
  101. }
  102.  
  103.  
  104. //////////////////////////////////////////////////////////
  105. /**
  106.  * OutputPDF.java
  107.  * Write a String as a new PDF document (overwriting existing files).
  108.  *
  109.  * Serves as a very easy first example on how to "import" external and 3rd-party Java
  110.  * API libraries, to enhance the capabilities of the complete Java platform. In this
  111.  * case, we're importing iText, the leading PDF library for Java. In order to compile
  112.  * it properly, you need to link the 3rd-party library at runtime using the following
  113.  * commands to the Java compiler (use full path to the iText JAR or run in same dir):
  114.  *
  115.  * javac -cp itextpdf-5.4.3.jar OutputPDF.java
  116.  *
  117.  * RUN as:
  118.  * java -classpath .;itextpdf-5.4.3.jar OutputPDF
  119.  *
  120.  */
  121.  
  122. import java.io.File;
  123. import java.io.FileOutputStream;
  124. import java.io.OutputStream;
  125. import java.io.IOException;
  126. import java.util.Date;
  127.  
  128. /* import external iText PDF libraries */
  129. import com.itextpdf.text.Document;
  130. import com.itextpdf.text.DocumentException;
  131. import com.itextpdf.text.Paragraph;
  132. import com.itextpdf.text.pdf.PdfWriter;
  133.  
  134.  
  135. public class OutputPDF {
  136. public static void main(String[] args) {
  137. try {
  138. //create blank PDF file called "Test.pdf" using iText lib
  139. OutputStream file = new FileOutputStream(new File("Test.pdf"));
  140. Document document = new Document();
  141. PdfWriter.getInstance(document, file);
  142.  
  143. //open "Test.pdf" generated file and write to it
  144. document.open();
  145. document.add(new Paragraph("Hello World!"));
  146. document.add(new Paragraph(new Date().toString()));
  147. document.add(new Paragraph("This PDF document created with iText"));
  148.  
  149. //close the PDF document and File handle
  150. document.close();
  151. file.close();
  152. } catch (IOException ioEx) {
  153. ioEx.printStackTrace();
  154. } catch (DocumentException dEx) {
  155. dEx.printStackTrace();
  156. }
  157.  
  158. }
  159. }
  160.  
  161.  
  162. //////////////////////////////////////////////////////////
  163. import java.io.BufferedReader;
  164. import java.io.File;
  165. import java.io.FileNotFoundException;
  166. import java.io.FileReader;
  167. import java.io.IOException;
  168.  
  169. /**
  170.  *
  171.  * @author bcbcope
  172.  */
  173. public class DisplayFileContents {
  174.  
  175. /**
  176.   * fileToString
  177.   * Takes a java.io.File handle and converts it to a String for output
  178.   *
  179.   * @param file
  180.   * @return
  181.   */
  182. public String fileToString(File file) {
  183. StringBuilder fileContent = new StringBuilder();
  184. try {
  185. while (in.ready()) {
  186. //reads from the file contents and appends to string
  187. fileContent.append(in.readLine());
  188. fileContent.append("\n");
  189. }
  190. // dispose all the resources after using them.
  191. in.close();
  192. } catch (FileNotFoundException ex) {
  193. ex.printStackTrace();
  194. } catch (IOException ioEx) {
  195. ioEx.printStackTrace();
  196. } catch (NullPointerException nEx) {
  197. nEx.printStackTrace();
  198. }
  199. return (String)fileContent.toString();
  200. }
  201.  
  202. public static void main(String[] args) {
  203. DisplayFileContents output = new DisplayFileContents();
  204. System.out.println("-----OUTPUTTING FILE CONTENTS-----");
  205. //output raw file contenst as read in (i.e. TXT, XML, JSON, props, etc)
  206. File file = new File("C://APPS/tmp.txt");
  207. System.out.println(output.fileToString(file));
  208. }
  209. }
  210.  
  211.  
  212. //////////////////////////////////////////////////////////
  213. /**
  214.  * Grade.java
  215.  * Given a student score, calculate their Letter Grade.
  216.  */
  217.  
  218.  
  219.  
  220. //////////////////////////////////////////////////////////
  221. /**
  222.  * GPA.java
  223.  * Given a set of student scores, calculate their GPA.
  224.  */
  225.  
  226.  
  227.  
  228. //////////////////////////////////////////////////////////
  229. import java.util.*;
  230.  
  231. /**
  232.  * Lottery
  233.  * Plays a lottery game with the user, reading the user's lottery numbers and
  234.  * printing how many matched a winning lottery ticket.
  235.  * @author BCBCOPE
  236.  * @since 15-Aug-2012
  237.  */
  238. public class Lottery {
  239. public static final int NUMBERS = 6;
  240. public static final int MAX_NUMBER = 40;
  241. public static boolean instapick = false;
  242.  
  243. /* contrsuctor */
  244. public Lottery() {
  245. instapick = true;
  246. }
  247.  
  248. /* contrsuctor
  249.   public Lottery(int[] numbers) {
  250.   setTicket();
  251.   }
  252.   */
  253.  
  254. // generates a set of the winning lotto numbers
  255. public static Set<Integer> generateWinningNumbers() {
  256. Set<Integer> winningNumbers = new TreeSet<Integer>();
  257. Random r = new Random();
  258. while (winningNumbers.size() < NUMBERS) {
  259. int number = r.nextInt(MAX_NUMBER) + 1;
  260. winningNumbers.add(number);
  261. }
  262. return winningNumbers;
  263. }
  264.  
  265. // Allows a player to input their lottery ticket from console
  266. public static Set<Integer> getTicket() {
  267. Set<Integer> ticket = new TreeSet<Integer>();
  268. Scanner console = new Scanner(System.in);
  269. System.out.print("Type your " + NUMBERS + " unique lotto numbers: ");
  270. //collect N lotto numbers as input from Player
  271. while (ticket.size() < NUMBERS) {
  272. int number = console.nextInt();
  273. ticket.add(number);
  274. }
  275. return ticket;
  276. }
  277.  
  278. /* Sets a player's lottery ticket programmatically
  279.   public static Set<Integer> setTicket() {
  280.  
  281.   }
  282.   */
  283.  
  284. public static void main(String[] args) {
  285. // get winning number and ticket sets
  286. Set<Integer> winningNumbers = generateWinningNumbers();
  287. Set<Integer> ticket = getTicket();
  288. System.out.println();
  289.  
  290. // keep only the winning numbers from the user's ticket
  291. Set<Integer> intersection = new TreeSet<Integer>(ticket);
  292. intersection.retainAll(winningNumbers);
  293.  
  294. // print results
  295. System.out.println("Your ticket: " + ticket);
  296. System.out.println("Winning numbers: " + winningNumbers);
  297. System.out.println();
  298. System.out.println("You had " + intersection.size() + " matching numbers.");
  299. if (intersection.size() > 0) {
  300. double prize = 100 * Math.pow(2, intersection.size());
  301. System.out.println("The matched numbers are " + intersection);
  302. System.out.println("Winnings: $" + prize);
  303. }
  304. }
  305.  
  306. }
  307.  
  308.  
  309.  
  310.  
  311. //////////////////////////////////////////////////////////
  312. /**
  313.  * ConnectToURL.java
  314.  * Connect to & display data from the web at a specific site's URL.
  315.  */
  316. import java.net.*;
  317. import java.io.*;
  318.  
  319. public class ConnectToURL {
  320. public ConnectToURL() { }
  321.  
  322. public static void main (String[] args) throws IOException {
  323. try {
  324. URL url = new URL("http://www.bryancopeland.com");
  325. BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
  326. String str;
  327.  
  328. while ((str = in.readLine()) != null) {
  329. System.out.println(str);
  330. }
  331.  
  332. in.close();
  333. }
  334. catch (MalformedURLException e) {}
  335. catch (IOException e) {}
  336. }
  337. }
  338.  
  339. //////////////////////////////////////////////////////////
  340. // THE END //
  341. //////////////////////////////////////////////////////////

Report this snippet  

You need to login to post a comment.