Archive for the ‘JAVA’ Category

Return positions of matching closing parenthesis

Wednesday, November 25th, 2015
def get_closing_paren(sentence, opening_paren_index):
    open_nested_parens = 0
    position = opening_paren_index + 1

    for char in sentence[position:]:
        if char == '(':
            open_nested_parens += 1
        elseif char == ')':
            if open_nested_parens == 0:
                return position
            else:
                open_nested_parens -= 1
        position += 1

    raise Exception("No closing parenthesis :(")

source: https://www.interviewcake.com/question/matching-parens

JAVA Reflection handy MethodInspector Class

Sunday, December 8th, 2013

import java.lang.reflect.*;

public class MethodInspector {

public static void main(String[] arguments) {

Class inspect;
try {

if (arguments.length > 0)

inspect = Class.forName(arguments[0]);

else

inspect = Class.forName(“MethodInspector”);

Method[] methods = inspect.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {

Method methVal = methods[i];
Class returnVal = methVal.getReturnType();
int mods = methVal.getModifiers();
String modVal = Modifier.toString(mods);
Class[] paramVal = methVal.getParameterTypes();
StringBuffer params = new StringBuffer();
for (int j = 0; j < paramVal.length; j++) {

if (j > 0)

params.append(“, “);

params.append(paramVal[j].getName());

}
System.out.println(“Method: “ + methVal.getName() + “()”);
System.out.println(“Modifiers: “ + modVal);
System.out.println(“Return Type: “ + returnVal.getName());
System.out.println(“Parameters: “ + params + “\n”);

}

} catch (ClassNotFoundException c) {

System.out.println(c.toString());

}

}

}

credit: Sams Teach Yourself JAVA in 21 Days, Day 16, http://workbench.cadenhead.org/book/java21days/

JAVA Swing: JLabel, JOptionPane, JTextField, JSlider, JButton, JToolBar, JMenuItem, JMenu, JScrollPane, JProgressBar, JPanel, JTabbedPane

Saturday, September 28th, 2013

Example 1

import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;

public class FeedInfo extends JFrame {
private JLabel nameLabel = new JLabel(“Name: “,
SwingConstants.RIGHT);
private JTextField name;
private JLabel urlLabel = new JLabel(“URL: “,
SwingConstants.RIGHT);
private JTextField url;
private JLabel typeLabel = new JLabel(“Type: “,
SwingConstants.RIGHT);
private JTextField type;

public FeedInfo() {
super(“Feed Information”);
setSize(400, 145);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLookAndFeel();
// Site name
String response1 = JOptionPane.showInputDialog(null,
“Enter the site name:”);
name = new JTextField(response1, 20);

// Site address
String response2 = JOptionPane.showInputDialog(null,
“Enter the site address:”);
url = new JTextField(response2, 20);

// Site type
String[] choices = { “Personal”, “Commercial”, “Unknown” };
int response3 = JOptionPane.showOptionDialog(null,
“What type of site is it?”,
“Site Type”,
0,
JOptionPane.QUESTION_MESSAGE,
null,
choices,
choices[0]);
type = new JTextField(choices[response3], 20);

setLayout(new GridLayout(3, 2));
add(nameLabel);
add(name);
add(urlLabel);
add(url);
add(typeLabel);
add(type);
setLookAndFeel();
setVisible(true);
}

private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
“com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel”
);
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
System.err.println(“Couldn’t use the system ”
+ “look and feel: ” + e);
}
}

public static void main(String[] arguments) {
FeedInfo frame = new FeedInfo();
}
}

 

Example 2

import java.awt.event.*;
import javax.swing.*;

public class Slider extends JFrame {
public Slider() {
super(“Slider”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLookAndFeel();
JSlider pickNum = new JSlider(JSlider.HORIZONTAL, 0, 30, 5);
pickNum.setMajorTickSpacing(10);
pickNum.setMinorTickSpacing(1);
pickNum.setPaintTicks(true);
pickNum.setPaintLabels(true);
add(pickNum);
pack();
setVisible(true);
}

private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
“com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel”
);
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
System.err.println(“Couldn’t use the system ” + “look and feel: ” + e);
}
}

public static void main (String[] args) {
Slider frame = new Slider();
}
}

 

Example 3

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FeedBar extends JFrame {

public FeedBar() {
super(“FeedBar”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLookAndFeel();
// create icons
ImageIcon loadIcon = new ImageIcon(“load.gif”);
ImageIcon saveIcon = new ImageIcon(“save.gif”);
ImageIcon subscribeIcon = new ImageIcon(“subscribe.gif”);
ImageIcon unsubscribeIcon = new ImageIcon(“unsubscribe.gif”);
// create buttons
JButton load = new JButton(“Load”, loadIcon);
JButton save = new JButton(“Save”, saveIcon);
JButton subscribe = new JButton(“Subscribe”, subscribeIcon);
JButton unsubscribe = new JButton(“Unsubscribe”, unsubscribeIcon);
// add buttons to toolbar
JToolBar bar = new JToolBar();
bar.add(load);
bar.add(save);
bar.add(subscribe);
bar.add(unsubscribe);
// create menu
JMenuItem j1 = new JMenuItem(“Load”);
JMenuItem j2 = new JMenuItem(“Save”);
JMenuItem j3 = new JMenuItem(“Subscribe”);
JMenuItem j4 = new JMenuItem(“Unsubscribe”);
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu(“Feeds”);
menu.add(j1);
menu.add(j2);
menu.addSeparator();
menu.add(j3);
menu.add(j4);
menubar.add(menu);
// prepare user interface
JTextArea edit = new JTextArea(8, 40);
JScrollPane scroll = new JScrollPane(edit);
BorderLayout bord = new BorderLayout();
setLayout(bord);
add(“North”, bar);
add(“Center”, scroll);
setJMenuBar(menubar);
pack();
setVisible(true);
}

public void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
“com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel”
);
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
System.err.println(“Couldn’t use the system look and feel: ” + e);
}
}

public static void main(String[] arguments) {
FeedBar frame = new FeedBar();
}
}

 

Example 4

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ProgressMonitor extends JFrame {
JProgressBar current;
JTextArea find;
Thread runner;
int num = 0;

public ProgressMonitor() {
super(“Progress Monitor”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLookAndFeel();
setSize(205, 68);
setLayout(new FlowLayout());
current = new JProgressBar(0, 2000);
current.setValue(0);
current.setStringPainted(true);
add(current);
}

public void iterate() {
while (num < 2000) {
current.setValue(num);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
num += 95;
}
}

private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
“com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel”
);
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
System.err.println(“Couldn’t use the system ”
+ “look and feel: ” + e);
}
}

public static void main(String[] arguments) {
ProgressMonitor frame = new ProgressMonitor();
frame.setVisible(true);
frame.iterate();
}
}

 

Example 5

import java.awt.*;
import javax.swing.*;

public class TabPanels extends JFrame {
public TabPanels() {
super(“Tabbed Panes”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLookAndFeel();
setSize(480, 218);
JPanel mainSettings = new JPanel();
JPanel advancedSettings = new JPanel();
JPanel privacySettings = new JPanel();
JPanel emailSettings = new JPanel();
JPanel securitySettings = new JPanel();
JTabbedPane tabs = new JTabbedPane();
tabs.addTab(“Main”, mainSettings);
tabs.addTab(“Advanced”, advancedSettings);
tabs.addTab(“Privacy”, privacySettings);
tabs.addTab(“E-mail”, emailSettings);
tabs.addTab(“Security”, securitySettings);
add(tabs);
setVisible(true);
}

private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
“com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel”
);
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
System.err.println(“Couldn’t use the system ”
+ “look and feel: ” + e);
}
}

public static void main(String[] arguments) {
TabPanels frame = new TabPanels();
}
}

resource: Sams Teach Yourself JAVA in 21 Days, 6th Editions, Covers Java 7 and Android, Rogers Cadenhead

Find the nth Prime Number; Exceptions, Threads JAVA example

Tuesday, August 20th, 2013

public class PrimeThreads {
public static void main( String[] arguments ) {
PrimeThreads pt = new PrimeThreads( arguments );
}

public PrimeThreads( String[] arguments ) {
PrimeFinder[] finder = new PrimeFinder[arguments.length];
for( int i = 0; i < arguments.length; i++ ) {
try {
long count = Long.parseLong( arguments[i] );
finder[i] = new PrimeFinder(count);
System.out.println( “Looking for prime “ + count );
} catch ( NumberFormatException nfe ) {
System.out.println( “Error: “ + nfe.getMessage() );
}
}
boolean complete = false;
while( !complete ) {
complete = true;
for( int j=0;  j < finder.length; j++ ) {
if( finder[j]==null ) continue;
if( !finder[j].finished ) {
complete = false;
} else {
displayResult( finder[j] );
finder[j] = null;
}
}
try {
Thread.sleep( 1000 );
} catch ( InterruptedException ie ) {
// do nothing
}
}
}

private void displayResult( PrimeFinder finder ) {
System.out.println( “Prime “ + finder.target + ” is “ + finder.prime );
}
}

 

public class PrimeFinder implements Runnable {
public long target;
public long prime;
public boolean finished = false;
private Thread runner;

PrimeFinder( long inTarget ) {
target = inTarget;
if( runner == null ) {
runner = new Thread( this );
runner.start();
}
}

public void run() {
long numPrimes = 0;
long candidate = 2;
while( numPrimes < target ) {
if( isPrime(candidate) ) {
numPrimes++;
prime = candidate;
}
candidate++;
}
finished = true;
}

boolean isPrime( long checkNumber ) {
double root = Math.sqrt( checkNumber );
for( int i = 2; i <= root; i++ ) {
if( checkNumber % i == 0 )
return false;
}
return true;
}
}

run with command-line arguments, example: 1 10 100 1000

Example from: Sams Teach Yourself Java in 21 Days; 6th Edition Covers Java 7 and Android; Rogers Cadenhead, copyright 2013; chapter 7

JAVA LinkedList Class simple example

Wednesday, August 7th, 2013

import java.util.*;

public class LinkedListDemo {

public static void main(String args[]) {
// create a linked list
LinkedList ll = new LinkedList();
// add elements to the linked list
ll.add(“F”);
ll.add(“B”);
ll.add(“D”);
ll.add(“E”);
ll.add(“C”);
ll.addLast(“Z”);
ll.addFirst(“A”);
ll.add(1, “A2”);
System.out.println(“Original contents of ll: ” + ll);

// remove elements from the linked list
ll.remove(“F”);
ll.remove(2);
System.out.println(“Contents of ll after deletion: ”
+ ll);

// remove first and last elements
ll.removeFirst();
ll.removeLast();
System.out.println(“ll after deleting first and last: ”
+ ll);

// get and set a value
Object val = ll.get(2);
ll.set(2, (String) val + ” Changed”);
System.out.println(“ll after change: ” + ll);
}
}

Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]

credit: http://www.tutorialspoint.com/java/java_linkedlist_class.htm

JAVA count Fibonacci

Wednesday, August 7th, 2013
class Fib {
	public static void main( String[] args ) {
		int f = 0;
		int g = 1;

		for( int i = 1; i <= 10; i++) {
			System.out.print(f + " ");
			f = f + g;
			g = f - g;
		}

		System.out.println();
	}
}

JAVA simple Deque Interface example

Wednesday, August 7th, 2013

import java.util.*;

class Deque {
public static void main(String[] arguments){

ArrayDeque<String> ourDeque = new ArrayDeque<String>();

// fill our deque interface
String[] alph = { “a”,”b”,”c”,”d”,”e”,”f”,”g”,”h”,”i”,”j”,”k”,”l”,”m”,”n”,”o”,”p”,”q”,”r”,”s”,”t”,”u”,”v”,”w”,”x”,”y”,”z” };
for( int i = 0; i < alph.length; i++){
ourDeque.addFirst( alph[i] );
}

// foreach
for (String str : ourDeque) {
System.out.print(str);
}

System.out.println(“\n”);

// iterator
//ArrayDeque<String> ourDeque = new ArrayDeque<String>();
for (Iterator<String> iter = ourDeque.iterator(); iter.hasNext(); ) {
System.out.print(iter.next());
}

System.out.println(“\n”);

// Let’s do it forward though
int holdSize = ourDeque.size();
for ( int j = 0; j < holdSize; j++){
String getOne = ourDeque.removeLast();
System.out.print(getOne);
}

System.out.println(“\n”);
}
}

JAVA simple HashMap (+Generics) syntax example

Wednesday, August 7th, 2013

import java.util.*;

HashMap<String, Float> quality = new HashMap<>();
float price1 = 3.00F;
quality.put(“mint”, price1);
quality.get(“very fine”);
quality.clear();
quality.containsValue(price1);
quality.containsKey(“good”);

JAVA simple ArrayList example

Wednesday, August 7th, 2013

import java.util.*;

public class CodeKeeper {

ArrayList<String> list;
String[] codes = { “alpha”, “lambda”, “gamma”, “delta”, “zeta” };

public CodeKeeper(String[] userCodes) {

list = new ArrayList<>();
// load codes
for (int i = 0; i < codes.length; i++) {

if (!list.contains(code)) {

list.add(codes[i]);

}

}
// display all codes with new for loop
for (String code : list) {

System.out.println(code);

}

}

public static void main(String[] arguments) {

CodeKeeper keeper = new CodeKeeper(arguments);

}

}

reverse a String

Wednesday, August 7th, 2013

JAVA

class Reverso{
	public static void main(String[] args) {
		for (String toReverse: args) {
			int countOf = toReverse.length();
			for(int $i = toReverse.length() - 1; $i >= 0; $i--){
				System.out.print(toReverse.charAt($i));
			}
		}
	}
}

JavaScript

var reverse = function(str) {
    var arr = [];

    for (var i = 0, len = str.length; i <= len; i++) {
        arr.push(str.charAt(len - i))
    }

    return arr.join('');
}

document.writeln(reverse('lorem ipsum dolor'));

JAVA simple Array refresher & some String methods

Wednesday, August 7th, 2013

int[] holiday = { 1, 15, 50, 148, 185, 246, 281, 316, 326, 359 };
for (int i = 0; i < holiday.length; i++ ) {
someFunc(holiday[i]);
}

 

str.length()
str.charAt(6)
str.substring(26, 32)
str.indexOf(‘a’)
str.toUpperCase())

JAVA simple BitSet refresher

Tuesday, August 6th, 2013

import java.util.*;

BitSet connex = new BitSet();
connex.set(3);
connex.get(3);
connex.clear(3);
int numBits = connex.size();

Factorial of n recursive and iterative

Monday, August 5th, 2013

Recursive solution:

public int Factorial ( int n ) {
	if ( n == 0 ) {
		return 1;
	} else {
		return n * Factorial(n-1);
	}
}

Iterative Solution:

public int factorial ( int input ) {
	int x, fact = 1;
	for ( x = input; x > 1; x--) {
		fact *= x;
	}
	return fact;
}

Detect a Palindrome

Monday, August 5th, 2013
function isPalindrome(input)
{
	var len = input.length;

	var isPalindrome = true;

	// iterate through half the length of the string
	for(j = 0; j<len/2; j++)
	{
		if(input[j] != input[len - 1 -j])
		{
			isPalindrome = false;	
			break;
		}
	}

	return isPalindrome;
}
document.writeln(isPalindrome("hello"));
document.writeln(isPalindrome("Anna"));
document.writeln(isPalindrome("deified"));

JAVA simple StringTokenizer example

Sunday, August 4th, 2013

import java.util.StringTokenizer;

class TokenTester {

public static void main(String[] arguments) {

StringTokenizer st1, st2;

String quote1 = “GOOG 604.43 -0.42”;
st1 = new StringTokenizer(quote1);
System.out.println(“Token 1: ” + st1.nextToken());
System.out.println(“Token 2: ” + st1.nextToken());
System.out.println(“Token 3: ” + st1.nextToken());

String quote2 = “RHT@60.39@0.78”;
st2 = new StringTokenizer(quote2, “@”);
System.out.println(“\nToken 1: ” + st2.nextToken());
System.out.println(“Token 2: ” + st2.nextToken());
System.out.println(“Token 3: ” + st2.nextToken());

}

}

Simple JAVA app convert Fahrenheit to Celsius / Celsius to Fahrenheit

Sunday, August 4th, 2013

Really just so that I can quickly search for this formula… 🙂

 

public class Weather {

public static void main(String[] arguments) {

float fah = 86;

System.out.println(fah + ” degrees Fahrenheit is …”);
// To convert Fahrenheit into Celcius
// begin by subtracting 32
fah = fah – 32;
 // Divide the answer by 9
fah = fah / 9;
// Multiply that answer by 5
fah = fah * 5;
System.out.println(fah + ” degrees Celsius\n”);

float cel = 33;
System.out.println(cel + ” degrees Celsius is …”);
// To convert Celsius into Fahrenheit
// begin by multiplying by 9
cel = cel * 9;
// Divide the answer by 5
cel = cel / 5;
// Add 32 to the answer
cel = cel + 32;
System.out.println(cel + ” degrees Fahrenheit”);

}

}