Some basic Java exercises

Source: Internet
Author: User

1, in the text file Book.txt contains a long length of the English essay, the writing procedure requires that the statistics file contains the English letter "a" number

Package Iowork;import java.io.file;import Java.io.fileinputstream;import java.io.ioexception;/**2014-11-15 * @author Administrator * 1, in the text file Book.txt contains a long length of English essays, the program requires that the statistical file contains the number of the English letter "a" */public class Readtxt {public static void Main (string[] args) {file File=new file ("D:/book.txt");//Create File    if (!file.exists ()) {        try {        File.createnewfile ();        } catch (IOException e) {            e.printstacktrace ();        }    }    try {fileinputstream fis=new fileinputstream (file); int c=fis.read ();        int count=0;for (int i=0;i<file.length (); i++) {        char ch = (char) (Fis.read ());  Loop read character        if (ch== ' A ') {        count++;        }        System.out.print (CH);} SYSTEM.OUT.PRINTLN ("Total" +count+ "a"); Fis.close ();} catch (Exception e) {//TODO auto-generated catch block      System.out.println ("File open failed. "); E.printstacktrace ();}}}
2. Read the contents of a file, convert uppercase letters to lowercase and output to another file

Package Iowork;import Java.io.bufferedreader;import Java.io.bufferedwriter;import java.io.file;import Java.io.fileinputstream;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstreamreader;import java.io.outputstreamwriter;/**2014-11-15 * @author Administrator * 2, read out the contents of a file,  Convert capital letters to lowercase letters output to another file */public class Work2 {public static void main (string[] args) throws IOException {String Txtfilepath = "D:/book.txt";//original file FileInputStream fis = new FileInputStream (new file (Txtfilepath)); InputStreamReader ISR = new InputS Treamreader (FIS, "GBK"); BufferedReader reader = new BufferedReader (ISR); String Othertxtfilepath = "d:/book_lower.txt";//Save lowercase file FileOutputStream fos = new FileOutputStream (new file Othertxtfilepath)); OutputStreamWriter OSW = new OutputStreamWriter (FOS, "GBK"); BufferedWriter writer = new BufferedWriter (OSW); String line = Null;while ((line = Reader.readline ()) = null) {Writer.append (Line.tolowercase ()). Append ("\ r \ n");} Writer.close (); Reader.close ();}}


3. Write a program that detects if there is a local save object that holds the student (deserialization), prints the student information in the console if it exists (deserializes), if not, first creates the student object through student, outputs and saves the student information to the local file (serialization).

Package Iowork;import Java.io.file;import Java.io.fileinputstream;import java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;import java.io.serializable;/**2014-11-15 * @author Administrator * 3, write a program, Detects if there is a local save object that holds the student (deserialization), outputs the student information in the console if it exists (deserializes), * if not, the student object is first created through student and the student information is output and saved to a local file (serialization). */public class Work3 implements serializable{private static final long serialversionuid = 1l;private String name;public St Ring GetName () {return name;} public void SetName (String name) {this.name = name;} public static void Main (string[] args) throws FileNotFoundException, IOException, classnotfoundexception {/* * file is stu under E-disk  Dent.txt file */objectoutputstream output = Null;object obj = null;//If an exception is caught, no object is stored in the file Try{objectinputstream input = new ObjectInputStream (New FileInputStream ("E:\\student.txt")); obj = Input.readobject ();} catch (Exception eofexception) {System.out.println ("No Student object stored"");} System.out.println (obj), if (obj instanceof Work3) {//If there is no exception and is stored for the student object Work3 student = (WORK3) obj; System.out.println ("The name of the saved student is:" + student.getname ());} else {//If there is no exception but not the student object stored Work3 s = new Work3 (); S.setname ("Zhang San"); output = new ObjectOutputStream (New FileOutputStream File ("E:\\student.txt")); Output.writeobject (s); SYSTEM.OUT.PRINTLN ("Student Information Saved");}}}
4. Please write a class named Subthread, which is a subclass of the thread class.  The run () method is defined in the class, there is a for loop in the method, and the loop is 5 times, and the loop body shows the thread looping the first several times at the command line, then sleeps for half a second, and then displays the thread end message after the loop ends: thread name +finished. Write a application program in which you create the Sub thread class of three thread objects t1,t2,t3, whose names are Frist,second,third, and start these three threads

Package iowork;/**2014-11-15 * @author Administrator, write a class with the class name Subthread, which is a  subclass of the thread class. The run () method is defined in the class, there is a for loop in the method, and the loop is 5 times, and the loop body shows the thread looping the first few times in the command line and then sleeps for half a second, * The thread end information is displayed after the loop ends: thread name +finished.  Write a application program, * and create a Sub thread class in which the three thread object T1,T2,T3, * Their name is Frist,second,third, and start the three threads */public class Subthread extends Thread{public void run () {try {for (int i=0;i<5;i++) {System.out.println ("The Thread Loops" +i+ "Times"); Thread.Sleep (500); System.out.println (i+ "thread Finished");}} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} public static void Main (string[] args) {//three threads thread        t1 = new Thread (new Subthread ());  The first custom thread        t2 = new Thread (new Subthread ());  The second custom thread thread        t3 = new Thread (new Subthread ());  A second custom thread        t1.start ();        T2.start ();        T3.start ();}}

5. Multithreading to find prime numbers

Package Work5;public class Calcprime {public static void main (string[] args) {Thread1 T1 = new Thread1 (); Thread2 t2 = new Thread2 (); Thread3 t3 = new Thread3 (); T1.start (); T2.start (); T3.start ();}} Class Thread1 extends Thread {Thread4 t4 = thread4.getinstance ();p ublic void Run () {String str1 = primehandler.getinstance (). Getprimenums (10000); t4.accept (STR1);}} Class Thread2 extends Thread {Thread4 t4 = thread4.getinstance ();p ublic void Run () {String str2 = primehandler.getinstance (). Getprimenums (10001, 20000); t4.accept (STR2);}} Class Thread3 extends Thread {Thread4 t4 = thread4.getinstance ();p ublic void Run () {String STR3 = primehandler.getinstance (). Getprimenums (20001, 30000); t4.accept (STR3);}} Class Thread4 extends Thread {private static int isend = 0;private static Thread4 t4;private Thread4 () {}public static Thr Ead4 getinstance () {if (T4 = = null) {T4 = new Thread4 ();} return t4;} public void Run () {while (isend = = 3) {Printhandler.destroy ();}} public void Accept (String content) {PrinthaNdler.getinstence ("Xyz.dat"). printstring (content); isend++;}} 

Package Work5;public class Primehandler {private static Primehandler phandler;private Primehandler () {}public static sync hronized Primehandler getinstance () {if (Phandler = = null) {Phandler = new Primehandler ();} return Phandler;} private static Boolean isprimenum (int n) {Boolean hasdivisor = false;for (int i = 2; i < n; i++) {if (n% i = = 0) {HASD Ivisor = True;}} if (Hasdivisor) {return false;} else {return true;}} Public synchronized String getprimenums (int from, int. to) {StringBuilder Strbuilder = new StringBuilder (); int tag = 1;for (int i = from; I <= to; i++) {if (Isprimenum (i)) {strbuilder.append (i). Append (","); if (tag% = = 0) {strbuilder.append (' \ n ');} tag++;}} return strbuilder.tostring ();}} Package Work5;public class Primehandler {private static Primehandler phandler;private Primehandler () {}public static sync hronized Primehandler getinstance () {if (Phandler = = null) {Phandler = new Primehandler ();} return Phandler;} private static Boolean isprimenum (int n) {Boolean hasdivisor = false;for (int i = 2; i < n; i++) {if (n% i = = 0) {Hasdivisor = true;}} if (Hasdivisor) {return false;} else {return true;}} Public synchronized String getprimenums (int from, int. to) {StringBuilder Strbuilder = new StringBuilder (); int tag = 1;for (int i = from; I <= to; i++) {if (Isprimenum (i)) {strbuilder.append (i). Append (","); if (tag% = = 0) {strbuilder.append (' \ n ');} tag++;}} return strbuilder.tostring ();}}

6. Traversing the contents of a folder
Package iowork; Import Java.io.File; public class Work6 {/** * @param args */public static void main (string[] args) {//TODO Auto-gene        Rated method Stub file = new file ("c:\\ thunderbolt download \ \");     Printfile (file,0);        }/** * Output tree * @param file * @param l */public static void Printfile (file file,int l) {  String str = new string ();        Generate supplemental space for (int i=0;i<l;i++) {str + = "";                 }//output the output subdirectory or file Formatprint (FILE,STR) first;  if (File.isdirectory ()) {//Determine if directory file[] files = file.listfiles ();            Get directory under File list for (file f:files) {///recursive output file Printfile (f,l+3); }}}/** * format output Files * @param file * @param str */public static void for        Matprint (file file,string str) {///First output file string[] names = File.getname (). Split ("[.]");                System.out.println (Str+file.getname ()  + "" +names[names.length-1]+ "file" + "" +file.length ()); } }


Some basic Java exercises

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.