Getting historical stock quotes using yahoofinance API

Question:
How to get historical stock quotes using yahoofinance API?

Answer:
Here is an example on how to get historical stock quotes using the YahooFinance API.

Code:
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import yahoofinance.Stock;
import yahoofinance.YahooFinance;
import yahoofinance.histquotes.HistoricalQuote;
import yahoofinance.histquotes.Interval;
 
public class YahooQuotes {
 
  public static void main(String[] args) throws IOException {
 
    Calendar from = new GregorianCalendar(2015, 5, 1);
    Calendar to = new GregorianCalendar(2015, 5, 10);
 
    Stock stock = YahooFinance.get("GOOG");
 
    List<HistoricalQuote> history = stock.getHistory(from, to, Interval.DAILY);
    for (HistoricalQuote hq : history) {
      System.out.print(hq.getSymbol() + " - ");
      System.out.print(hq.getClose() + " - ");
      System.out.println(hq.getDate().getTime());
    }    
 
  }
}

Output:
$ java YahooQuotes
GOOG - 536.690002 - Wed Jun 10 00:00:00 EDT 2015
GOOG - 526.690002 - Tue Jun 09 00:00:00 EDT 2015
GOOG - 526.830017 - Mon Jun 08 00:00:00 EDT 2015
GOOG - 533.330017 - Fri Jun 05 00:00:00 EDT 2015
GOOG - 536.700012 - Thu Jun 04 00:00:00 EDT 2015
GOOG - 540.309998 - Wed Jun 03 00:00:00 EDT 2015
GOOG - 539.179993 - Tue Jun 02 00:00:00 EDT 2015
GOOG - 533.98999 - Mon Jun 01 00:00:00 EDT 2015

How to get a single StockQuote using yahoofinance API?

Question:
How to get a StockQuote using yahoofinance API?

Answer:
Here is a simple example on how to get a single quote using the Java Finance Quotes API for Yahoo.Finance

Code:
import java.io.IOException;
import yahoofinance.Stock;
import yahoofinance.YahooFinance;
import yahoofinance.quotes.stock.StockQuote;
 
public class YahooStockQuoteAPI {
 
  public static void main(String[] args) throws IOException {
    YahooFinance yahoo = new YahooFinance();
    Stock stock = yahoo.get("GOOG");
    StockQuote sq = stock.getQuote();
 
    System.out.println("Symbol: " + sq.getSymbol());
    System.out.println("Price: " + sq.getPrice());
    System.out.println("Date: " + sq.getLastTradeTime().getTime());
  }
}

Output:
$ java YahooStockQuoteAPI 
Symbol: GOOG
Price: 662.20
Date: Fri Oct 16 16:00:00 EDT 2015

Converting BigDecimal to an int

Question:
How to Convert a BigDecimal to an int?
Converting BigDecimal to Integer

Answer:
bigdecimal.intValue();

Code:
import java.math.*;
 
public class BigDecimalTest {
  public static void main(String[] args) {
 
    BigDecimal big = new BigDecimal(123.456);
    int x = big.intValue();
    System.out.println(x);
  }
}
 

Output:
$ java BigDecimalTest
123

How to multiply a BigDecimal by an integer in Java?

Question:
How to multiply a BigDecimal by an int in Java?
Multiplication with BigDecimals.

Answer:
bigdecimal.multiply(new BigDecimal(int))

Code:
import java.math.*;
 
public class BigDecimalTest {
  public static void main(String[] args) {
 
    BigDecimal bd = new BigDecimal(2.0);
    int x = 5;
    bd = bd.multiply(new BigDecimal(x));
    System.out.println(bd);
  }
}
 

Output:
$ java BigDecimalTest
10

How to test if a BigDecimal is less then zero?

Question:
How to test if a BigDecimal is less then zero?
How to compare BigDecimal to an int?

Answer:
number.compareTo(BigDecimal.ZERO)

Code:
import java.math.*;
 
public class BigDecimalTest {
  public static void main(String[] args) {
    BigDecimal bd = new BigDecimal(-1.5);
 
    if (bd.compareTo(BigDecimal.ZERO) < 0) {
      System.out.println(bd + " is less then zero");
    }
  }
}
 

Output:
$ java BigDecimalTest
-1.5 is less then zero

How to write a java program that will ask for the length and width of a rectangle and then multiply them together and create a rectangle out of astrisks

Question:
How to write a java program that will ask for the length and width of a rectangle and then multiply them together and create a rectangle out of astrisks?

Code:
import java.util.Scanner;
 
public class Rectangle {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
 
    System.out.print("Enter height: ");
    int h = sc.nextInt();
 
    System.out.print("Enter width: ");
    int w = sc.nextInt();
 
    for(int i=0;i<h;i++){
      for(int j=0;j<w;j++){
        System.out.print("*");
      }
      System.out.println();
    }
  }
}

Output:
$ java Rectangle
Enter height: 5
Enter width: 20
********************
********************
********************
********************
********************

Find closest value to 0 for Float in Java?

Question:
Find closest value to 0 for Float in Java?

Answer:
Float.MIN_VALUE

Code:
public class MyFloat {
  public static void main(String[ ] args) {
    Float f = new Float(Float.MIN_VALUE);
    System.out.format("%.50f%n", f);
  }
}
 

Output:
$ java MyFloat
0.00000000000000000000000000000000000000000000140130

Write a java program that reads 10 numbers from the user, but does not allow the user to enter duplicates.

Question:
Write a java program that reads 10 numbers from the user, but does not allow the user to enter duplicates.

Code:
import java.util.*;
 
public class TenNumbers {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
 
    Set set = new TreeSet();
    do {
      System.out.print("Enter number: ");
      try {
        int i = sc.nextInt();
        if (set.contains(i)){
          System.out.println("Duplicate.");
        } else {
          set.add(i);
        }
      } catch (InputMismatchException e) {
         System.out.println("Not a number.");
         sc.nextLine();
      }
 
    } while (set.size()<10);
 
    System.out.println("set: " + set);
  }
}

Output:
$ java TenNumbers
Enter number: 1
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: 5
Enter number: 6
Enter number: 7
Enter number: 8
Enter number: 9
Enter number: ten
Not a number.
Enter number: 9
Duplicate.
Enter number: 10
set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

How to get screen resolution (screen size) using Java?

Question:
How to get screen resolution (screen size) using Java?

Code:
import java.awt.*;
 
public class GetScreenSize {
 
  public static void main(String[] args) {
 
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    System.out.println("Height: " + screen.height);
    System.out.println("Width: " + screen.width);
 
  }
}

Output:
$ java GetScreenSize
Height: 1200
Width: 1920

Counting vowels in a java string?

Question:
How to count vowels in a string?
How to count upper case vowels in a string?
How to count lower case vowels in a string?

Code:
public class CountVowels {
  public static void main(String[] args) {
 
    String str = "abcdefg HIJKLMNOP qrstuvwxyz";
 
    int upper = 0;
    int lower = 0;
    int non = 0;
 
    String vowels = "aeiouAEIOU";
    char[] array = str.toCharArray();
 
    for(char c: array) {
      if(vowels.indexOf(c) != -1){
        if(Character.isLowerCase(c)){
          lower = lower + 1;
        } else if(Character.isUpperCase(c)){
          upper = upper + 1;
        }
      } else {
         non = non + 1;
      }
    }
    System.out.println("String: " + str);
    System.out.println("Upper case vowels: " + upper);
    System.out.println("Lower case vowels: " + lower);
    System.out.println("Non vowels: " + non);
  }
}

Output:
$ java CountVowels
String: abcdefg HIJKLMNOP qrstuvwxyz
Upper case vowels: 2
Lower case vowels: 3
Non vowels: 23

Creating a celsius to fahrenheit calculator using a JSlider.

Question:
Create a celsius to fahrenheit calculator using a JSlider.

Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
 
public class CelsiusToFahrenheit {
 
  public static void main(String[] arguments) {
 
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame f = new JFrame("Celsius To Fahrenheit");
    f.setSize(400,200);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
    JPanel container = new JPanel();
    container.setBorder(BorderFactory.createEmptyBorder(0,20,0,20));
    container.setLayout(new GridLayout(3, 1));
 
    JPanel results = new JPanel();
    results.setLayout(new FlowLayout());
 
    JLabel cLabel = new JLabel("Celsius: ");
    final JTextField cText = new JTextField(5);
 
    JLabel fLabel = new JLabel("Fahrenheit: ");
    final JTextField fText = new JTextField(5);
    results.add(cLabel);
    results.add(cText);
    results.add(fLabel);
    results.add(fText);
 
 
    JLabel sLabel = new JLabel("Celsius Slider",JLabel.CENTER);
    final JSlider slider = new JSlider(JSlider.HORIZONTAL,0,100,10);
    slider.setMinorTickSpacing(5);  
    slider.setMajorTickSpacing(20);  
    slider.setPaintTicks(true);  
    slider.setPaintLabels(true);  
 
 
    slider.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        int c = slider.getValue();
        fText.setText("" + (c * (double) 9 / 5 + 32) );
        cText.setText("" + c);
      }
    });
 
    // set default value
    fText.setText("" + (slider.getValue() * (double) 9 / 5 + 32) );
    cText.setText("" + slider.getValue());
 
    container.add(sLabel);
    container.add(slider);
    container.add(results);
 
    f.add(container);
    f.setVisible(true);
 
  }
}
 

Output:
 

Drawing a Rectangle using astrisks

Question:
How to write a java program that will ask for the length and width of a rectangle and then multiply them together and create a rectangle out of astrisks?

Code:
import java.util.Scanner;
 
public class Rectangle {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
 
    System.out.print("Enter height: ");
    int h = sc.nextInt();
 
    System.out.print("Enter width: ");
    int w = sc.nextInt();
 
    for(int i=0;i<h;i++){
      for(int j=0;j<w;j++){
        System.out.print("*");
      }
      System.out.println();
    }
  }
}

Output:
$ java Rectangle
Enter height: 5
Enter width: 20
********************
********************
********************
********************
********************

m(i)=1/3 + 2/5 +...+ i/(2i+i)

Question:
java program to solve: 

  m(i)=1/3 + 2/5 +...+ i/(2i+i)

Answer:
Use recursion

Code:
import java.util.Scanner;
 
public class Example {
 
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      System.out.print("Enter a value: ");
      int n = input.nextInt();
 
      double d = m(n);
      System.out.println("m(5) = " + d );
   }
 
   public static double m(int i) {
      double d = (double)i/(2*i+1);
      if(i <= 1){
        return(d);
      } else {
        return (d + m(i-1));
      }
   }
}

Output:
$ java Example
Enter a value: 5
m(5) = 2.060894660894661

Create ArrayList (ArrayList) from array (T[])

Question:
I have an array that is initialized like:
  Element[] array = {new Element(1), new Element(2), new Element(3)};

I would like to convert this array into an object of the ArrayList class:
  ArrayList arraylist = ???;

Answer:
new ArrayList(Arrays.asList(array))

Code:
import java.util.*;
 
public class ArrayToArrayList {
 
  public static void main(String[] args) {
 
    String[] array = {new String("aaa"),new String("bbb"),new String("ccc")};
 
    ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));
 
    System.out.println("array: " + Arrays.toString(array));
    System.out.println("list: " + list);
 
  }
}

Output:
$ java ArrayToArrayList
array: [aaa, bbb, ccc]
list: [aaa, bbb, ccc]

How do I convert int[] into List in Java?

Question:
How do I convert int[] into List in Java?

Code:
import java.util.*;
 
public class IntToList {
 
  public static void main(String[] args) {
 
    int[] ints = new int[]{1,2,3,4,5,6,7,8,9};
 
    List<Integer> list = new ArrayList<Integer>();
    for (int n = 0; n < ints.length; n++) {
        list.add(ints[n]);
    }
 
    System.out.println("int[] ints: " + Arrays.toString(ints));
 
 
    System.out.print("List<Integer> list: ");
    for(int i=0;i<list.size();i++){
      System.out.print(list.get(i) + " ");
    }
    System.out.println();
  }
}

Output:
$ java IntToList
int[] ints: [1, 2, 3, 4, 5, 6, 7, 8, 9]
List list: 1 2 3 4 5 6 7 8 9 

How to convert Byte[] to byte[] in java?

Question:
How to convert Byte[] to byte[] in java?

Code:
import java.util.Arrays;
 
public class BytesToBytes {
  public static void main(String[] args) {
 
    Byte[] B = new Byte[]{1,2,3,4,5,6,7,8,9};
    byte[] b = new byte[B.length];
 
    for (int i = 0; i < B.length; i++) {
      b[i] = B[i];
    }
 
    System.out.println("Byte[] B: " + Arrays.toString(B));
    System.out.println("byte[] b: " + Arrays.toString(b));
  }
}

Output:
$ java BytesToBytes
Byte[] B: [1, 2, 3, 4, 5, 6, 7, 8, 9]
byte[] b: [1, 2, 3, 4, 5, 6, 7, 8, 9]

How to convert byte[] to Byte[] in java?

Question:
How to convert byte[] to Byte[] in java?

Code:
import java.util.Arrays;
 
public class BytesToBytes {
  public static void main(String[] args) {
 
    byte[] b = new byte[]{1,2,3,4,5,6,7,8,9};
    Byte[] B = new Byte[b.length];
    for (int i = 0; i < b.length; i++) {
        B[i] = Byte.valueOf(b[i]);
    }
 
    System.out.println("byte[] b: " + Arrays.toString(b));
    System.out.println("Byte[] B: " + Arrays.toString(B));
  }
}

Output:
$ java BytesToBytes
byte[] b: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Byte[] B: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Java program that counts words in a file

Question:
Write a java program that counts words in a file?

Answer:
Here is an example that counts the words in a file called TheCatInTheHat.txt.

Code:
import java.io.*;
import java.util.*;
 
public class WordCount {
  public static void main(String[] args) throws FileNotFoundException {
    Map<String, Integer> map = new HashMap<String, Integer>();
 
    Scanner in = new Scanner(new File("TheCatInTheHat.txt"));
    while (in.hasNext()) {
      String word = in.next();
      word = word.replaceAll("[^a-zA-Z0-9]", "");
      word = word.toLowerCase();
 
      if(map.containsKey(word)) {
        Integer count = (Integer)map.get(word);
        map.put(word, new Integer(count.intValue() + 1));
      } else {
        map.put(word, new Integer(1));
      }
    }
 
    ArrayList arraylist = new ArrayList(map.keySet());
    Collections.sort(arraylist);
 
    for (int i = 0; i < arraylist.size(); i++) {
      String key = (String)arraylist.get(i);
      Integer count = (Integer)map.get(key);
      System.out.println(key + " : " + count);
    }
 
  }
}

Output:
$ java WordCount
a : 33
about : 3
after : 1
all : 15
always : 1
and : 69
another : 2
any : 1
are : 5
as : 9
asked : 1
at : 14
away : 6
back : 2
bad : 2
ball : 5
be : 7
bed : 1
bent : 1
bet : 2
big : 5
bit : 3
bite : 1
.......

Java program to sort a map by value.

Question:
How to sort or order a HashMap or TreeSet or any map item by value?

Answer:
Write a comparator which compares by value, not by key.

Code:
import java.util.*;
import java.util.Map.*;
 
public class SortHashMap {
 
  public static void main(String a[]){
 
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("apple", 20);
    map.put("plum", 11);
    map.put("orange", 16);
    map.put("peach", 3);
    map.put("grape", 7);
 
    Set<Entry<String,Integer>> set = map.entrySet();
    List<Entry<String,Integer>> list = new ArrayList<Entry<String,Integer>>(set);
 
    Collections.sort(list, new Comparator<Map.Entry<String,Integer>>() {
      public int compare( Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) {
        return (o2.getValue()).compareTo( o1.getValue());
      }
    });
 
    for(Map.Entry<String, Integer> entry:list){
      System.out.println(entry.getValue() + " " + entry.getKey());
    }
  }
}

Output:
$ java SortHashMap
20 apple
16 orange
11 plum
7 grape
3 peach

Test if two numbers have the same digits.

Question:
How to test if two numbers contain the same digits.

Answer:
Convert the numbers to Strings.
Convert the Strings to a Char Arrays.
Sort the Char Arrays.
Compare the Char Arrays.

Code:
import java.util.Arrays;
 
public class Example {
  public static void main(String[] args) {
    System.out.println("12 & 21: " + match(12,21));
    System.out.println("123 & 321: " + match(123,321));
    System.out.println("1231 & 2131: " + match(1231,2131));
    System.out.println("876 & 886: " + match(876,866));
  }
  public static boolean match(int a, int b) {
 
    String s1 = String.valueOf(a);
    char[] c1 = s1.toCharArray();
    Arrays.sort(c1);
 
    String s2 = String.valueOf(b);
    char[] c2 = s2.toCharArray();
    Arrays.sort(c2);
 
    return(Arrays.equals(c1,c2));
  }
}

Output:
$ java Example
12 & 21: true
123 & 321: true
1231 & 2131: true
876 & 886: false