java basic

int passengers;
passengers = 0;
passengers = passengers + 5;
passengers = passengers - 3;
passengers = passengers - 1 + 5;
System.out.println(passengers);

int stops;
int fare;
stops = 0;
fare = 0;
stops = stops + 1;
fare = fare + 5;
stops = stops + 1;
fare = fare + 3;
stops = stops + 1;
fare = fare + 7;
Systeml.out.println(stops);
String driver;
driver = "Hamish";
int letters = driver.length();
System.out.println(letters);

driver = driver.toUpperCase();
System.out.println(driver);
String driverFirstName;
driverFirstName = "Hamish";
String driverLastName;
driverLastName = "Blake";
String driverFullName = driverFirstName + " " + driverLastName;
System.out.println(driverFullName);
System.out.println("The bus made $"+fare+" after "+stops+"stops");

data type

int maxInt = 2147483647;
long muchMore = 2147483647*10000000;
double fraction = 99.275;
String fullText = "(b) WWII ended 1945";
char answer = 'b';
char three = '3';
boolean fact = true;
double current = 17;
double rate = 1.5;
double future = current * rate;
System.out.println(future);
int approx = (int) future;
System.out.println(approx);

casting

int x = 5;
int y = 2;
double div = x/y;
System.out.println(div);
double accurate = (double)x/y;
System.out.println(accurate);

average

double maths=97.5;
double english=98;
double science=83.5;
double drama=75;
double music=96;
double sum=maths+english+science+drama+music;
double average=sum/5;
System.out.println(average);

interface

public interface Drawable
{
	void draw();
}

public class House implements Drawable
{
	public void draw(){...}
}
for (Drawable d : elements) { d.draw();}
public interface Moveable
{
	void move(int seconds);
}

public class Car implements Drawable, Moveable

setter and getter

publi class Person
{
	private String name;

	public String getName(){ return name; }
	public void setName(String newName)
	{
		if(newName.length() > 0) { name = newName; }
	}
}

getter はprivate instance field を getできるようにするもの。
setter はpublic (String/double/picture..) getHogeの値をセットするものです。

    public void setDriverName(String newName)
    {
      driverName = newName;
    }

    public String getDriverName()
    {
      return driverName;
    }

static method:staticメソッドはインスタンスではなく「クラスに属するメソッド」のため、インスタンスを作らずに直接呼び出すことができる。

    public Person(String name)
    {
        this.name = name;
        friends = new ArrayList<Person>();
        lastAssignedId++;
        id = lastAssignedId;
    }
public boolean tryToAdd(Person p)
{
    if(passengers.size() + 2 < numberOfSeats && p.getDestination() <= destination);
    {
        passengers.add(p);
        return true;
    }
    else
    {
        return false;
    }
}
public void drive()
{
    location++;
    while (i < passengers.size())
    {
      Person p = passengers.get(i);
      if (p.getDestination() == location)
      {
        passengers.remove(i);
      }
      else
      {
        i++;
      }
    }
}
public void loadPassengers()
{
    for (Person p : people)
    {
      boolean added = false;
      for (int i = 0; !added && i < cars.size(); i++)
      {
        added = cars.get(i).tryToAdd(p);
      }
    }
}
public void driveCars()
{
  while (cars.size() > 0)
  {
    for (int i = 0; i < cars.size(); i++)
    {
      Car c = cars.get(i);
      c.drive();
      if (c.hasArrived())
      {
        cars.remove(i);
      }
      else
      {
        i++;
      }
    }
  }
}

Java class

class look for nouns in the process
methods: verbs
each method is the responsibility of a single class

  private int numberOfPassengers;

    public void addPassenger(int n)
    {
        if (numberOfPassengers + 1 < numberOfSeats)
        {
          numberOfPassengers++;
        }
    }
    public int getPassengerCount()
    {
        return numberOfPassengers;
    }
import java.util.ArrayList;

public class Car
{
    private int numberOfSeats;
    private ArrayList passengers;
    private int numberOfPassengers;


    public Car(int numberOfSeats)
    {
        this.numberOfSeats = numberOfSeats;
        passengers = new ArrayList();
    }

   /**
    *  Adds a passenger to this car, provided that there is space.
    *  @param name the name of the passenger
    */
    public void addPassenger(String name)
    {
        if(getPassengerCount() + 1 < numberOfSeats)
        {
          passengers.add(name);
        }
        
    }

    public int getPassengerCount()
    {
        return passengers.size();
    }

    public String getPassengerList()
    {
        return passengers.toString();
    }
    
}

average pic color

public class Blocks
{
    public static void main(String[] args)
    {
        Picture pic = new Picture("eiffel-tower.jpg");
        int[][] pixels = pic.getGrayLevels();

        
        for (int i = 0; i < pixels.length; i = i + 2)
        {
            for (int j = 0; j < pixels[0].length; j = j + 2)
            {
                int avg = (pixels[i][j] + pixels[i][j+1]
                    + pixels[i+1][j] + pixels[i+1][j+1]) / 4;
                pixels[i][j] = avg;
                pixels[i][j+1] = avg;
                pixels[i+1][j] = avg;
                pixels[i+1][j+1] = avg;                
            }
        }

        pic.draw();
        Picture pic2 = new Picture(pixels);
        pic2.translate(pic.getWidth() + 10, 0);
        pic2.draw();
    }
}

double[] total = new double[numStudents];
for(int i = 0; i < numStudents; i++) { total[i] = totalForStudent(i); } return total; [/java]

swap halves

import java.util.Arrays;

public class SwapHalves
{
    public static void main(String[] args)
    {
        int[] elements = { 1, 4, 9, 7, 3, 2, 5, 11, 0, 9 };

        int j = elements.length / 2;
        for(int i = 0;  i < (elements.length / 2); i++)
        {
            int saved = elements[i];
            elements[i] = elements[j];
            elements[j] = saved;
            j++;
        }
        System.out.println(Arrays.toString(elements));
    }
}

two dimension array

double reg1 = prices[0][1];
for (int i = 0; i < prices.length; i++)
{
	for (j = 0; j < prices[0].length; j++)
	{
		System.out.printf("%10.3f", prices[i][j]);
	}
	System.out.println();
}

Array declaration

String[] words = new String[10];
String[] words = { "yes", "no" };
values[2] = values[1];
values.set(2, values.get(1));

Use hasNextDouble

public HomeworkScores(int maxScores)
    {
        System.out.println("enter socre 0 to quit: ");

        while(userInput.hasNextDouble())
        {
          double nextScore = userInput.nextDouble();
          socres[currentSize] = nextScore;
          currentSize++;
        }
    }
public double sumScores()
    {
        double sum = 0;
        for (double score: scores)
        {
            sum = sum + score; 
        }
        return sum;
    }

output average score

public double averageScore()
    {
        if (currentSize == 0)
        {
          return 0;
        }
        else {
          sumScores() / currentSize;
        }
    }

remove lowest score

public void removeLowest()
{
      double low = LowScore();
      int lowScoreIndex = find(low);
      remove(lowScoreIndex);
}

public void getLowScoreIndex()
{
double lowestScore = scores[0];
int lowestScoreIndex = 0;
for (int i = 1; i < currentSize; i++) { if (scores[i] < lowestScore) { lowestScore = scores[i]; lowestScoreIndex = i; } } return lowestScoreIndex; } [/java]

ArrayList

ArrayList<Color> palette = new ArrayList<Color>();

ArrayElement is simple than array list.

double[] values = new double[10];
double[] moreValues = { 32, 54, 67.5, 29, 35}
double firstValue = values[0];
values[0] = 42;

list

for (int i = 0; i < values.length; i++)
{
	System.out.println(values[i]);
}
for (double value: values)
{
	System.out.println(value);
}

array declare

int[] primes = { 2, 3, 5, 7, 11 };
int[] primes = { 2, 3, 5, 7, 11 };
for (int i = 0; i < 2; i++)
{
	primes[4 - i] = primes[i];
}
values[0] = 10;
values[values.length - 1] = 10;

find portait

import java.util.ArrayList;

public class ListOfPictures
{
    public static void main(String[] args)
    {
        ArrayList<Picture> gallery = new ArrayList<Picture>();
        gallery.add(new Picture("degas1.jpg"));
        gallery.add(new Picture("gaugin1.jpg"));
        gallery.add(new Picture("monet1.jpg"));
        gallery.add(new Picture("monet2.jpg"));
        gallery.add(new Picture("renoir1.jpg"));
        
        // Your code here
        Int count = 0;
        for(Picture pic: gallery)
        {
            if ( pic.getHeight() > pic.getWidth())
            {
                counter++;
            }
        }
        System.out.println("Pictures with portrait orientation: " + count);
    }
}

find match
i = 0
found = false
while not found and i < size if ith element matches found = true else i++ if found, then i is index of of match

import java.util.ArrayList;

public class ListOfPictures
{
    public static void main(String[] args)
    {
        ArrayList gallery = new ArrayList();
        gallery.add(new Picture(“degas1.jpg”));
        gallery.add(new Picture(“gaugin1.jpg”));
        gallery.add(new Picture(“monet1.jpg”));
        gallery.add(new Picture(“monet2.jpg”));
        gallery.add(new Picture(“renoir1.jpg”));
        
        int i = 0;
        boolean found = false;
        
        while (!found && i < gallery.size())
        {
            Picture pic = gallery.get(i)
            if(pic.getHeight() > pic.getWidth())
            {
                found = true;
            }
            else
            {
              i++;
            }
        }
        
        if (found)
        {
            gallery.get(i).draw();
        }
    }
}

arrya list

import java.util.ArrayList;

public class ListOfPictures
{
    public static void main(String[] args)
    {
        ArrayList<Picture> gallery = new ArrayList<Picture>();
        gallery.add(new Picture("degas1.jpg"));
        gallery.add(new Picture("gaugin1.jpg"));
        gallery.add(new Picture("monet1.jpg"));
        gallery.add(new Picture("monet2.jpg"));
        gallery.add(new Picture("renoir1.jpg"));

        ArrayList<Picture> matches = new ArrayList<Picture>();
        for(Picture pic: gallery)
        {
            if(pic.getHeight() > pic.getWidth())
            {
                matches.add(pic);
            }
        }

        int rightmostX = 0;
        for (Picture pic : matches)
        {
            pic.translate(rightmostX + 10, 0);
            rightmostX = pic.getMaxX();
            pic.draw();
        }
    }
}
    public String getFriends(String separator)
    {
        String separatedFriends = "";
        for (int i = 0; i < friends.size(); i++)
        {
          if (i > 0)
          {
            separatedFriends = separatedFriends + separator + friend.get(i);
          }
          else 
          {
            separatedFriends = separatedFriends + friend.get(i);
          }
        }
    }
public void unfriend(Person nonFriend)
{
   int nonFriendIndex = find(nonFriend);
   if (nonFriendIndex != -1)
   {
     friends.remove(nonFriendIndex);
   }   
}

use find

public void talkTo(Person person)
{
    int oldIndex = find(person);
    if(oldIndex != -1)
    {
      friends.remove(oldIndex);
      friends.add(0, person);
    }
}