Converting decimal to octal in java.

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

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

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

Output:
$ java DecimalToOctal 9
Decimal : 9
Octal : 11

$ java DecimalToOctal 891
Decimal : 891
Octal : 1573

$ java DecimalToOctal 12345
Decimal : 12345
Octal : 30071

How to enter a double from a scanner.

Question:
How do you read a double from a scanner?

Answer:
Use the methed Scanner.nextDouble().

Code:
import java.util.Scanner;
 
public class ScanDouble {
  public static void main(String[] args) {
 
    System.out.print("Enter double: " ); 
    Scanner in=new Scanner(System.in);
    double d=in.nextDouble();
 
    System.out.println("You entered: " + d); 
 
  }
} 

Output:
$ java ScanDouble
Enter double: 12.2
You entered: 12.2

How to tell when a file was last modified?

Question:
How can you tell when a file was last updated in java?

Answer:
Use the File.lastModified() method.

Code:
import java.io.*;
import java.util.*;
 
public class FileModified {
   public static void main(String[] args) {
      File file = new File("FileModified.java");
      Date d = new Date(file.lastModified());
      System.out.println(d);
   }
}

Output:
$ java FileModified 
Fri Feb 28 06:59:28 EST 2014

$ ls -l FileModified.java 
-rw-r--r-- 1 dennis dennis 242 Feb 28 06:59 FileModified.java

How to get the size of a file?

Question:
How can you get the size of a given file in java?

Answer:
Use the method File.length().

Code:
import java.io.*;
 
public class FileSize {
   public static void main(String[] args) {
      File file = new File("FileSize.java");
      System.out.println("FileSize.java: "  + file.length());
   }
}

Output:
$ java FileSize 
FileSize.java: 201

$ ls -l FileSize.java
-rw-r--r-- 1 dennis dennis 201 Feb 28 06:51 FileSize.java

Round doubles to the nth decimal

Question:
How can you round doubles to the nth decimal?

Answer:
For 5 digits precision:
   (double)Math.round(value * 100000) / 100000
The number of zeros indicate the number of decimals.

Code:
public class Rounding {
   public static void main(String[] args) {
 
      double pi = 3.14159265359;
      System.out.println(pi);
 
      System.out.println( Math.round(pi) );
      System.out.println( (double)Math.round(pi*10)/10 );
      System.out.println( (double)Math.round(pi*100)/100 );
      System.out.println( (double)Math.round(pi*1000)/1000 );
      System.out.println( (double)Math.round(pi*10000)/10000 );
      System.out.println( (double)Math.round(pi*100000)/100000 );
      System.out.println( (double)Math.round(pi*1000000)/1000000 );
      System.out.println( (double)Math.round(pi*10000000)/10000000 );
 
   }
}

Output:
$ java Rounding 
3.14159265359
3
3.1
3.14
3.142
3.1416
3.14159
3.141593
3.1415927

Drawing a triangle in java.

Question:
A user provides a number and I need to draw a triangle using loops based on the users input:

This is what the output should look like:
Enter number: 5
x
xx
xxx
xxxx
xxxxx

Answer:
Use a nested for loop.

Code:
import java.util.Scanner;
 
public class Triangle {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter number: ");
      int number = sc.nextInt();
      for (int i=1;i<=number;i++) { 
         for(int j=1; j<=i; ++j) {
            System.out.print("x");
         } 
         System.out.println();
      }
   }
}

Output:
$ java Triangle
Enter number: 10
x
xx
xxx
xxxx
xxxxx
xxxxxx
xxxxxxx
xxxxxxxx
xxxxxxxxx
xxxxxxxxxx

How to remove all occurrences of a letter from a string?

Question:
How to remove all occurrences of a letter from a string?

Answer:
Use a for loop and compare each character of the string to see if it matches the letter that needs to be removed. Build a new string based on the results.

Use the String.replace() method.

Code:
public class RemoveChars {
   public static void main(String[] args) {
 
      String str1 = "axbxcxdxex";
      String str2 = "";
      String str3 = "";
 
      // using a for loop 
      for (int i = 0; i < str1.length(); i++) {
         if (str1.charAt(i) != 'x') {
            str2 = str2 + str1.charAt(i);
         }
      }
 
      // using a for String.replace()
      str3 = str1.replace( "x", "");
 
      System.out.println(str1);
      System.out.println(str2);
      System.out.println(str3);
  }
}

Output:
$ java RemoveChars 
axbxcxdxex
abcde
abcde

Counting words in a file.

Question:
How to count the number times a certain word appears in a file?

Answer:
Use the method Scanner.next() to read in each word of the file and then compare it with the desired word.

Code:
import java.io.*;
import java.util.*;
 
public class CountWords {
   public static void main(String[] args) {
 
      int count=0;
      String word = "cat";
 
      try {
         File file = new File("file.txt");
         Scanner sc = new Scanner(new FileInputStream(file));
 
         while(sc.hasNext()){
            if(word.equalsIgnoreCase(sc.next())){
               count = count + 1;
            }
         }
      } catch (Exception e) {
      }
      System.out.println("Number of " + word  + " words: " + count);
   }
}

Output:
$ cat file.txt 
Dog cat dog cat
Cat dog cat dog

$ java CountWords
Number of cat words: 4

Getting the first char of each line in a file.

Question:
How can I get the first character of each line in a file?

Answer:
See code.

Code:
import java.io.*;
 
public class ReadFile {
   public static void main(String[] args) {
      try {
         FileInputStream is = new FileInputStream("file.txt");
         BufferedReader br = new BufferedReader(new InputStreamReader(is));
         String str;
         while ((str = br.readLine()) != null)   {
 
            char first = str.charAt(0);
            System.out.println(first);
 
         }
      } catch (Exception e) {
      }
   }
}

Output:
$ java ReadFile 
a
b
c
d

$ cat file.txt 
a bbb ccc ddd
bb ccc dddd eeee
cccc dd ee f
dd eeeeee fff ggg

How can you round doubles to the nth decimal?

Question:
How can you round doubles to the nth decimal?

Answer:
Using the Math.round method and formating with the DecimalFormat class.

Code:
import java.text.DecimalFormat;
 
public class RoundDoubles {
   public static void main(String[] args) {
 
      double d1 = 0;
      double d2 = 1.49999;
      double d3 = 3.14159265359;
      double d4 = 98.5555555;
 
      //the number of zeros indicate the number of decimals.
      d1 = (double)Math.round(d1 * 100) / 100;
      d2 = (double)Math.round(d2 * 100) / 100;
      d3 = (double)Math.round(d3 * 100) / 100;
      d4 = (double)Math.round(d4 * 100) / 100;
 
      //the number of .0's indicate right padding.
      DecimalFormat df = new DecimalFormat("0.00"); 
      System.out.println(df.format(d1));
      System.out.println(df.format(d2));
      System.out.println(df.format(d3));
      System.out.println(df.format(d4));
   }
}

Output:
$ java RoundDoubles
0.00
1.50
3.14
98.56

How can you enter multiple doubles from a scanner?

Question:
Looking for a example on how to enter multiple doubles using the Scanner class.

Code:
import java.util.Scanner;
 
public class ScanMultipleDoubles {
 
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
 
      // change the value of 5 to the number required
      double[] values = new double[5];
 
      for(int i=0;i<values.length;i++){
         System.out.print("Enter double: ");
         values[i] = sc.nextDouble();
      }
 
      double total=0;
      for(int i=0;i<values.length;i++){
         total = total + values[i];
      }
 
      System.out.println("Total: " + total);
 
      double average = total / values.length;
      System.out.println("Average: " + average);
   }
}

Output:
$ java ScanMultipleDoubles
Enter double: 1.1
Enter double: 2.2
Enter double: 3.3
Enter double: 4.4
Enter double: 5.5
Total: 16.5
Average: 3.3

Remove a value from an array element and fill the last element by 0

Question:
I need to search for a number in an array. If the number is found in the list, remove it from the list by packing the array and fill the last element by 0.

Code:
import java.util.*;
 
public class RemoveElement {
   public static void main(String[] args) {
 
      // create an array and populate it
      int[] array = {1,2,3,4,5,6,7,8,9,10};
      System.out.println(Arrays.toString(array));
 
      // this will be the int to be removed from the array
      int x = 3;
      System.out.println("Removing: " + x);
 
      // here is where the work is done:
      for(int i=0; i<array.length; i++) {
         if(array[i]==x){
            // remove x and shift everything
            for(int j=i; j<array.length-1; j++){
               array[j] = array[j+1];
            }
            // fill last element with a zero
            array[array.length-1]=0;
         }
      } 
 
      System.out.println(Arrays.toString(array));
 
   }
}

Output:
$ java RemoveElement 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Removing: 3
[1, 2, 4, 5, 6, 7, 8, 9, 10, 0]

How to populate contents of a file into an ArrayList?

Question:
I have a file that has two columns of integers that need to be read in and populated into two separate ArrayLists with its content.

Code:
import java.io.*;
import java.util.*;
 
public class FileIntoArray {
   public static void main(String[] args) {
 
      ArrayList<Integer> col1 = new ArrayList<>(); 
      ArrayList<Integer> col2 = new ArrayList<>(); 
 
      try {
         FileInputStream is = new FileInputStream("data.txt");
         BufferedReader br = new BufferedReader(new InputStreamReader(is));
 
         String str;
         String values[]; 
 
         while ((str = br.readLine()) != null) {
            values = str.split(" "); 
            col1.add(Integer.parseInt(values[0])); 
            col2.add(Integer.parseInt(values[1])); 
         }
      } catch (Exception e) {
         // needs better exception handling in real world
         System.out.println(e.toString());
         col1.clear();
         col2.clear();
      }
      System.out.println("col1: " + col1);
      System.out.println("col2: " + col2);
   }
}

Output:
$ java FileIntoArray 
col1: [115, 123, 116, 113, 112, 104, 110, 218, 208]
col2: [257, 253, 246, 243, 239, 239, 238, 243, 242]

$ cat data.txt 
115 257
123 253
116 246
113 243
112 239
104 239
110 238
218 243
208 242 

How to test string for a Palindrome?

Question:
How can you test a string to see if it is a palidrome?

Answer:
By comparing the string with a 2nd string created by the method StringBuilder().reverse().

Code:
import java.util.*;
 
public class  Palidrome {
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
 
      System.out.println("Enter exit to quit.");
      while(true){
         System.out.print("Enter a word: ");
         String str = sc.nextLine();
 
         if(str.equals("exit")){
            break;
         }
 
         String reverse = new StringBuilder(str).reverse().toString();
         if (str.toLowerCase().compareTo(reverse.toLowerCase()) == 0) {
           System.out.println(str + " is a palidrome");
         } else {
           System.out.println(str + " is not a palidrome");
         }
      }
      sc.close();
   }
} 

Output:
$ java Palidrome 
Enter exit to quit.
Enter a word: hello
hello is not a palidrome
Enter a word: racecar
racecar is a palidrome
Enter a word: Racecar
Racecar is a palidrome
Enter a word: exit

How to test if an Array contains a certain value?

Question:
How to test if an Array contains a certain value?

Answer:
Iterate through the array looking for a match

Or

Convert array to a list and use the method contains()

Code:
import java.util.*;
 
public class TestArray {
   public static void main(String[] args) {
 
      String[] names = new String[] {"George","Paul","Ringo","John"};
      System.out.println(Arrays.toString(names));
 
      String who = "George";
 
      // iterate through the array looking for a match 
      for (int i = 0; i < names.length; i++){
         if(who.equals(names[i])){
            System.out.println( who + " is found");
            break;
         }
      }  
 
      // convert array to a list and use the method contains()
      List list = Arrays.asList(names);
      if(list.contains(who)){
         System.out.println( who + " is found");
      }
 
   }
}

Output:
$ java TestArray 
[George, Paul, Ringo, John]
George is found
George is found

How do you declare an array in java?

Question:
How do you declare an array in java?

Answer:
Here is an example on how to declare and initial arrays.

Code:
import java.util.*;
 
public class MyArray {
   public static void main(String[] args) {
 
      int[] array;
 
      // declare an array (not initialized)
      int[] array1 = new int[3];
      System.out.println("array1: " + Arrays.toString(array1));
 
      // declare and initialize
      int[] array2 = {1,2,3};
      System.out.println("array2: " + Arrays.toString(array2));
 
      // declare and initialize
      int[] array3 = new int[]{1,2,3};
      System.out.println("array3: " + Arrays.toString(array3));
 
 
      // two dimensional array (not initialized)
      int[][] array4 = new int[4][2];
      System.out.println("array4: " + Arrays.deepToString(array4));
 
      // two dimensional array and initialized
      int[][] array5 = { {1,2}, {1,2}, {1,2} ,{1,2}, {1,2} };
      System.out.println("array5: " + Arrays.deepToString(array5));
 
   }
}

Output:
$ java MyArray 
array1: [0, 0, 0]
array2: [1, 2, 3]
array3: [1, 2, 3]
array4: [[0, 0], [0, 0], [0, 0], [0, 0]]
array5: [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2]]

How do you convert a string to an Int

Question:
How does one convert a String to an int in Java?

Answer:
Use the method Integer.parseInt()

Code:
public class StringToInt {
   public static void main(String[] args) {
 
      String str1 = "111";
      String str2 = "333";
 
      int x1 = Integer.parseInt(str1);
      int x2 = Integer.parseInt(str2);
 
      int x3 = x1 + x2;
 
      System.out.println("x3 = " + x3);
 
   }
}

Output:
$ java StringToInt 
x3 = 444

How to sort an array of ints?

Question:
How do I do the following:

A user will input 3 different numbers and the program should return a 3-digit number in ascending order of the digits.

For example, if the user inputs 6, 1, 5 the returned integer should be 156.

Answer:
Put the three numbers in a array. Use the method Arrays.sort() to sort them. Then a little math to get to the final number.

Code:
import java.util.*;
 
public class SortNumbers {
 
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
 
      int[] input = new int[3];
 
      System.out.print("Enter Number: ");
      input[0] = sc.nextInt();
 
      System.out.print("Enter Number: ");
      input[1] = sc.nextInt();
 
      System.out.print("Enter Number: ");
      input[2] = sc.nextInt();
 
      System.out.println("Before: " + Arrays.toString(input));
      Arrays.sort(input);
      System.out.println("After: " + Arrays.toString(input));
 
      int number = input[0]*100;
      number = number + (input[1]*10);
      number = number + input[2];
 
      System.out.println("Number: " + number);
   }
}

Output:
$ java SortNumbers 
Enter Number: 6
Enter Number: 1
Enter Number: 5
Before: [6, 1, 5]
After: [1, 5, 6]
Number: 156

Write each character of a string to a queue (FIFO) and then read it back one character at a time.

Question:
Write each character of a string to a queue (FIFO) and then read it back one character at a time.

Answer:
Here is an example using the LinkedList class which implements a Queue. The string is put into the queue one letter at a time. Then read back one letter at a time.

Code:
import java.util.*;
 
public class QueueExample {
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter string: ");
      String str = sc.nextLine();
 
      Queue<Character> queue = new LinkedList<Character>();
 
      for(int i=0; i<str.length(); i++){
         queue.add(str.charAt(i));
      }
 
      String str2 = "";
      while( queue.peek() != null ){
        str2 = str2 + queue.remove(); 
        System.out.println(str2); 
      }
   }
}

Output:
$ java QueueExample
Enter string: ABCDEFGHIJ
A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH
ABCDEFGHI
ABCDEFGHIJ

Using a stack to reverse a string.

Question:
How to reverse a String using a stack?

Answer:
Here is an example using the java Stack class using the push(), pop() and empty() methods.

Code:
import java.util.*;
 
public class StackExample {
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter string: ");
      String str = sc.nextLine();
 
      Stack<Character> stack = new Stack<Character>();
 
      for(int i=0; i<str.length(); i++){
         stack.push(str.charAt(i));
      }
      while(! stack.empty()){
        System.out.print(stack.pop()); 
      }
      System.out.println(""); 
   }
}

Output:
$ java StackExample
Enter string: I love java
avaj evol I