Showing posts with label Tutorial. Show all posts
Showing posts with label Tutorial. Show all posts

Apr 4, 2017

Read and Write a File Line by Line in Java 8

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

public class FileTest {

 public static void main(String[] args) throws IOException  {
  
  Path pathToRead = Paths.get("C:\\...\\dataIn.csv");
  
  // Check if file exists
  if(!Files.exists(pathToRead)) {
   System.out.println("file doesn't exist :-(");
   return;
  };
  
  // read a file line by line
  Files.lines(pathToRead).forEach(line -> {
   // Process the String line here!!
   System.out.println(line);
  });
  
  // write a file line by line
  List<String> lines = Arrays.asList("line 1", "line 2", "line 3");
  Path pathToWrite = Paths.get("C:\\...\\dataOut.csv");
  Files.write(pathToWrite, lines);
 }
}

In Files.write() you can use also add Options, e.g. StandardOpenOption.CREATE or StandardOpenOption.APPEND. If omitted like above you get StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING.

More options to read/write also larger files in a buffered way are found here https://www.baeldung.com/java-read-file

Mar 31, 2014

Tutorial: Installing Eclipse with e(fx)clipse and Scene Builder for JavaFX

For e(fx)clipse you have two possibilites:
OR
  1. As a prerequisite install Xtext & Xtend 2.5.1 on Eclipse:  Help > Install new software... > work with: http://download.eclipse.org/modeling/tmf/xtext/updates/composite/releases/
  2. Install e(fx)clipse: http://www.eclipse.org/efxclipse/install.html (e.g. for version 0.9.0: Help > Install new software... > work with: http://download.eclipse.org/efxclipse/updates-released/0.9.0/site, check the Kepler-version)
  3. Install Scene Builder: http://www.oracle.com/technetwork/java/javase/downloads/javafxscenebuilder-info-2157684.html


Mar 20, 2014

Tutorial: Installing portable MinGW C-Compiler gcc on USB Flash Drive / Stick

If you work on different computers, but always want to have a C compiler with you, just create a portable version on an USB flash drive:
  1. Install MinGW to your computer, e.g. "C:\MinGW\"
  2. Copy "C:\MinGW\" to the USB drive "X:\MinGW\"
  3. Create a text file "X:\MinGW\bin\setpath.bat" with content set path=%path%;%CD%
  4. Run the batch file "X:\MinGW\bin\setpath.bat"
Now the bin directory of MinGW is in the search path. Now you can use the compiler gcc or other MinGW tools...

Tutorial: Installing Eclipse with JDK on USB Flash Drive / Stick

If you work on different computers, but want to have the same dev environment, just create a mobile version on an USB flash drive:
  1. Download Eclipse and unzip on your USB drive, e.g. "X:\eclipse" 
  2. Install a JDK on your computer (e.g. to "C:\Programme\Java\jdk1.7.xx")
  3. Copy "C:\Programme\Java\jdk1.7.x" to "X:\Java\jdk1.7.xx" j
  4. Paste into the file "X:\eclipse\eclipse.ini" just before "-vmargs"
  5.     -vm
        ..\Java\jdk1.7.xx\bin\javaw
  6. Start Eclipse with "X:\Eclipse\eclipse.exe" 
  7. Set the workspace to ".\workspace" (relative path!)
Done!

Mar 19, 2014

Tutorial: Installing Java 8 support for Eclipse Kepler

Java SE 8 has launched (http://www.oracle.com/technetwork/java/javase/downloads/index.html), but what about support in Eclipse Kepler? There is a feature patch (https://wiki.eclipse.org/JDT_Core/Java8), but only for Kepler SR2 (4.3.2). 

Installation (https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler):

  1. Help > Install New Software...
  2. enter the following URL into the 'Work with' field: http://download.eclipse.org/eclipse/updates/4.3-P-builds/
  3. select category 'Eclipse Java 8 Support (for Kepler SR2)'
  4. for faster install, deselect 'Contact all updates sites during install to find required software'
  5. click 'Next', click 'Next', accept the license, click 'Finish', restart Eclipse when asked...

Apr 24, 2013

Tutorial: Determinant of a Matrix in Java

Calculating the determinant of a quadratic matrix A=(a_ij) of size n using Laplace's formula with expanding along the i-th row is given by
where A_ij is the so-called minor (it is A with the i-th row and j-th column removed). Note that it is a recursive definition; it terminates since the size of the matrices decreases and the determinant of a number is the number itself.

In Java it can be implemented like this (for i=1, i.e. the first row):

package de.bigdev;

public class Determinant {

    /**
     * Determinant of a matrix using Laplace's formula with expanding along the
     * 0th row. It is not checked whether the matrix is quadratic!
     * 
     * @param m Matrix
     * @return determinant
     */
    public static double det(double[][] m) {
        int n = m.length;
        if (n == 1) {
            return m[0][0];
        } else {
            double det = 0;
            for (int j = 0; j < n; j++) {
                det += Math.pow(-1, j) * m[0][j] * det(minor(m, 0, j));
            }
            return det;
        }
    }

    /**
     * Computing the minor of the matrix m without the i-th row and the j-th
     * column
     * 
     * @param m input matrix
     * @param i removing the i-th row of m
     * @param j removing the j-th column of m
     * @return minor of m
     */
    private static double[][] minor(final double[][] m, final int i, final int j) {
        int n = m.length;
        double[][] minor = new double[n-1][n-1];
        // index for minor matrix position:
        int r = 0, s = 0;
        for (int k = 0; k < n; k++) {
            double[] row = m[k];
            if (k != i) {
                for (int l = 0; l < row.length; l++) {
                    if (l != j) {
                        minor[r][s++] = row[l];
                    }
                }
                r++;
                s = 0;
            }
        }
        return minor;
    }

    private static void printMatrix(double[][] m) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < m.length; i++) {
            double[] row = m[i];
            sb.append("[");
            for (int j = 0; j < row.length; j++) {
                sb.append(" ");
                sb.append(row[j]);
            }
            sb.append(" ]\n");
        }
        sb.deleteCharAt(sb.length() - 1);

        System.out.println(sb.toString());
    }

    public static void main(String[] args) {

        System.out.println("Determinant");
        System.out.println("===========");
        
        double[][] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 0 } };
        double[][] b = { { 1 } };
        double[][] c = { { 1, 2 }, { 3, 4 } };
        
        System.out.println("");
        System.out.println("Testing minor");
        System.out.println("=============");
        printMatrix(a);
        System.out.println("deleting row 3, and column 2:");
        printMatrix(minor(a, 2, 1));

        System.out.println("");
        System.out.println("Testing det");
        System.out.println("===========");
        
        printMatrix(b);
        System.out.println("has det=" + det(b) +"\n");
        
        printMatrix(c);
        System.out.println("has det=" + det(c) +"\n");
        
        printMatrix(a);
        System.out.println("has det=" + det(a) +"\n");
    }
}

You get following output on the console:


Determinant
===========

Testing minor
=============
[ 1.0 2.0 3.0 ]
[ 4.0 5.0 6.0 ]
[ 7.0 8.0 0.0 ]
deleting row 3, and column 2:
[ 1.0 3.0 ]
[ 4.0 6.0 ]

Testing det
===========
[ 1.0 ]
has det=1.0

[ 1.0 2.0 ]
[ 3.0 4.0 ]
has det=-2.0

[ 1.0 2.0 3.0 ]
[ 4.0 5.0 6.0 ]
[ 7.0 8.0 0.0 ]
has det=27.0

Apr 4, 2013

OOP Tutorial: 2-dimensional Vector as Scala Object

As before in Java: When starting to learn object orientated programming, a good first example is the following: Modelling a 2-dimensional vector over the real numbers could result in this (pay attention to the overloading of * and +. Compare to the verbose Java variant):

package de.bigdev

class Vector(val x: Double, val y: Double) {
    
  /**
   * Addition of two vectors
   *
   * @param v
   * @return the sum with v
   */
  def +(v: Vector) = new Vector(x + v.x, y + v.y)
  
  /**
   * Scalar Mulitplication with a constant
   *
   * @param c
   * @return the scalar multiplication with c
   */
  def *(c: Double) = new Vector(c * x, c * y)

  /**
   * Length of two vectors
   *
   * @return length
   */
  def length = math.sqrt(x * x + y * y)

  /**
   * Scalar Product of two vectors
   *
   * @param v
   * @return the scalar product with v
   */
  def *(v: Vector) = x * v.x + y * v.y
  
  /**
   * Angle between two vectors
   *
   * @param v
   * @return the angle with v in degrees
   */
  def angle(v: Vector) = math.acos(this * v / (this.length * v.length)) *
    180.0 / Math.PI

  override def toString = "[" + x + "," + y + "]"
}

For execution we need a main method (pay attention to the usage of *, + and angle):

package de.bigdev

object VectorTest {

  /**
   * for testing only... or use ScalaTest!
   */
  def main(args: Array[String]) {

    val v = new Vector(1, 1)
    val w = new Vector(-1, -1)

    println("Vector algebra")
    println("==============")
    println("addition      : " + v + " + " + w + " = " + (v + w))
    println("scalar multip.: 2 * " + v + " = " + v * 2)
    println("length        : ||" +v + "|| = " + v.length)
    println("scalar product: " + v + " * " + w + " = " + v * w)
    println("angle         : angle(" + v + ", " + w
      + ") = " + math.round(v angle w) + "°")
  }
}

The output on the console is:

Vector algebra
==============
addition      : [1.0,1.0] + [-1.0,-1.0] = [0.0,0.0]
scalar multip.: 2 * [1.0,1.0] = [2.0,2.0]
length        : ||[1.0,1.0]|| = 1.4142135623730951
scalar product: [1.0,1.0] * [-1.0,-1.0] = -2.0
angle         : angle([1.0,1.0], [-1.0,-1.0]) = 180°

OOP Tutorial: 2-dimensional Vector as Java Object

When starting to learn object orientated programming, a good first example is the following: Modelling a 2-dimensional vector over the real numbers could result in this

package de.bigdev;

public class Vector {

    private double x;
    private double y;

    public Vector(double x, double y) {
        super();
        this.x = x;
        this.y = y;
    }
    
    /**
     * Addition of two vectors
     *
     * @param v
     * @return the sum with v
     */
    public Vector add(Vector v) {
        return new Vector(x + v.x, y + v.y);
    }
    
    /**
     * Scalar Mulitplication with a constant
     *
     * @param c
     * @return the scalar multiplication with c
     */
    public Vector scalarMult(double c) {
        return new Vector(c * x, c * y);
    }

    /**
     * Length of two vectors
     * 
     * @return length
     */
    public double length() {
        return Math.sqrt(x * x + y * y);
    }

    /**
     * Scalar Product of two vectors
     * 
     * @param v
     * @return the scalar product with v
     */
    public double scalarProd(Vector v) {
        return this.x * v.getX() + this.y * v.getY();
    }

    /**
     * Angle between two vectors
     * 
     * @param v
     * @return the angle with v in degrees
     */
    public double angle(Vector v) {
        return Math.acos(this.scalarProd(v) / (this.length() * v.length()))
                * 180.0 / Math.PI;
    }

    public double getX() { return x; }
    public double getY() { return y; }

    @Override
    public String toString() {
        return "[" + x + ", " + y + "]";
    }

    /**
     * for testing only. should be factored out into another class... or use
     * JUnit!
     * 
     * @param args
     */
    public static void main(String[] args) {
        Vector v = new Vector(1, 1);
        Vector w = new Vector(-1, -1);

        System.out.println("Vector algebra");
        System.out.println("==============");
        System.out.println("addition      : " + v + " + " + w + " = " + v.add(w));
        System.out.println("scalar multip.: 2 * " + v + " = " + v.scalarMult(2));
        System.out.println("length        : ||" +v + "|| = " + v.length());
        System.out.println("scalar product: " + v + " * " + w + " = " + v.scalarProd(w));
        System.out.println("angle         : angle(" + v + ", " + w
          + ") = " + Math.round(v.angle(w)) + "°");
    }
}

The output on the console is


Vector algebra
==============
addition      : [1.0, 1.0] + [-1.0, -1.0] = [0.0, 0.0]
scalar multip.: 2 * [1.0, 1.0] = [2.0, 2.0]
length        : ||[1.0, 1.0]|| = 1.4142135623730951
scalar product: [1.0, 1.0] * [-1.0, -1.0] = -2.0
angle         : angle([1.0, 1.0], [-1.0, -1.0]) = 180°


Jan 22, 2013

Tutorial: Installing Eclipse IDE for C/C++ Developers on Windows

Here is a summary of the most important steps:
  1. Download and install a JDK version 8 (Java Development Kit) 
  2. Download Eclipse IDE for C/C++ Developers from http://www.eclipse.org/downloads/ (same bit version as for the JRE, i.e. 32 or 64 bit) and unzip e.g. to C:\dev\eclipse
  3. Download and install a C/C++ compiler (you will need gcc) for Windows, 

    • add the bin directory (e.g. C:\MinGW\bin) to the PATH variable, as before in 1.
    • Check on the command line: gcc
    • You should get: gcc: fatal error: no input files. compilation terminated. (this means gcc is found!!!)
  1. Start Eclipse with eclipse.exe. Then:
    • File > New > C Project
    • Enter a project name of your choice e.g. "helloworld"
    • Select project type "Hello World ANSI C Project" and toolchain "MinGW GCC"
    • Edit the source file:
    #include <stdio.h>
    
    int main(void) {
     printf("C/C++ on Eclipse...\n");
     return 0;
    }
    

  1. Initially build the project: either press Ctrl+B or click the "Hammer" button or right click the project and click "Build Project"
  2. Click the "Run" button. That's it!