1. Шинэ прожест үүсгэнэ.
2. Add Local Database - Database.sdf
3. Add new Table
4. Add static class
SQLFunctions static class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlServerCe;
using System.Data;
using System.Windows.Forms;
namespace LocalDatabaseTutorial
{
static class SQLFunctions
{
static private SqlCeConnection connection = new SqlCeConnection(@"Data Source=|DataDirectory|\Database.sdf");
static public void Refresh(DataGridView dgv)
{
try
{
connection.Open();
SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter("select * from [Table]", connection);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dgv.DataSource = dataTable;
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}
static public void Insert(string username)
{
try
{
connection.Open();
SqlCeCommand commandInsert = new SqlCeCommand("insert into[Table] values(@username)", connection);
commandInsert.Parameters.Add("@username", username);
commandInsert.ExecuteNonQuery();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}
static public void Delete(string username)
{
try
{
connection.Open();
SqlCeCommand commandInsert = new SqlCeCommand("delete from [Table] where username = @username", connection);
commandInsert.Parameters.Add("@username", username);
commandInsert.ExecuteNonQuery();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}
static public void Update(string oldname, string newname)
{
try
{
connection.Open();
SqlCeCommand commandInsert = new SqlCeCommand("update [Table] set username = @newname where username = @oldname", connection);
commandInsert.Parameters.Add("@newname", newname);
commandInsert.Parameters.Add("@oldname", oldname);
commandInsert.ExecuteNonQuery();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}
}
}
Form1 class:
private void Form1_Load(object sender, EventArgs e)
{
SQLFunctions.Refresh(this.dataGridView1);
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
SQLFunctions.Insert(textBox1.Text);
SQLFunctions.Refresh(this.dataGridView1);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox2.Text != "")
{
SQLFunctions.Delete(textBox2.Text);
SQLFunctions.Refresh(this.dataGridView1);
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox3.Text != "" && textBox4.Text != "")
{
SQLFunctions.Update(textBox3.Text, textBox4.Text);
SQLFunctions.Refresh(this.dataGridView1);
}
}
}
}
Result:
Sunday, January 10, 2016
Monday, January 4, 2016
Java File Example
1: How to reaad text file
public class javareadfile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String line = null;
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
2: How to read and write text files
public class myFile {
public static void main(String[] args) throws IOException{
// write to text file
ArrayList<String> lines = new ArrayList<String>();
lines.add("Сайн уу? world");
lines.add("This is дараагийн мөр");
Path pathtoFile = Paths.get("file.txt");
Files.write(pathtoFile, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
// read from text file
List<String> line2 = Files.readAllLines(pathtoFile, StandardCharsets.UTF_8);
for(String l : line2)
System.out.println(l);
}
}
3: How to copy, move and delete files in Java
public static void main(String[] args) throws IOException{
// write to text file
ArrayList<String> lines = new ArrayList<String>();
lines.add("Сайн уу? world");
lines.add("This is дараагийн мөр");
Path pathtoFile = Paths.get("file.txt");
Files.write(pathtoFile, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
// read from text file
List<String> line2 = Files.readAllLines(pathtoFile, StandardCharsets.UTF_8);
for(String l : line2)
System.out.println(l);
// file exists?
System.out.println("file exists?: " + Files.exists(pathtoFile));
Path pathtoFile2 = Paths.get("file2.txt");
// move file
Files.move(pathtoFile, pathtoFile2, StandardCopyOption.REPLACE_EXISTING);
System.out.println("file exists?: " + Files.exists(pathtoFile));
// copy file
Files.copy(pathtoFile2, pathtoFile);
// delete file
Files.delete(pathtoFile);
Files.delete(pathtoFile2);
}
}
4: How to get free, available and total disk space in Java
public class javadisk {
public static void main(String[] args) throws IOException{
FileStore fs = Files.getFileStore(Paths.get("c:/"));
long totalSpaceInBytes = fs.getTotalSpace();
long freeSpaceInBytes = fs.getUsableSpace();
long usedSpaceInBytes = totalSpaceInBytes - freeSpaceInBytes;
System.out.println("total space in GB: " + (totalSpaceInBytes/1024/1024/1024));
System.out.println("free space in GB: " + (freeSpaceInBytes/1024/1024/1024));
System.out.println("used space in GB: " + (usedSpaceInBytes/1024/1024/1024));
}
}
public class javareadfile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String line = null;
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
2: How to read and write text files
public class myFile {
public static void main(String[] args) throws IOException{
// write to text file
ArrayList<String> lines = new ArrayList<String>();
lines.add("Сайн уу? world");
lines.add("This is дараагийн мөр");
Path pathtoFile = Paths.get("file.txt");
Files.write(pathtoFile, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
// read from text file
List<String> line2 = Files.readAllLines(pathtoFile, StandardCharsets.UTF_8);
for(String l : line2)
System.out.println(l);
}
}
3: How to copy, move and delete files in Java
public static void main(String[] args) throws IOException{
// write to text file
ArrayList<String> lines = new ArrayList<String>();
lines.add("Сайн уу? world");
lines.add("This is дараагийн мөр");
Path pathtoFile = Paths.get("file.txt");
Files.write(pathtoFile, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
// read from text file
List<String> line2 = Files.readAllLines(pathtoFile, StandardCharsets.UTF_8);
for(String l : line2)
System.out.println(l);
// file exists?
System.out.println("file exists?: " + Files.exists(pathtoFile));
Path pathtoFile2 = Paths.get("file2.txt");
// move file
Files.move(pathtoFile, pathtoFile2, StandardCopyOption.REPLACE_EXISTING);
System.out.println("file exists?: " + Files.exists(pathtoFile));
// copy file
Files.copy(pathtoFile2, pathtoFile);
// delete file
Files.delete(pathtoFile);
Files.delete(pathtoFile2);
}
}
4: How to get free, available and total disk space in Java
public class javadisk {
public static void main(String[] args) throws IOException{
FileStore fs = Files.getFileStore(Paths.get("c:/"));
long totalSpaceInBytes = fs.getTotalSpace();
long freeSpaceInBytes = fs.getUsableSpace();
long usedSpaceInBytes = totalSpaceInBytes - freeSpaceInBytes;
System.out.println("total space in GB: " + (totalSpaceInBytes/1024/1024/1024));
System.out.println("free space in GB: " + (freeSpaceInBytes/1024/1024/1024));
System.out.println("used space in GB: " + (usedSpaceInBytes/1024/1024/1024));
}
}
Java Thread Example 2
Using Thread
Concurrency and simple thread synchronization
/ Тред зэрэг ачаалах /
/ Тред зэрэг ачаалах /
Энгийн хэвлэх функц:
public synchronized void doStuff(String threadname){
jTextArea1.append(threadname + " access started...\n");
jTextArea1.append("Doing stuff...\n");
jTextArea1.append(threadname + " access finished...\n");
}
Товчны дарах үзэгдэл дээр бичих:
for(int i = 0; i<10; i++){
Thread t1 = new Thread(){
public void run() { doStuff("thread1"); } };
Thread t2 = new Thread(){
public void run(){ doStuff("thread2"); } };
t1.start();
t2.start();
}
Үр дүн:
synchronized ашиглаагүй:
synchronized ашиглаагүй:
Sunday, January 3, 2016
Java Thread Example 1
1: How to Create Threads in Java by Extending Thread Class
class MyClass extends Thread{
public void run(){
for(int i = 0; i<10; i++)
System.out.println(Thread.currentThread().getId() + " Value: " + i);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class JavaThreadExample {
public static void main(String[] args) {
// TODO code application logic here
MyClass mc = new MyClass();
mc.start();
MyClass mc1 = new MyClass();
mc1.start();
}
}
2: Creating Java Threads by implementing Runnable Interface
class MyClass implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyClass());
Thread t2 = new Thread(new MyClass());
t1.start();
t2.start();
// How to create thread inside main class
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
t3.start();
}
}
3: Java Thread.join() Method and Synchronized Method
public class MyThreadJoin {
private static int count = 0;
public synchronized static void counter() {
count++;
}
public static void main(String[] args) {
try {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10000; i++) {
counter();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10000; i++) {
counter();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Value:" + count);
} catch (InterruptedException ex) {
Logger.getLogger(MyThreadJoin.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class MyClass extends Thread{
public void run(){
for(int i = 0; i<10; i++)
System.out.println(Thread.currentThread().getId() + " Value: " + i);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class JavaThreadExample {
public static void main(String[] args) {
// TODO code application logic here
MyClass mc = new MyClass();
mc.start();
MyClass mc1 = new MyClass();
mc1.start();
}
}
2: Creating Java Threads by implementing Runnable Interface
class MyClass implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyClass());
Thread t2 = new Thread(new MyClass());
t1.start();
t2.start();
// How to create thread inside main class
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
t3.start();
}
}
3: Java Thread.join() Method and Synchronized Method
public class MyThreadJoin {
private static int count = 0;
public synchronized static void counter() {
count++;
}
public static void main(String[] args) {
try {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10000; i++) {
counter();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10000; i++) {
counter();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Value:" + count);
} catch (InterruptedException ex) {
Logger.getLogger(MyThreadJoin.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Java GUI Basic 3
EXAMPLE 1:
private ArrayList<ArrayList<String>> md = new ArrayList<ArrayList<String>>();
private int trust;
public HybridMD(int trust){
this.trust = trust;
}
public void addRow(ArrayList<String> row){
if(row.size() == trust) md.add(row);
else throw new IllegalArgumentException("Row ist't trusted. Should contain values: " + trust);
}
public String get(int row, int column){
return md.get(row).get(column);
}
public int getRowCount(){
return md.size();
}
public int getColumnCount(){
return trust;
}
}
NEWJFRAME
HybridMD md = new HybridMD(3);
Button:
String name = jTextField1.getText();
String surname = jTextField2.getText();
String age = jTextField3.getText();
ArrayList<String> row = new ArrayList<String>();
row.add(name);
row.add(surname);
row.add(age);
// error Row ist't trusted. Should contain values: 3
// row.add(age);
md.addRow(row);
jTextArea1.setText("");
for(int i = 0; i<md.getRowCount(); i++){
for(int j = 0; j<md.getColumnCount(); j++)
jTextArea1.append(md.get(i, j) + "\t");
jTextArea1.append("\n");
}
Result:

EXAMPLE 2:
Using String Tokenizer Example:
Гараас оруулсан текстийн таслалын тоог арилгаж хэвлэх:
Creating Secure Dynamic Multi-Dimensional Array
public class HybridMD {private ArrayList<ArrayList<String>> md = new ArrayList<ArrayList<String>>();
private int trust;
public HybridMD(int trust){
this.trust = trust;
}
public void addRow(ArrayList<String> row){
if(row.size() == trust) md.add(row);
else throw new IllegalArgumentException("Row ist't trusted. Should contain values: " + trust);
}
public String get(int row, int column){
return md.get(row).get(column);
}
public int getRowCount(){
return md.size();
}
public int getColumnCount(){
return trust;
}
}
NEWJFRAME
HybridMD md = new HybridMD(3);
Button:
String name = jTextField1.getText();
String surname = jTextField2.getText();
String age = jTextField3.getText();
ArrayList<String> row = new ArrayList<String>();
row.add(name);
row.add(surname);
row.add(age);
// error Row ist't trusted. Should contain values: 3
// row.add(age);
md.addRow(row);
jTextArea1.setText("");
for(int i = 0; i<md.getRowCount(); i++){
for(int j = 0; j<md.getColumnCount(); j++)
jTextArea1.append(md.get(i, j) + "\t");
jTextArea1.append("\n");
Result:

EXAMPLE 2:
Using String Tokenizer Example:
Гараас оруулсан текстийн таслалын тоог арилгаж хэвлэх:
Товчны дарах
үзэгдэл дээр:
String inp =
JOptionPane.showInputDialog("Enter keywords separated by comma:");
StringTokenizer st = new StringTokenizer(inp, ",");
JOptionPane.showMessageDialog(this, st.countTokens());
while(st.hasMoreTokens()){
jTextArea1.append(st.nextToken().trim() + " "); }
jTextArea1.append("\n");
Үр дүн:
Үр дүн:
Java GUI Basic 2
Example 1:
Өнөөдрийн пост бичлэгээр netbeans ашиглан хялбархан програм хийх талаар оруулъя. Уг програм нь JFrame form ашиглан JTable-д өгөгдөл нэмэх, засах, устгах жишээ юм.
Өнөөдрийн пост бичлэгээр netbeans ашиглан хялбархан програм хийх талаар оруулъя. Уг програм нь JFrame form ашиглан JTable-д өгөгдөл нэмэх, засах, устгах жишээ юм.
1. Эхлээд дараах кодыг бичъе: / DemoTable бол классын нэр юм. /
String[] data = new String[2];
DefaultTableModel model;
public
DemoTable() {
initComponents();
model = new DefaultTableModel();
model.addColumn("Name");
model.addColumn("Team");
}
2. Нэмэх товчны код:
data[0] = JOptionPane.showInputDialog("Enter
name:");
data[1] =
JOptionPane.showInputDialog("Enter team:");
model.addRow(new Object[]{data[0],
data[1]});
jTable1.setModel(model);
3.
Засах товчны код:
data[0] =
JOptionPane.showInputDialog("Change name:");
data[1] =
JOptionPane.showInputDialog("Change team:");
jTable1.getModel().setValueAt(data[0],
jTable1.getSelectedRow(), 0);
jTable1.getModel().setValueAt(data[1],
jTable1.getSelectedRow(), 1);
4. Устгах товчны код:
//
//
//
//
//
//
Одоо дараах
програмыг өөр хэлбэрээр / массив ашиглан динамик шинжтэй / дахин зохиоё.
1.
Дараах хоёр хувьсагчийг гишүүн хувьсагчаар
нэмлээ.
Object[][] data = null;
String[] columnNames = new String[2];
Object[][] data = null;
String[] columnNames = new String[2];
2.
Хүснэгт
үүсгэх товчны код: / instantiate table button /
columnNames[0] = "Name";
columnNames[1] = "Team";
data = new Object[1][2];
data[0][0] = JOptionPane.showInputDialog("Enter name:");
data[0][1] = JOptionPane.showInputDialog("Enter team:");
jTable1.setModel(new DefaultTableModel(data, columnNames));
columnNames[0] = "Name";
columnNames[1] = "Team";
data = new Object[1][2];
data[0][0] = JOptionPane.showInputDialog("Enter name:");
data[0][1] = JOptionPane.showInputDialog("Enter team:");
jTable1.setModel(new DefaultTableModel(data, columnNames));
3.
Мөр
нэмэх товчны код:
Object[][] temp = new Object[data.length+1][2];
for( int i = 0; i<data.length; i++){
Object[][] temp = new Object[data.length+1][2];
for( int i = 0; i<data.length; i++){
temp[i][0] = data[i][0];
temp[i][1] = data[i][1];
}
temp[data.length][0] = JOptionPane.showInputDialog("Enter name:");
temp[data.length][0] = JOptionPane.showInputDialog("Enter name:");
temp[data.length][1] =
JOptionPane.showInputDialog("Enter team:");
data = temp;
jTable1.setModel(new
DefaultTableModel(temp, columnNames));
4.
Мөр
засах товчны код:
if(jTable1.getSelectedRow()>=0){
if(jTable1.getSelectedRow()>=0){
String name = JOptionPane.showInputDialog("Change
name:");
String team =
JOptionPane.showInputDialog("Change team:");
data[jTable1.getSelectedRow()][0] = name;
data[jTable1.getSelectedRow()][1] = team;
jTable1.setModel(new
DefaultTableModel(data, columnNames));
//
jTable1.getModel().setValueAt(name, jTable1.getSelectedRow(), 0);
//
jTable1.getModel().setValueAt(team , jTable1.getSelectedRow(), 1);
}
else {
JOptionPane.showMessageDialog(this, "You must select row!");
}
5.
Мөр
устгах:
int pos = jTable1.getSelectedRow();
int pos = jTable1.getSelectedRow();
Object[][] temp = new
Object[data.length - 1][2];
for(int i = 0; i<pos; i++)
{
temp[i][0] = data[i][0];
temp[i][1] = data[i][1];
}
for( int i = pos+1;
i<data.length; i++){
temp[i-1][0] =
data[i][0];
temp[i-1][1] =
data[i][1];
}
data = temp;
jTable1.setModel(new
DefaultTableModel(data, columnNames));
Example 2:
Using JMenubar:
Using JMenubar:
Save Menu Click:
JOptionPane.showMessageDialog(this, "Saved!");
JMenuItem itm
= new JMenuItem("Exit");
itm.addActionListener(new ActionListener() {
@Override
public
void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Tut30.this, "Exit!");
System.exit(0);
}
});
jMenu1.add(itm);
Using
MouseClickListener:
Button -> MouseReleased
if(evt.getButton() == MouseEvent.BUTTON1)
if(evt.getButton() == MouseEvent.BUTTON1)
JOptionPane.showMessageDialog(this, "Left Clicked!");
else if
(evt.getButton() == MouseEvent.BUTTON2)
JOptionPane.showMessageDialog(this, "Middle Clicked!");
else if
(evt.getButton() == MouseEvent.BUTTON3)
JOptionPane.showMessageDialog(this, "Right Clicked!");
Using JPopupMenu:
private void
jButton1MouseReleased(java.awt.event.MouseEvent evt) {
if
(evt.getButton() == MouseEvent.BUTTON3)
{
jPopupMenu1.removeAll();
JMenuItem
itm = new JMenuItem("Copy");
itm.addActionListener(new ActionListener() {
@Override
public
void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Tut30.this,
"Copied!");
}
});
jPopupMenu1.add(itm);
jPopupMenu1.show(jButton1, evt.getX(), evt.getY());
}
}
Monday, December 21, 2015
Java Basic 2
1. ArrayList
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> list1 = new ArrayList<String>();
list1.add("Zoloo");
list1.add("Bataa");
list1.add("Miigaa");
list1.add("Hurlee");
String input = JOptionPane.showInputDialog("Please enter name:");
list1.add(input);
String msg="";
for(String s: list1) msg+=s + "\n";
JOptionPane.showMessageDialog(null, msg);
}
2. Reading and writing files
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String[] array = new String[]{"Carmelo Anthony",
"Lebron James", "Kevin Durant",
"Paul Pierce", "Paul George" };
BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"));
for(String s : array)
bw.write(s + "\n");
bw.close();
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String s = "";
String msg= "";
while((s = br.readLine())!=null)
msg += s + "\n";
br.close();
JOptionPane.showMessageDialog(null, msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
3. Map and HashMap
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("Carmelo", 15);
map.put("Lebron", 23);
map.put("Kobe", 24);
map.put("Duncan", 21);
map.put("Dirk", 41);
int markofKobe = map.get("Kobe");
System.out.println("Marks of Kobe :" + markofKobe);
int markofDuncan = map.get("Duncan");
System.out.println("Marks of Duncan :" + markofDuncan);
map.remove("Kobe");
if(map.containsKey("Kobe"))
System.out.println("Kobe exists!");
else System.out.println("Kobe is gone!");
for(Entry<String, Integer> s : map.entrySet())
System.out.println("Key: " + s.getKey() + " Value: " + s.getValue());
}
4. Interface Example
Interface:
public interface Person {
public String whoRyou();
public String getName();
}
Class 2:
public class GoodPerson implements Person{
String name="";
public GoodPerson(String n) {
// TODO Auto-generated constructor stub
name = n;
}
@Override
public String whoRyou() {
// TODO Auto-generated method stub
return "Good";
}
@Override
public String getName() {
// TODO Auto-generated method stub
return name;
}
}
Class 1:
public class BadPerson implements Person{
String name="";
public BadPerson(String n) {
// TODO Auto-generated constructor stub
name = n;
}
@Override
public String whoRyou() {
// TODO Auto-generated method stub
return "Bad";
}
@Override
public String getName() {
// TODO Auto-generated method stub
return name;
}
}
Main Class:
public class Killer {
public static void main(String[] args){
GoodPerson gp1 = new GoodPerson("Percy");
GoodPerson gp2 = new GoodPerson("Harry");
BadPerson bp1 = new BadPerson("Black");
BadPerson bp2 = new BadPerson("Reddy");
kill(gp1);
kill(gp2);
kill(bp1);
kill(bp2);
}
public static void kill(Person p){
if(p instanceof BadPerson)
System.out.println("Killed " + p.getName() + ". Feels good to kill a bad person.");
else if(p instanceof GoodPerson)
System.out.println("Killed " + p.getName() + ". Cannot kill a good person.");
}
}
5. Abstraction
public abstract class Shape {
String colorname = "";
int vertices = 0;
public abstract void Draw();
public String getColorname() {
return colorname;
}
public void setColorname(String colorname) {
this.colorname = colorname;
}
public int getVertices() {
return vertices;
}
public void setVertices(int vertices) {
this.vertices = vertices;
}
}
public class Circle extends Shape{
public Circle(String n){
super.setColorname(n);
super.setVertices(0);
System.out.println("Circle has been created!");
}
@Override
public void Draw() {
// TODO Auto-generated method stub
System.out.println("Circle has been drawn");
}
}
main Class:
public static void main(String[] args){
Circle c1= new Circle("Black");
Circle c2 = new Circle("Red");
Shape c3 = new Circle("Blue");
c1.Draw();
c2.Draw();
c3.Draw();
}
https://www.youtube.com/playlist?list=PL8F0C07390BAC102A
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> list1 = new ArrayList<String>();
list1.add("Zoloo");
list1.add("Bataa");
list1.add("Miigaa");
list1.add("Hurlee");
String input = JOptionPane.showInputDialog("Please enter name:");
list1.add(input);
String msg="";
for(String s: list1) msg+=s + "\n";
JOptionPane.showMessageDialog(null, msg);
}
2. Reading and writing files
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String[] array = new String[]{"Carmelo Anthony",
"Lebron James", "Kevin Durant",
"Paul Pierce", "Paul George" };
BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"));
for(String s : array)
bw.write(s + "\n");
bw.close();
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String s = "";
String msg= "";
while((s = br.readLine())!=null)
msg += s + "\n";
br.close();
JOptionPane.showMessageDialog(null, msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
3. Map and HashMap
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("Carmelo", 15);
map.put("Lebron", 23);
map.put("Kobe", 24);
map.put("Duncan", 21);
map.put("Dirk", 41);
int markofKobe = map.get("Kobe");
System.out.println("Marks of Kobe :" + markofKobe);
int markofDuncan = map.get("Duncan");
System.out.println("Marks of Duncan :" + markofDuncan);
map.remove("Kobe");
if(map.containsKey("Kobe"))
System.out.println("Kobe exists!");
else System.out.println("Kobe is gone!");
for(Entry<String, Integer> s : map.entrySet())
System.out.println("Key: " + s.getKey() + " Value: " + s.getValue());
}
4. Interface Example
Interface:
public interface Person {
public String whoRyou();
public String getName();
}
Class 2:
public class GoodPerson implements Person{
String name="";
public GoodPerson(String n) {
// TODO Auto-generated constructor stub
name = n;
}
@Override
public String whoRyou() {
// TODO Auto-generated method stub
return "Good";
}
@Override
public String getName() {
// TODO Auto-generated method stub
return name;
}
}
Class 1:
public class BadPerson implements Person{
String name="";
public BadPerson(String n) {
// TODO Auto-generated constructor stub
name = n;
}
@Override
public String whoRyou() {
// TODO Auto-generated method stub
return "Bad";
}
@Override
public String getName() {
// TODO Auto-generated method stub
return name;
}
}
Main Class:
public class Killer {
public static void main(String[] args){
GoodPerson gp1 = new GoodPerson("Percy");
GoodPerson gp2 = new GoodPerson("Harry");
BadPerson bp1 = new BadPerson("Black");
BadPerson bp2 = new BadPerson("Reddy");
kill(gp1);
kill(gp2);
kill(bp1);
kill(bp2);
}
public static void kill(Person p){
if(p instanceof BadPerson)
System.out.println("Killed " + p.getName() + ". Feels good to kill a bad person.");
else if(p instanceof GoodPerson)
System.out.println("Killed " + p.getName() + ". Cannot kill a good person.");
}
}
5. Abstraction
public abstract class Shape {
String colorname = "";
int vertices = 0;
public abstract void Draw();
public String getColorname() {
return colorname;
}
public void setColorname(String colorname) {
this.colorname = colorname;
}
public int getVertices() {
return vertices;
}
public void setVertices(int vertices) {
this.vertices = vertices;
}
}
public class Circle extends Shape{
public Circle(String n){
super.setColorname(n);
super.setVertices(0);
System.out.println("Circle has been created!");
}
@Override
public void Draw() {
// TODO Auto-generated method stub
System.out.println("Circle has been drawn");
}
}
main Class:
public static void main(String[] args){
Circle c1= new Circle("Black");
Circle c2 = new Circle("Red");
Shape c3 = new Circle("Blue");
c1.Draw();
c2.Draw();
c3.Draw();
}
https://www.youtube.com/playlist?list=PL8F0C07390BAC102A
Subscribe to:
Posts (Atom)






