scala 構文2

object MyApp{

  def main(args: Array[String]): Unit = {
  // for(ジェネレータ ※変数<-データ集合)
  for (i <- 0 to 3; j <- 0 to 3 if i != j) println(s"i, $j")

  }

}

method

object MyApp{

  // method

  def sayHi: String = {
      // println("hi!")
      "hi!"
  }

  def main(args: Array[String]): Unit = {
    println(sayHi)

  }

}

メソッドの引数

object MyApp{

  def sayHi(name: String = "yokota", age: Int = 23): Unit = {
      println(s"hi! $name ($age)")
  }

  def main(args: Array[String]): Unit = {
    sayHi("bob", 35)
    sayHi("tom", 43)
    sayHi()
    sayHi(age = 18, name="jack")

  }

}

class

class User {
  val name = "my name"
  def sayHi() =  println("hi!")
}

object MyApp{
  def main(args: Array[String]): Unit = {
    val user = new User
    println(user.name)
    user.sayHi()
  }

}

コンストラクタ引数

class User(_name: String) {
  val name = _name
  def sayHi() =  println("hi!" + this.name)
}

object MyApp{
  def main(args: Array[String]): Unit = {
    val tom = new User("tom")
    println(tom.name)
    tom.sayHi()
  }

}

継承、override

class User(val name: String) {
  def sayHi() =  println("hi!" + this.name)
}

class AdminUser(name: String, val age: Int) extends User(name) {
  def sayHello() =  println("hello!" + name + "(" + age  + ")")
  override def sayHi() = println("[admin] hi " + name)
}

object MyApp{
  def main(args: Array[String]): Unit = {
    val bob = new AdminUser("bob", 23)
    println(bob.name)
    println(bob.age)
    bob.sayHi()
    bob.sayHello()
  }

}

package

package com.hpscript.model 

class User(val name: String) {
  def sayHi() =  println("hi!" + this.name)
}

class AdminUser(name: String, val age: Int) extends User(name) {
  def sayHello() =  println("hello!" + name + "(" + age  + ")")
  override def sayHi() = println("[admin] hi " + name)
}

アクセス修飾子

class User {
  protected var name = "user"
  def sayHi() =  println("hi!" + this.name)
}

class AdminUser extends User {
  override def sayHi() = println("[admin] hi " + name)
}

object MyApp{
  def main(args: Array[String]): Unit = {
    val user = new User
    val adminUser = new AdminUser
     // println(user.name)
    user.sayHi()
    adminUser.sayHi()
  }

}

object

object User {
 def getInfo() = println("User Object")
}

class User(val name: String) {
  def sayHi() =  println("hi!" + this.name)
}

object MyApp{
  def main(args: Array[String]): Unit = {
    User.getInfo()
  }

}

抽象クラス

abstract class User{
  def sayHi()
}

class Japanese extends User {
 def sayHi() = println("こんにちは")
}

class American extends User {
 def sayHi() = println("hello")
}

object MyApp{
  def main(args: Array[String]): Unit = {
   val aki = new Japanese
   val tom = new American
   aki.sayHi()
   tom.sayHi()
  }

}

trait

trait Printable {
 def print() = println("now printing ...")
}

trait Sharable {
 def share() = println("now sharing ...")
}

class User extends Printable with Sharable

object MyApp{
  def main(args: Array[String]): Unit = {
    val user  = new User
    user.print()
    user.share()
  }

}

型パラメータ

//class MyInt {
//  def getThree(i: Int): Unit = println(s"$i $i $i")
//}

class MyData[T]{
  def getThree(i: T): Unit = println(s"$i $i $i")
}

object MyApp{
  def main(args: Array[String]): Unit = {
    val i = new MyData[Int]
    i.getThree(5)
    val s = new MyData[String]
    s.getThree("hello")
  }

}

scala構文

変数

object MyApp{

  def main(args: Array[String]): Unit = {
   // 変数
   // - val:値の再代入ができない
   // - var:値の再代入ができる

   // val msg: String = "hello world";
   val msg = "hello world again"
    println(msg)
  }
}

データ型

// 整数 Byte Short Int Long
   val i = 5
   val l = 5555555555L
   val d = 32534.4
   val f = 234.34F
   val c = 'a' // 文字char
   val s = "Hello" // 文字列string
   var flag = true // Boolean
   val msg = "hello\n world again\t"
    println(msg)

四則演算

   // + - * / %
   val x = 10
   println(x / 3)
   println(x / 3.0)
   println(x % 3)

   var y = 6
   y += 10
   println(y)

   var s = "hello"
   println(s + "world")

   var flag = true
   println(!flag)

文字列

object MyApp{

  def main(args: Array[String]): Unit = {
   var name = "igarashi"
   var score = 55
   val height = 159.32

   println(s"name: $name, score: $score, height: $height")
   println(s"name: $name, score: ${score + 10}, height: $height")

   println(f"name: $name%s, score: $score%d, height: $height%f")
   println(s"name: $name%10s, score: $score%10d, height: $height%10f")
  }
}

条件分岐

object MyApp{

  def main(args: Array[String]): Unit = {
   val score = 85
   if (score > 80) println("Great!")
   else if (score > 60) println("Great!")
   else println("soso...")
  }
}

条件分岐 match

object MyApp{

  def main(args: Array[String]): Unit = {
   val signal = "red"
   var result = signal match {
    case "red" => "stop"
    case "blue" | "green" => "go"
    case "yellow" => "caution"
    case _ => "wrong signal"
   }
   println(result)
  }
}

while

object MyApp{

  def main(args: Array[String]): Unit = {
   var i = 0
   while (i < 10){
   println(i)
   i += 1
   }
  }
}

sbt 及び scalaのインストール

sbtのインストール

http://www.scala-sbt.org/0.13/docs/Installing-sbt-on-Linux.html

curl https://bintray.com/sbt/rpm/rpm | sudo tee /etc/yum.repos.d/bintray-sbt-rpm.repo
sudo yum install sbt

atomにもscala-formatのpackageをインストールしておきます。

sbt -> console でscalaのコマンドを試すことができます。

[vagrant@localhost scala]$ sbt
[info] Set current project to scala (in build file:/home/vagrant/scala/)
scala> 1 + 2
res0: Int = 3

scala> 2 + 2
res1: Int = 4

メモリが足りないと表示された場合は、sbt -mem 512でスタートさせます。

sbt -mem 512

ファイルは、src/main/scala/が推奨されています。
コンパイル実行は、sbt-> runとします。

object MyApp{

  def main(args: Array[String]): Unit = {
    println("hello world")
  }
}
[vagrant@localhost scala]$ sbt
[info] Set current project to scala (in build file:/home/vagrant/scala/)
> run
[info] Compiling 1 Scala source to /home/vagrant/scala/target/scala-2.11/classes...
[info] Running MyApp
hello world
[success] Total time: 20 s, completed 2016/11/21 16:55:04

Java 構文5

HashMap

import java.util.*;

public class MyApp{
  public static void main(String[] args){
      HashMap<String, Integer> sales = new HashMap<>();

      sales.put("tom", 10);
      sales.put("john", 20);
      sales.put("mason", 30);

          System.out.println(sales.get("tom"));
          System.out.println(sales.size());

          for (Map.Entry<String, Integer> sale: sales.entrySet()){
            System.out.println(sale.getKey() + ":" + sale.getValue());
          }
    }
}

StreamAPI

import java.util.*;

public class MyApp{
  public static void main(String[] args){

      List<Integer> sales = new ArrayList<>(Arrays.asList(12, 30, 22, 4, 9));
      sales
       .stream()
       // 中間処理
       .filter(e -> e % 3 == 0)
       // 終端処理
       .map(e -> "(" + e+ ")")
       .forEach(System.out::println);
    }
}

LocalDateTime

import java.time.*;
import java.time.format.DateTimeFormatter;

public class MyApp{
  public static void main(String[] args){
      LocalDateTime d = LocalDateTime.now();
      // LocalDateTime d = LocalDateTime.of(2017, 1, 1, 10, 10, 10);
      // LocalDateTime d = LocalDateTime.parse("2016-12-12T10:10:10");

      System.out.println(d.getYear());
      System.out.println(d.getMonth());
      System.out.println(d.getMonth().getValue());

      System.out.println(d.plusMonths(2).minusDays(3));
      DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy!MM!dd!");
      System.out.println(d.format(dtf));
    }
}

Java 構文4

例外

// 例外処理
class MyException extends Exception {
  public MyException(String s){
    super(s);
  }
}

public class MyApp{

  public static void div(int a, int b){
    try {
      if (b < 0){
        throw new MyException("not minus!");
      }
      System.out.println(a / b);
    } catch (ArithmeticException e){
      System.err.println(e.getMessage());
    } catch (MyException e){
      System.err.println(e.getMessage());
    } finally{
      System.out.println(" -- end -- ");
    }
  }
  public static void main(String[] args){
    div(3, 0);
    div(5, -2);
  }
}

ラッパークラス

public class MyApp{
  public static void main(String[] args){
    // Integer i = new Integer(32);
    // int n = i.intValue();
    Integer i = 32; // auto boxing
    i = null;
    int n = i; // auto unboxing
    
    System.out.println();
  }
}

generics:型の汎用化

class MyData<T> {
  public void getThree(T x){
    System.out.println(x);
    System.out.println(x);
    System.out.println(x);
  }
}

public class MyApp{
  public static void main(String[] args){
    // MyInteger mi = new MyInteger();
    // mi.getThree(55);
    MyData<Integer> i = new MyData<>();
    i.getThree(32);
    MyData<String> s = new MyData<>();
    s.getThree("hello");
  }
}

Thread処理:

class MyRunnable implements Runnable{
  @Override
  public void run(){
    for (int i= 0; i < 500; i++){
      System.out.print('*');
    }
  }
}

public class MyApp{
  public static void main(String[] args){
    MyRunnable r = new MyRunnable();
    Thread t = new Thread(r);
    t.start();

    for (int i= 0; i < 500; i++){
      System.out.print('.');
    }
  }
}

無名クラス

public class MyApp{
  public static void main(String[] args){
    // MyRunnable r = new MyRunnable();
    // Thread t = new Thread(r);
    // t.start();
    new Thread(new Runnable(){
      @Override
      public void run(){
        for (int i= 0; i < 500; i++){
          System.out.print('*');
        }
      }
    }).start(); // 無名クラス

    for (int i= 0; i < 500; i++){
      System.out.print('.');
    }
  }
}

Stringクラス

public class MyApp{
  public static void main(String[] args){
      String s = "abcdef";
      System.out.print(s.length());
      System.out.print(s.substring(2, 5));
      System.out.print(s.replaceAll("ab","AB"));

      String s1 = "ab";
      String s2 = "ab";

      if (s1.equals(s2)){
        System.out.print("same!");
      }

      if (s1 == s2){
        System.out.print("same!same!");
      }
    }
}

printfメソッド

public class MyApp{
  public static void main(String[] args){
    int score=50;
    double height=165.8;
    String name ="yoshimoto";

      System.out.printf("name: %s, score: %d, height: %f\n", name, score, height);
      System.out.printf("name: %-10s, score: %10d, height: %5.2f\n", name, score, height);

      String s = String.format("name: %10s, score: %-10d, height: %5.2f\n", name, score, height);
      System.out.println(s);
    }
}

Math, randomクラス

import java.util.Random;

public class MyApp{
  public static void main(String[] args){
      double d = 53.234;
      System.out.println(Math.ceil(d));
      System.out.println(Math.floor(d));
      System.out.println(Math.round(d));
      System.out.println(Math.PI);

      Random r = new Random();
      System.out.println(r.nextDouble()); // 0-1
      System.out.println(r.nextInt(100)); // 0-1
      System.out.println(r.nextBoolean()); // 0-1
    }
}

ArrayList

import java.util.*;

public class MyApp{
  public static void main(String[] args){
      List sales = new ArrayList<>();

      sales.add(10);
      sales.add(20);
      sales.add(30);

      for (int i = 0; i < sales.size(); i++){
        System.out.println(sales.get(i));
      }

      sales.set(0, 100);
      sales.remove(2);

      for (Integer sale: sales){
        System.out.println(sale);
      }

    }
}

Hash.set

import java.util.*;

public class MyApp{
  public static void main(String[] args){
      HashSet sales = new HashSet<>();

      sales.add(10);
      sales.add(20);
      sales.add(30);
      sales.add(10);

        System.out.println(sales.size());

        for (Integer sale: sales){
          System.out.println(sale);
        }
        sales.remove(30);
        for (Integer sale: sales){
          System.out.println(sale);
        }
    }
}

Java 構文3

getter, setter

class User {
  private String name;
  private int score;

  public User(String name, int score){
    this.name = name;
    this.score = score;
  }

  public int getScore(){ //getter
    return this.score;
  }

  public void setScore(int score){
    if (score > 0) {
    this.score = score;
   }
  }

}

public class MyApp{

  public static void main(String[] args){
    User tom = new User("tom", 65); // instance
    tom.setScore(85);
    tom.setScore(-22);
    System.out.println(tom.getScore());
  }
}

static:インスタンス化しなくても、クラスから直接扱えるフィールドやメソッドを定義できます。

class User {
  private String name;
  private static int count = 0;

  public User(String name){
    this.name = name;
    User.count++;
  }

  public static void getInfo(){
    System.out.println("# of instances: " + User.count);
  }

}

public class MyApp{

  public static void main(String[] args){
    User.getInfo();
    User tom = new User("tom");
    User.getInfo();
  }
}

initializer

class User {
  private String name;
  private static int count; //クラス変数

  static {
    User.count = 0;
    System.out.println("static initializer");
  }

  {
    System.out.println("Instance initializer");
  }

  public User(String name){
    this.name = name;
    User.count++;
    System.out.println("constructor initializer");
  }

  public static void getInfo(){
    System.out.println("# of instances: " + User.count);
  }

}

変更できないfinal修飾子

// final 変更できない

final class User {
  protected String name;
  private static final double VERSION = 1.1;

  public User(String name){
    this.name = name;
    User.VERSION = 1.2;
  }

  public final void sayHi(){
    System.out.println("hi! " + this.name);
  }
}

class AdminUser extends User {
  public AdminUser(String name){
    super(name);
  }

  @override
  public void sayHi(){
    System.out.println("[Admin]hi!" + this.name);
  }
}

public class MyApp{

  public static void main(String[] args){
    User tom = new User("tom");
  }
}

抽象クラス

//抽象クラス -> 具象クラス

abstract class User {
  public abstract void sayHi();
}

class JapaneseUser extends User {
  @Override
  public void sayHi(){
    System.out.println("こんにちは!");
  }
}

class AmericanUser extends User {
  @Override
  public void sayHi(){
    System.out.println("hi!");
  }
}

public class MyApp{

  public static void main(String[] args){
    AmericanUser tom = new AmericanUser();
    JapaneseUser aki = new JapaneseUser();
    tom.sayHi();
    aki.sayHi();
  }
}

interface

//interface

interface Printable {
  //定数、
double VERSION = 1.2;
  //抽象
  void print();
 // default method
 public default void getInfo(){
   System.out.println("I/F ver. " + Printable.VERSION);
 }
 // static
}


class User implements Printable {
  @Override
  public void print(){
    System.out.println("Now printing user prifile...");
  }

}

public class MyApp{

  public static void main(String[] args){
    User tom = new User();
    tom.print();
    tom.getInfo();
  }
}

列挙型とordinal()

// 列挙型
enum Result {
  SUCCESS,
  ERROR,
}

public class MyApp{

  public static void main(String[] args){
    Result res;

    res = Result.ERROR;

    switch (res){
      case SUCCESS:
      System.out.println("OK!");
      System.out.println(res.ordinal());
      break;
      case ERROR:
      System.out.println("NG!");
      System.out.println(res.ordinal());
      break;
    }

  }
}

Java packageの書き方

クラス

class User {
  String name = "Me"; // field

  void sayHi(){
    System.out.println("hi!");
  }
}

public class MyApp{

  public static void main(String[] args){

    User tom;
    tom = new User(); // instance
    System.out.println(tom.name);
    tom.sayHi();
  }
}

コンストラクター:クラスの初期化

class User {
  String name;

  // constructor
  User(String name){
    this.name = name;
  }

  // User(){
  //   this.name = "me";
  // }

  User(){
    this("me!");
  }

  void sayHi(){
    System.out.println("hi!" + this.name);
  }
}

public class MyApp{

  public static void main(String[] args){

    User tom;
    tom = new User(); // instance
    System.out.println(tom.name);
    tom.sayHi();
  }
}

クラスの継承とoverride

class User {
  String name;

  User(String name){
    this.name = name;
  }

  void sayHi(){
    System.out.println("hi!" + this.name);
  }
}

class AdminUser extends User {
  AdminUser(String name){
    super(name);
  }
  void sayHello(){
    System.out.println("hello!" + this.name);
  }

  // override
  @Override
  void sayHi(){
    System.out.println("[admin] hi!" + this.name);
  }

}

public class MyApp{
  public static void main(String[] args){

    User tom = new User("tom"); // instance
    System.out.println(tom.name);
    tom.sayHi();

    AdminUser bob = new AdminUser("bob"); // instance
    System.out.println(bob.name);
    bob.sayHi();
    bob.sayHello();
  }
}

public:アクセス可
private:同じクラスならアクセス可能
protected:同じパッケージのみ

パッケージ化
com/hpscript/myapp/MyApp.java

package com.hpscript.myapp;
import com.hpscript.myapp.model.User;
import com.hpscript.myapp.model.AdminUser;
// import hpscript.myapp.model.*;

public class MyApp{
  public static void main(String[] args){

    User tom = new User("tom"); // instance
    // System.out.println(tom.name);
    tom.sayHi();

    AdminUser bob = new AdminUser("bob"); // instance
    // System.out.println(bob.name);
    bob.sayHi();
    bob.sayHello();
  }
}

com/hpscript/myapp/model/User.java

package com.hpscript.myapp.model;

public class User {
  protected String name;

  public User(String name){
    this.name = name;
  }

  public void sayHi(){
    System.out.println("hi!" + this.name);
  }
}

com/hpscript/myapp/model/AdminUser.java

package com.hpscript.myapp.model;

public class AdminUser extends User {
  public AdminUser(String name){
    super(name);
  }
  public void sayHello(){
    System.out.println("hello!" + this.name);
  }

  // override
  @Override
  public void sayHi(){
    System.out.println("[admin] hi!" + this.name);
  }

}

java 構文

条件分岐

int score = 35;
    if (score > 80){
      System.out.println("great");
    } else if (score> 60){
      System.out.println("good");
    } else {
    System.out.println("soso");
  }
int score = 65;
  String msg = score > 80 ? "great" : "soso...";

switch

String signal = "red";
    switch (signal){
      case "red":
        System.out.println("stop!");
        break;
      case "blue":
        System.out.println("go");
        break;
      case "yellow":
        System.out.println("caution");
        break;
      default:
        System.out.println("wrong signal");
        break;

while, do while

int i = 0;
    while (i < 10){
      System.out.println(i);
      i++;
    } 
int i = 0;
    do {
      System.out.println(i);
      i++;
    } while (i < 10);

for

for(int i = 0; i < 10; i++){
        if (i == 5){
          break;
        }
        System.out.println(i);
      }

array

      int[] sales;
      sales = new int[3];
      sales[0] = 100;
      sales[1] = 200;
      sales[2] = 300;
      sales[1] = 1000;
      System.out.println(sales[1]);
      // int[] sales:
      // sales = new int[](100, 200, 300);

      int[] sales = {100, 200, 300}

要素の操作

int[] sales = {700, 300, 500};

      for (int i = 0; i < sales.length; i++){
        System.out.println(sales[i]);
      }

int[] sales = {700, 300, 500};

      for (int sale : sales){
        System.out.println(sale);
      }

参照型にはメモリ領域のバッチが入ります。文字列の場合は、変更不可となります。

      int[] a = {3, 5, 7};
      int[] b = a;
      b[1] = 8;
      System.out.println(a[1]);
      System.out.println(b[1]);
      String s = "hello";
      String t = s;
      t = "world";

メソッド

public static void sayHi(String name){
    System.out.println("hi!" + name);
  }

  public static void main(String[] args){
    sayHi("jack");
  }

public static String sayHi(String name){
    return "hi!" + name;
  }

  public static void main(String[] args){
    String msg = sayHi("jack");
    System.out.println(msg);
  }

オーバーロード

public static void sayHi(){
    System.out.printl("hi! nobody");
  }

  public static void main(String[] args){
    sayHi("jack"); //引数
    sayHi();
  }

open-java JDK8

開発環境にJDKをインストールします。javaは.classにコンパイルすれば、Linux以外のOS(mac, windows等)のJRE(Java Runtime Environment)/JVM(Java Virtual Machine)で実行することが可能です。Run anywhereの思想です。

http://openjdk.java.net/install/

[vagrant@localhost java]$ sudo yum -y install java-1.8.0-openjdk-devel

ターミナルからのコンパイル方法です。

public class MyApp{

  public static void main(String[] args){

    String msg;
    msg = "Hello Wrold again";
    System.out.println(msg);
  }
}
[vagrant@localhost java]$ javac MyApp.java
[vagrant@localhost java]$ java MyApp
Hello Wrold again

データ型

    char a = 'a';
    int x = 10;
    long y = 5555555555L;
    double d = 23423.344;
    float f = 32.33F;
    boolean flag = true; // false
    // \n \t

演算

// 演算
    int i;
    i = 10 / 3;
    i = 10 % 3;
    int x = 5;
    x++;
    x--;
    int x = 5;
    x = x + 12;
    x += 12;
    String s;
    s = "hello " + "world";

型変換(cast)

    double d = 452323.231;
    int i = (int)d;
    int i = 10;
    double d = i / 4

Android Fragment

Fragmentは、Activity でのユーザー インターフェースの挙動や部位を表すものです。 1 つのアクティビティに複数のフラグメントを組み合わせてマルチペインの UI をビルドしたり、複数のアクティビティでフラグメントを再利用したりできます。

TitlesFragment.java

package self.myfragmentapp;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.widget.ArrayAdapter;


public class TitlesFragment extends ListFragment {

    public TitlesFragment() {}

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);

        setListAdapter(new ArrayAdapter<String>(
                getActivity(),
                android.R.layout.simple_list_item_1,
                News.Titles
        ));
    }
}