หัดเขียนโปรแกรม ภาษาจาวา

Java basic | Java OOP | โครงสร้างข้อมูล | โจทย์ ACM



Showing posts with label Java basic. Show all posts
Showing posts with label Java basic. Show all posts

Convert base Numbers การแปลงเลขฐาน

ในบทความนี้จะมีการแปลงเลขฐาน 6 แบบด้วยกัน คือ
  1. ฐาน 10 เป็น ฐาน 2
  2. ฐาน 10 เป็น ฐาน 16
  3. ฐาน 2 เป็น ฐาน 10
  4. ฐาน 2 เป็น ฐาน 16
  5. ฐาน 2 เป็น ฐาน 16
  6. ฐาน 10 เป็น ฐาน 16
นอกจาก 6 ข้อนี้ยังมีมากกว่านี้นะครับส่วนสูตรในการคำนวณผมจะไม่ขอกล่าวถึงนะครับเน้นเอาไปใช้งานอย่างเดียวฮ่าๆ\

java - How to check if a string is a number เช็คว่าเป็นตัวเลขหรือตัวอักษร หรือไม่


Input  



142Sp94r09y+j0i50*5i198++07m6743


จาก input ให้ดึงเอาเฉพาะตัวเลขมาแสดง.

Output

14294090505198076743


Sample Code

 
      String intput = "142Sp94r09y+j0i50*5i198++07m6743";                   
       String number ="";
             for(int i = 0 ; i < intput.length() ;i++){
                   char c = intput.charAt(i);
                 if(Character.isDigit(c)){
                    number += c;
                 }
             }
         System.out.println("output : " +number);

ตัวอย่างการใช้งาน
เช่น เอาไปแก้ปัญหาในโจทย์ Opt String(http://goo.gl/YlfFyX)

เนื้อหาที่เกียวข้อง / ควรศึกษาเพิ่มเติมถ้าไม่เข้าใจ 

Java ArrayList Object example


ArrayList เป็นอีกทางเลือกหนึ่งที่เราไม่ทราบ ขนาด Array ที่แน่นอน และช่วยให้เราสามารถเก็บข้อมูลเป็น object ได้ 
Method ของ ArrayList ที่จะใช้
  • add()    : สำหรับเพิ่มข้อมูลให้ลงใน ArrayList
  • get()     : สำหรับดึงค่าใน ArrayList
  • set()     : สำหรับเปลี่ยนแปลงตำแหน่งข้อมูลใน ArrayList

วันนี้จะเราจะทำโจทย์ที่นำ ArrayList มาประยุกต์ใช้งานกัน
โจทย์ คือ จะให้ไฟล์ students.in ภายในไฟล์จะเป็นข้อมูลนักศึกษามาโดยมี รหัสนักศึกษา ชื่อนักศึกษา คะแนนที่ได้ อยากให้เรียงลำดับคะแนน นักศึกษาจาก มากไปหาน้อย
Student_Id,Student_name,Student_score
53001,Theerapong Hunghuan,50
53002,Vatcharin Phoya,35
53003,Prapakorn Moonnoi,38
53004,Agkasit Tontan,56
53005,Wattanakron Apichit,35
53006,Tanachai Sunarug,68
53007,Chanwit Phuwadkien,66
53008,Wkt Rescue,55
53009,Scream Srisawet,73
53010,Tanachai Sunarug,33
53011,Leng ManDer,46
53012,CupidNoy Sky InNocence,67
(Downloadไฟล์ students.in จาก http://goo.gl/AghNCr )
ตัวอย่างผลลัพธ์ของโปรแกรม
ขั้นตอนในการแก้ปัญหา 
  1. ให้อ่านข้อมูลจากไฟล์ students.in  เข้ามาเก็บใน Arraylist โดยสร้างคลาส Students สำหรับเก็บค่า studentId ,studentName,studentGate หรือจะมองเป็นหนึ่ง object แล้วมา add ใน Arraylist
  2. นำข้อมูลนักศึกษาทั้งหมดมาเรียงจากมากไปหาน้อย การเรียงข้อมูลจากมากไปหาน้อย โดยดึงเฉพาะ sutudentScore มาเปรียบเทียบ แล้วใช้ Method set ของ ArrayList ในการสลับตำแหน่ง
ขั้นตอนที่ 1
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class ArrayListExample {
 private static String studentId;
 private static String studentName;
 private static int studentScore;

 public static void main(String[] args) throws IOException {
  BufferedReader readfile = new BufferedReader(new FileReader(new File(
    "C:/students.in")));
  String tmp;

  readfile.readLine();// ไม่เก็บ Student_Id,Student_name,Student_score
  ArrayList studentList = new ArrayList();
  // เก็บข้อมูลนักศึกษาให้ครบ
  while ((tmp = readfile.readLine()) != null) {
   String[] arr = tmp.split(",");
   studentId = arr[0];
   studentName = arr[1];
   studentScore = Integer.parseInt(arr[2]);
   // add ข้อมูลนักศึกษา studentId,studentName,studentGate ใส่
   // studentList
   studentList.add(new students(studentId, studentName, studentScore));
  }
  // show ข้อมูล ดู
  for (int i = 0; i < studentList.size(); i++) {
   System.out.println(studentList.get(i).studentId + " "
     + studentList.get(i).studentName + "   "
     + studentList.get(i).studentScore);
  }

 }
}

// สร้าง class students เพี่อเก็บ studentId ,studentName,studentGate
static class students {
 public String studentId;
 public String studentName;
 public int studentScore;

 students(String studentId, String studentName, int studentScore) {
  this.studentId = studentId;
  this.studentName = studentName;
  this.studentScore = studentScore;
 }
}
รันดู

ขั้นตอนทึ่ 2  ใช้การเรียงข้อมูลแบบ Bubble Sort ในการเรียงข้อมูล

 // Method สำหรับเรืยง ลำดับ score จาก มาก ->น้อย
 static ArrayList sort(ArrayList List) {
  students tmp;
  for (int i = 1; i < List.size(); i++) {
   for (int j = 0; j < List.size() - i; j++) {
    if (List.get(j).studentScore < List.get(j + 1).studentScore) {
     tmp = List.get(j);
     List.set(j, List.get(j + 1));
     List.set(j + 1, tmp);
    }
   }
  }
  return List;
 }
โค้ดทั้งหมด

เนื้อหาที่เกียวข้อง / ควรศึกษาเพิ่มเติมถ้าไม่เข้าใจ 

การสร้างโปรเจกใน NetBeans IDE



          สำหรับคนที่หัดเขียน Java เป็นครังแรกนะครับ วันนี้เรามาพาสร้างโปรเจกใน NetBeans IDE ไม่พูดร่ำทำเพลง มาเริ่มกันเลย  ขั้นแรกก็ new project 


              พอคลิก New Project ก็จะแสดงหน้าต่างให้เรา ตั้งชื่อโปรเจก ในที่นี้ ตั้งชื่อเป็น InceptionWatchQ
ตั้งชื่อโปรเจกตามรูป หรือตั้งตามใจเลยก็ได้ครับ
            จากรูปผมเอา Create Main Class เนื่องจาก ผมชอบพิมพ์เอง เสร็จแล้วก็กด finish ก็จะได้หน้าต่างนี้ขึ้นมา



ให้เราทำการ คลิกขวาที่ default package แล้วก็ new > Java Class



พอได้แล้วก็ ตั้งชื่อให้เหมือนกันกับชื้อโปรเจก ดังรูป แล้วก็กด finish

พอกดเสร็จ มันก็จะเจนค่าให้ดังรูป


ทีนี้ก็ได้ Class InceptionWatch มาแล้ว ซึ่งตอนนี้ยังไม่สามารถ run โปรเจกได้เนืองจากยังไม่มี Mathode main ให้เราพิมพ์ 

                 public static void main (String [] args){

                 }

[Java]การใช้ while loop


         คำสั่ง while loop เป็นคำสั่งสำหรับวนลูปอีกแบบจะมีเงื่อนไขการทำงานอยู่ว่า ถ้าเงื่อนไขเป็นจริงทำงานต่อไปเรื่อยๆและจะออกจากลูปเมื่อเงื่อนไขเป็นเท็จ


           /**
            * โปรแกรมนับเลข 1 - 10
            * @author http://javaagkasit.blogspot.com
            */
                public class whileloop {
                       public static void main(String[] args) {
                              int count = 1 ;
                         
                        while (true) {    
                                 if(count <= 10){
                                       System.out.println(count++);
                                }else{
                                       break;
                                }
                         }
                        }
                 }
          จากโค้ดด้านบนเป็นโปรแกรมนับเลข 1 ถึง 10 การทำงานก็คือว่า ในลูป while จะวนไปเรื่อยๆภายใน{}ของ while  ถ้า count น้อยกว่าหรือเท่า 10 ก็จะปริํนค่า count ออกมาพร้อมทั้งเพิ่มค่า count ขึ้นที่ละหนึ่ง เมื่อใดที่ค่า count มีค่าไม่ได้อยู่ในเงื่อนไข ก็จะออกจากลูป while
           ในการใช้คำสั้งวนใดๆก็ตาม จะมี 2 คำสั้งที่เกี่ยวข้อ คือ break กับ continue การใช้งานก็ง่ายนิดเดียว  break คือ ออกจากลูป ส่วน continue คือทำงานต่อไป ซึ่งการใช้งานจริงส่วนใหญ่ก็เป็น break ซะมากกว่า continue 

ศึกษาเพิ่มได้ที่
         - การใช้ if else http://javaagkasit.blogspot.com/2012/08/if-else.html
         - การสร้างโปรเจกใน NetBeans IDEhttp://javaagkasit.blogspot.com/2012/09/netbeans-ide.html
         - Class และ object คืออะไร

[Java]การใช้ for-each



             นอกเหนือจากการใช้ For loop แบบมี ค่าเริ่ม;เงื่อนไข;เพิ่มค่า ยังมีการวนลูปอีกแบบหนึ่งในภาษา Java คือ for - each  loop โดยมีรูปแบบคำสั่งดังนี้

                         for(declaration : expression) {
                               statement
                         }

                - declaration : เป็นการประกาศตัวแปรทั่วไป เช่น String color
                - expression : จะเป็นอาร์เรย์ (array) หรือ Object
                - statement : อาจจะเป็น การคำนวน การแสดงค่า(print)

              แล้วมันต่างจาก for ธรรมดาอย่างไร ข้อดีของ for-each คือกรณีที่เราต้องการโชว์ข้อมูลใน Array ทั้งหมด for -each จะทำได้ง่ายกว่า อาจจะมองภาพยังไม่ออกลองดูตัวอย่างโค้ดด้านล่าง

               /*
                * การใช้งาน foreach
                * @author http://javaagkasit.blogspot.com/
                */
                  public class foreach {
                         public static void main(String [] args){
     
                         String [] colors = {"Red","Blue","Pink","Yellow","Orange"};
                         //for ธรรมดา
                         for(int i =0 ; i< colors.length ;i++){
                                  System.out.println(colors[i]);
                         }
                         //for -each 
                         for(String c : colors){
                                 System.out.println(c);
                         }
                    }
              }

              จากโค้ดด้านบน จะเห็นได้ว่าการใช้ for-each จะทำได้ง่ายและเร็วกว่าการใช้ for ธรรมดา แต่ในทางกลับกันในความสะดวกสะบายของ for - each ยังมีข้อเสียอยู่ ในกรณี ถ้าเราต้องการแสดงเฉพาะตำแหน่งเราต้องการโชว์ เช่น โชว์เฉพาะตำแหน่ง colors[0]  จะทำไม่ได้


เนื่้อหาที่เกี่ยวข้อง
        - การใช้ for http://javaagkasit.blogspot.com/2012/08/for.html
        - การใช้ switch casehttp://javaagkasit.blogspot.com/2012/08/switch-case.html
        - การใช้ if else http://javaagkasit.blogspot.com/2012/08/if-else.html
        - การใช้ if else if http://javaagkasit.blogspot.com/2012/08/if-else-if.html

[Java]คำสั่งวนลูป การใช้ for



          การใช้งานคำสั่ง For มี 2 แบบ


                    แบบที่ 1

 /**
 *
 * @author http://javaagkasit.blogspot.com
 */
public class basic_For {
    public static void main(String [] args){
        String [] item = {"For_1 = for","For_2 = For-each Loop"};
          for(int i = 0 ; i < item.length;i++){
              System.out.println(item[i]);
          }
    }
}
                       
                แบบที่ 2

/**
 *
 * @author http://javaagkasit.blogspot.com
 */
public class basic_For2 {
    public static void main(String [] args){
        String [] item = {"For_1 = for","For_2 = For-each Loop"};
          for(String s : item){
              System.out.println(s);
          }
    }
}
                 
                          Output.



                 output ทั้ง 2 แบบเหมือนกันทุกประการ ถ้าจะถามว่าทำไมถึงมี 2 แบบ เขียนโปรแกรมบ่อยๆก็จะเข้าใจเอง 
              

          การทำงานของคำสั่ง For Loop

                     Sentex:

                            แบบที่ 1
 

for(initialization ; Boolean_expression ; update)
{
   //Statements
}
          
                            แบบที่ 2


for (type var : arr) {
    //Statements 
 }

                 Explained by flow control.

[Java]การใช้ switch case

      

               I have the source code.


/** ตัวอย่างการใช้งาน switch case
 * ตัวอย่างนี้ เป็นการแปลงตัวเลขเป็นตัวอักษร โดยนำ   switch case มาใช้งาน
 *
 * @author http://javaagkasit.blogspot.com/
 */
public class switchCase {
    public static void main(String [] args){
        for(int i = 0 ; i < 10 ; i++){
            System.out.println(revertNumberToString(i));//Show  Number String
        }
    }
    //Mathode revert Number to String.
    public static String revertNumberToString(int i){
        switch(i){
            case 0 : return "zero";     //if i == 0  then return "zero"
            case 1 : return "one";      //if i == 1  then return "one"
            case 2 : return "two";      //if i == 2  then return "two"
            case 3 : return "tree";     //if i == 3  then return "tree"
            case 4 : return "four";     //if i == 4  then return "four"
            case 5 : return "five";     //if i == 5  then return "five"
            case 6 : return "six";      // .
            case 7 : return "seven";    // .
            case 8 : return "eigth";    // .
            case 9 : return "nine";     //if i == 9  then return "nine"
            default : return"ten";      //others in condition then == "ten"
         
    }
    }
}
         
           สาเหตุที่ไม่มีคำสัง break  เหมือน switch case แบบที่เราเคยเห็นทั่วไป คือ ในลักษณะการทำงานนี้ทำครั้งเดียวอยู่แล้วไม่จำเป็นต้อง ใช้คำสั่ง break

          Explained by this.

       

         Output.



[Java ] การใช้ if else



             ตัวอย่าง การใช้งาน if else


 int score = 60;
                   if(score > 49){
                         System.out.println("you pass.");
                  }else{
                         System.out.println("you fail.");
                 }

            อธิบายเป็นภาพล่ะกันนะ


การทำงานของ เงื่่อนไง if - else

หนังสือจาวาฟรี Free Java Ebooks

หนังสือ Java ฟรี ภาษาไทย

  • สำหรับคนที่ชอบอ่านโค้ด  http://downloads.se-ed.com/ เป็นโค้ดที่มากับหนังสือที่ขาย ของ se-ed book
  • อ่านแล้วไม่เข้าใจก็ฟังเอา http://www.javathailand.com/ ฟังแล้วเข้าใจลองดู

[Java]การอ่านข้อมูลจากไฟล์ โดยการใช้ BufferedReader

การอ่านข้อมูลจากไฟล์ โดยการใช้ BufferedReader

การอ่านข้อมูลจากไฟล์ โดยการใช้ BufferedReader


ถ้าเราต้องการข้อมูลจาก ไฟล์ c.in ที่ไดร์ C: 
มีตัวอย่างดังนี้ ไฟล์ c.in จะมีข้อมูลดังนี้
   
5
+/+-*%
142Sp94r09y+j0i50*5i198++07m6743
40
/*--++
10234*x12bx3000001033309-81632@1200
200
--//%%
1234567810000000
50
--//
sdjf23349fjdhy36458!@#$%^&09*()xc00bn567800000000                      
20
++--
0000j*09
9

โค้ดที่เราจะเขียนดึงข้อในไฟล์ c.in คือ

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class readerfile {
    public static void main (String [] args) throws FileNotFoundException, IOException{
     File infile = new File("C:/c.in");
     FileReader in = new FileReader(infile);
     BufferedReader bin = new BufferedReader(in) ;
   
     String Stringin;
   
     while((Stringin = bin.readLine()) != null){//เช็ค ถ้าไม่เท่ากับ null ก็อ่านข้อมูลมาทีละบรรทัด จนหมด
         System.out.println(Stringin);  
     }
    }
}


หมายเหตุ
      -  bin.readLine() คือ อ่านข้อมูลในไฟล์ ได้ทีละ 1 บรรทัด


ผลที่ได้จากการ รัน


                               

นอกจากการอ่านข้อมูลจากไฟล์แบบ BufferedReader แล้วมีแบบอื่นอีก เช่น ใช้ Scanner   ผมจะชอบใช้ก็มีแค่ BufferedReader กับScanner 
            นอกจากที่อ่านข้อมูลจากไฟล์ได้แล้วยังมีการเขียนข้อมูลลงไฟล์อีกครับ ลองถามพี่ กรูส์ 
ดูนะครับผมก็ขอจบเรื่ิอง การอ่านข้อมูลจากไฟล์ โดยการใช้ BufferedReader แค่นี้ละกันครับ

วิดีโอนี้ เอามาให้ดูเพี่อจะให้เห็น การเขียน แบบ OOP สำคัญมากในการเขียน JAVA เขา(นิรนาม จักใคร)พูดว่า ถ้าไม่เข้าใจ OOP ก็ไม่มีประโยชน์ที่จะมาเขียนจาวา