Print out all vowels contained in the string.

Question:
How to read string and print out all vowels contained in the string.

Code:
import java.util.Scanner;
 
public class GetVowels {
  public static void main(String[] args) {
 
    String vowels = "AEIOUaeiou";
    System.out.print("Enter a string: ");
    Scanner in = new Scanner(System.in);
    String str = in.nextLine();
    for(int i=0;i<str.length();i++){
      String onechar = str.substring(i,i+1);
      if( vowels.indexOf(onechar) != -1){
        System.out.print(onechar);
      }
    }
    System.out.println();
  }
}

Output:
$ java GetVowels
Enter a string: abcDEFghi         
aEi

How to validate an input is a positive number?

Question:
How to validate an input is a positive number?

Code:
import java.util.*;
 
public class ReadInt {
 
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
 
      while(true) {
         try {
 
            System.out.print("Enter Positive Number: ");
            int i = sc.nextInt();
            if(i > 0){
               System.out.println("You entered: " + i);
               System.out.println("Thank you");
               break;
            } else {
               System.out.println("Negative Number");
            }
 
         } catch (InputMismatchException e) {
            System.out.println("You did not enter a Number.");
            sc.nextLine(); 
         }
      }
   }
}

Output:
$ java ReadInt 
Enter Positive Number: hello
You did not enter a Number.
Enter Positive Number: -222
Negative Number
Enter Positive Number: 100
You entered: 100
Thank you

Validating that a users input is a number and within a range.

Question:
How do I validate an input ensuring a user enters a number in the range 1-10?

Answer:
See example:

Code:
import java.util.*;
 
public class ReadInt {
 
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
 
      int number = 0;
      while (true) {
         try {
            System.out.print("Enter number betwen 1 and 10: ");
            number = sc.nextInt();
            if( number >= 1 && number <= 10){
              break;
            }
            System.out.println("Out of range.");
 
         } catch (InputMismatchException e) {
            System.out.println("You did not enter a Integer.");
            sc.nextLine(); // needed to clear buffer
         }
      }
      System.out.println("You entered: " + number);
   }
}

Output:
$ java ReadInt
Enter number betwen 1 and 10: 11
Out of range.
Enter number betwen 1 and 10: a
You did not enter a Integer.
Enter number betwen 1 and 10: 12
Out of range.
Enter number betwen 1 and 10: 10
You entered: 10

Finding the lowest and highest numbers in an array of ints?

Question:
How to find the lowest and highest numbers in an array of ints?

Answer:
Use a for loop.

Code:
import java.util.*;
 
public class LowestNumber {
   public static void main(String[] args) {
 
      int[] array = new int[15];
 
      // populate array
      Random r = new Random();
      for(int i=0;i<array.length;i++){
         array[i]= r.nextInt(1000);
      }
      System.out.println("Contents: " + Arrays.toString(array));
 
      // find smallest and largest numbers
      int small = array[0];
      int large = array[0];
      for(int i=0;i<array.length;i++){
         if(array[i] <= small){
            small = array[i];
         }
         if(array[i] >= large){
            large = array[i];
         }
      }
      System.out.println("Smallest number: " + small);
      System.out.println("Largest number: " + large);
   }
}

Output:
$ java LowestNumber
Contents: [489, 283, 334, 331, 665, 643, 280, 100, 184, 642, 730, 560, 930, 517, 24]
Smallest number: 24
Largest number: 930

Validate a SSN without using loops

Question:
Looking for a program to validate a SSN without using loops.

A valid input would be: 123-45-6789

Answer:
See example.

Code:
import java.util.*;
 
public class SSN {
   public static void main(String args[]){
 
      boolean valid = false;
 
      System.out.print("Enter SSN: ");
      Scanner sc = new Scanner(System.in);
      String ssn = sc.next();
      System.out.println("Input: "+ssn);
 
      if(ssn.length()==11) {
         if( (ssn.charAt(3)=='-') & (ssn.charAt(6)=='-') ) {
            String str = ssn.replaceAll("-", "");
            if (str.matches("[0-9]+") & str.length()==9) {
               valid = true;
            }
         }
      }
 
      System.out.println("valid: " + valid);
   }
}

Output:
$ java SSN 
Enter SSN: 123-12-1234
Input: 123-12-1234
valid: true

$ java SSN 
Enter SSN: 123-123-123
Input: 123-123-123
valid: false

$ java SSN 
Enter SSN: 123-12-123a
Input: 123-12-123a
valid: false

Program that provides the minimum amount of change for a given amount in US currency.

Question:
I'm looking for a java program that can give the minimum change for a given amount in US currency.

Answer:
See example

Code:
import java.util.*;
import java.math.*;
 
public class MakeChange {
 
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
 
      // example: 39.99
      System.out.print("Enter total amount: ");
      double amount =  sc.nextDouble();
 
      // Multiple by 100 so all the math can handle ints
      int remainder = (int)(amount * 100);
 
      int twentys =  remainder / 2000 ;
      remainder = remainder - (twentys * 2000);
 
      int tens =  remainder / 1000 ;
      remainder = remainder - (tens * 1000);
 
      int fives =  remainder / 500 ;
      remainder = remainder - (fives * 500);
 
      int dollars =  remainder / 100 ;
      remainder = remainder - (dollars * 100);
 
      int quarters =  remainder / 25 ;
      remainder = remainder - (quarters * 25);
 
      int dimes =  remainder / 10 ;
      remainder = remainder - (dimes * 10);
 
      int nickels =  remainder / 05 ;
      remainder = remainder - (nickels * 05);
 
      int pennies =  remainder / 01 ;
 
      System.out.println("Twentys: " + twentys); 
      System.out.println("Tens: " + tens); 
      System.out.println("Fives: " + fives); 
      System.out.println("Dollars: " + dollars); 
      System.out.println("Quarters: " + quarters); 
      System.out.println("Dimes   : " + dimes); 
      System.out.println("Nickels : " + nickels); 
      System.out.println("Pennies : " + pennies); 
  }
}

Output:
$ java MakeChange 
Enter total amount: 39.99
Twentys: 1
Tens: 1
Fives: 1
Dollars: 4
Quarters: 3
Dimes   : 2
Nickels : 0
Pennies : 4

Comparing the contents of two different multi dimensional arrays

Question:
How can you compare the contents of two different multi dimensional arrays?

Answer:
Use Arrays.deepEquals(array1, array2)

Code:
import java.util.Arrays;
 
class CompareArrays {
   public static void main (String[] args) {
 
      int[][] array1 = { {1,2}, {1,2}, {1,2} ,{1,2}, {1,2} };
      int[][] array2 = { {1,2}, {1,2}, {1,2} ,{1,2}, {1,2} };
      int[][] array3 = { {1,2}, {1,2}, {1,2} ,{1,2}, {1,3} };
 
      if (Arrays.deepEquals(array1, array2)){
         System.out.println("array1 and array2: same content");
      } else {
         System.out.println("array1 and array2: different content");
      }
 
      if (Arrays.deepEquals(array1, array3)){
         System.out.println("array1 and array3: same content");
      } else {
         System.out.println("array1 and array3: different content");
      }
 
   }
}

Output:
$ java CompareArrays
array1 and array2: same content
array1 and array3: different content

Comparing the contents of two different arrays

Question:
How to compare the contents of two different arrays?

Answer:
Use Arrays.equals(array1, array2)

Code:
import java.util.Arrays;
 
class CompareArrays {
   public static void main (String[] args) {
 
      int arr1[] = {1, 2, 3};
      int arr2[] = {1, 2, 3};
 
      if (Arrays.equals(arr1, arr2)){
         System.out.println("Array contents are the same");
      } else {
         System.out.println("Array contents are different");
      }
   }
}

Output:
$ java CompareArrays
Array contents are the same

Convert a string of number with commas to a long

Question:
How can I convert String of numbers with commas to Long?

Answer:
Remove commas from the string with str.replaceAll(",", "").

or

Use the NumberFormat class.

Code:
import java.text.NumberFormat;
import java.util.Locale;
import java.text.ParseException;
 
public class NumbersWithCommas {
   public static void main(String[] args) {
 
      String str = "1,234,567,890";
 
      // remove all commas in the string
      long l1 = Long.valueOf(str.replaceAll(",", "").toString());
      System.out.println("l1: " + l1);
 
      NumberFormat format = NumberFormat.getInstance(Locale.US);
      Number number = 0;
      try {
         number = format.parse(str);
      } catch (ParseException e) {
         e.printStackTrace();
      }
      long l2 = number.longValue();
      System.out.println("l1: " + l1);
   }
}

Output:
$ java NumbersWithCommas
l1: 1234567890
l1: 1234567890

Convert a char array to String

Question:
How do you convert char array to String in Java?

Answer:
Use String(array) or String.valueOf(array)

Code:
public class CharArrayToString {
   public static void main(String[] args) {
 
      char[] array = new char[] {'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3'};
 
      String str1 = new String(array);
      System.out.println("str1 : " + str1);
 
      String str2;
      str2 = String.valueOf(array);
      System.out.println("str2 : " + str2);
   }
}

Output:
$ java CharArrayToString 
str1 : abcABC123
str2 : abcABC123

Self destroying java program.

Code:
import java.io.File;
 
public class SelfDestruct {
    public static void main(String argz[]) {
        File file=new File("SelfDestruct.class");
        file.delete();
        return;
    }
}

Output:
$ ls -l SelfDestruct.class 
-rw-rw-r-- 1 tom tom 393 Mar  7 16:25 SelfDestruct.class

$ java SelfDestruct

$ ls -l SelfDestruct.class 
ls: cannot access SelfDestruct.class: No such file or directory

First 50 factorials using BigIntegers.

Code:
import java.math.*;
public class Factorial {
   public static void main(String args[]) {
      for(int n=1;n<=50;n++){
         BigInteger result = new BigInteger("1");
         int x;
         for (x=1; x<=n; x++) {
            result = result.multiply(new BigInteger(""+x));
         }
         System.out.println(n + ": " +  result);
      }
   }
}

Output:
1: 1
2: 2
3: 6
4: 24
5: 120
6: 720
7: 5040
8: 40320
9: 362880
10: 3628800
11: 39916800
12: 479001600
13: 6227020800
14: 87178291200
15: 1307674368000
16: 20922789888000
17: 355687428096000
18: 6402373705728000
19: 121645100408832000
20: 2432902008176640000
21: 51090942171709440000
22: 1124000727777607680000
23: 25852016738884976640000
24: 620448401733239439360000
25: 15511210043330985984000000
26: 403291461126605635584000000
27: 10888869450418352160768000000
28: 304888344611713860501504000000
29: 8841761993739701954543616000000
30: 265252859812191058636308480000000
31: 8222838654177922817725562880000000
32: 263130836933693530167218012160000000
33: 8683317618811886495518194401280000000
34: 295232799039604140847618609643520000000
35: 10333147966386144929666651337523200000000
36: 371993326789901217467999448150835200000000
37: 13763753091226345046315979581580902400000000
38: 523022617466601111760007224100074291200000000
39: 20397882081197443358640281739902897356800000000
40: 815915283247897734345611269596115894272000000000
41: 33452526613163807108170062053440751665152000000000
42: 1405006117752879898543142606244511569936384000000000
43: 60415263063373835637355132068513997507264512000000000
44: 2658271574788448768043625811014615890319638528000000000
45: 119622220865480194561963161495657715064383733760000000000
46: 5502622159812088949850305428800254892961651752960000000000
47: 258623241511168180642964355153611979969197632389120000000000
48: 12413915592536072670862289047373375038521486354677760000000000
49: 608281864034267560872252163321295376887552831379210240000000000
50: 30414093201713378043612608166064768844377641568960512000000000000

Showing a letter for a grade average

Code:
import java.util.Scanner;
 
public class Grades {
   public static void main(String[] args) {
 
      char grades[] = {'F','D','C','B','A'};
 
      System.out.print("Enter final class average: ");
 
      // Read in final class average
      Scanner in = new Scanner(System.in);
      double average = in.nextDouble();
 
      char grade = grades[(int)Math.min(4,Math.max(0,((average-1)/10)-5))];
      System.out.println("Grade: " + grade);
   }
}

Output:
$ java Grades
Enter final class average: 98
Grade: A

$ java Grades
Enter final class average: 71
Grade: C

$ java Grades
Enter final class average: 82
Grade: B

Finding the smallest of 3 integers

Question:
How to find the smallest of three ints?

Answer:
Use the method Math.min()

Code:
import java.util.Scanner;
 
public class SmallestInt {
 
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
 
      System.out.print("Enter 1st int: ");
      int i1 = sc.nextInt();
      System.out.print("Enter 2nd int: ");
      int i2 = sc.nextInt();
      System.out.print("Enter 3rd int: ");
      int i3 = sc.nextInt();
 
      int small = Math.min(i1,Math.min(i2,i3));  
      System.out.println("Smallest: " + small);
   }
}

Output:
$ java SmallestInt
Enter 1st int: 100
Enter 2nd int: 55
Enter 3rd int: 300
Smallest: 55

Reading in a date from a scanner.

Question:
How to read in a date from a Scanner?

Answer:
You can read in a String and then convert it to a Date.

Code:
import java.util.*;
import java.text.*;
 
public class ScanDate {
 
   public static void main(String[] args) {
 
      SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
      Scanner sc = new Scanner(System.in);
 
      System.out.println("Eample: 12-25-2103");
      System.out.print("Enter date: ");
      String str = sc.nextLine();
 
      try {
         Date date = sdf.parse(str); 
 
         sdf = new SimpleDateFormat("EEE, d MMM yyyy");
         System.out.println("Date: " + sdf.format(date));
      } catch (ParseException e) { 
         System.out.println("Parse Exception");
      }
   }
}

Output:
$ java ScanDate
Eample: 12-25-2103
Enter date: 02-12-2014
Date: Wed, 12 Feb 2014

Populating three different arrays from the contents of a file that has three columns of integers.

Question:
I am looking for a way to populate three different arrays from the contents of a file that has three columns of integers.

Answer:
Scanner(), StringTokenizer() and Integer.parseInt()

Code:
import java.io.*;
import java.util.*;  
 
public class ScanFileContents {
 
   public static void main(String[] args)throws IOException {
 
      String[] columns = new String[3];
 
      Scanner input;
      String str;
      StringTokenizer tokens;
 
      // need to know ho big of an array to create 
      int lines = 0;
      input = new Scanner(new File("data.txt"));
      while(input.hasNext()){
         str = input.nextLine();
         lines = lines+1;
      }
      input.close();
 
      int[] row1 = new int[lines-1];
      int[] row2 = new int[lines-1];
      int[] row3 = new int[lines-1];
 
      input = new Scanner(new File("data.txt"));
      str = input.nextLine();
      tokens = new StringTokenizer(str);
      columns[0]=tokens.nextToken();
      columns[1]=tokens.nextToken();
      columns[2]=tokens.nextToken();
 
      int count = 0;
      while(input.hasNext()){
         str = input.nextLine();
         tokens = new StringTokenizer(str);
         row1[count] = Integer.parseInt(tokens.nextToken());
         row2[count] = Integer.parseInt(tokens.nextToken());
         row3[count] = Integer.parseInt(tokens.nextToken());
         count = count + 1;
      }
      System.out.println(columns[0] + ":" + Arrays.toString(row1));
      System.out.println(columns[1] + ":" + Arrays.toString(row2));
      System.out.println(columns[2] + ":" + Arrays.toString(row3));
   }
}

Output:
$ java ScanFileContents
TOM:[100, 77, 100, 89, 91, 95, 84, 92]
BOB:[65, 78, 89, 66, 75, 78, 82, 93]
JOHN:[33, 98, 44, 86, 85, 68, 44, 100]

$ cat data.txt
TOM BOB JOHN
100 65 33
77 78 98
100 89 44
89 66 86
91 75 85
95 78 68
84 82 44
92 93 100

Calculating compound interest.

Question:
How can you calculate compound interest in java?

Answer:
Formula: amount = principal (1+rate)^years

Java: amount = principal * Math.pow(1+rate, years)

Code:
import java.util.Scanner; 
 
public class Interest {
 
   public static void main(String[] args) {
 
      Scanner in = new Scanner( System.in );  
 
      double principal; 
      double rate; 
      double interest;
 
      System.out.print("Enter the initial investment: ");
      principal = in.nextDouble();
 
      System.out.print("Enter the annual interest rate: ");
      rate = in.nextDouble();
 
      System.out.print("Please enter the number of years: "); 
      int years = in.nextInt(); 
 
      principal = principal * Math.pow(1+rate, years);
 
      System.out.print("The future value: ");
      System.out.printf("%.2f\n", principal); 
   } 
}

Output:
$ java Interest 
Enter the initial investment: 100.00
Enter the annual interest rate: .05
Please enter the number of years: 10
The future value: 162.89

Converting decimal to binary in java.

Question:
How to convert a decimal to binary in java?

Answer:
This java code is based on the tutorial from:
http://www.wikihow.com/Convert-from-Decimal-to-Binary

Code:
public class DecimalToBinary {
 
   public static void main(String[] args) {
 
      int decimal = Integer.parseInt(args[0]);
      int results = decimal;
      int remainder = decimal;
      String binary = "";
 
      while (results >= 2) {
         remainder = results % 2;
         results = results/2;
         binary = binary + remainder;
      }
      binary = binary + results;
      binary = new StringBuilder(binary).reverse().toString();
 
      System.out.println ("Decimal : " + decimal); 
      System.out.println ("Binary : " + binary); 
   }
}

Output:
$ java DecimalToBinary 156
Decimal : 156
Binary : 10011100

$ java DecimalToBinary 255
Decimal : 255
Binary : 11111111

$ java DecimalToBinary 32
Decimal : 32
Binary : 100000