二级Java程序题--02简单应用:源码大全(01-27)

目录

2.1

2.2

2.3

2.4

2.5

2.6

2.7

2.8

2.9

2.10

2.11

2.12

2.13

2.14

2.15

2.16

2.17

2.18

2.19

2.20

2.21

2.22

2.23

2.24

2.25

2.26


2.1

import java.util.Random;
​
public class Java_2
{
   public static void main(String args[]){
      Random random = new Random();
      float x = random.nextFloat();//产生0.0与1.0之间的一个符点数
      int n = Math.round(20*x);  //构造20以内的一个整数
      long f = 1 ;  //保存阶乘的结果
      int k = 1 ;  //循环变量
   //*********Found********
      do{f* = k;
         k++;
   //*********Found********
      }while(k<=n) ;    
      System.out.println(n+"!= "+f);
   }
}

2.2

import java.awt.*;
import java.applet.*;
​
//*********Found********
public class Java_2 extends Applet
{
    TextArea outputArea;
​
    public void init()
    {
        setLayout(new BorderLayout());
        outputArea = new TextArea();
     //*********Found********
       add( outputArea );
​
      // 计算0至10的阶乘
        for ( long i = 0; i <= 10; i++ )
            //*********Found********
            outputArea.append(i + "! = " + factorial(i) + "\n" );
    }
   
   // 用递归定义阶乘方法
    public long factorial( long number )
    {                  
        if ( number <= 1 )  // 基本情况
            return 1;
        else
            //*********Found********
            return number * factorial( number- 1 );
    }  
}
​

2.3

public class Java_2
{
    public static void main(String[] args) {
        int[][] aMatrix = {{1,1,1,1,1},{2,2,2,2,2},{3,3,3,3,3},{4,4,4,4,4}};
        int i = 0; //循环变量
        int j = 0; //循环变量
        //print matrix
        for (i = 0; i < aMatrix.length; i++) {
   //*********Found********
           for ( j = 0; j < aMatrix[i].length; j++) {
   //*********Found********
            System.out.print(aMatrix[i][j] + " ");
           }
        System.out.println();
        }
    }
}
​

2.4

//*********Found**********
public class Java_2 extends Thread{ 
   private int x=0; 
   private int y=0; 
 
   public static void main(String[]args){
      Java_2 r = new Java_2();
      //*********Found********** 
      Thread t = new Thread(r);
      t.start(); 
   }
   public void run() { 
      //*********Found**********
      int k = 0;
      for(;;){      
         x++; 
         //*********Found**********
         y++; 
         k++;
         if (k>5) break;
         System.out.println("x=" + x + ",y ="+ y); 
      }
   }
}

2.5

public class Java_2 { 
   public static void main (String args[]) { 
      try { 
         Sleep a = new Sleep (); 
         Thread t = new Thread (a); 
         //*********Found**********
         t.start();
         t.join(); 
         int j= a.i; 
         System.out.println("j="+j+",a.i="+a.i);
      } catch (Exception e) {} 
   } 
} 
​
//*********Found**********
class Sleep implements Runnable{ 
   int i; 
   public void run () { 
      try { 
         //*********Found**********
         Thread.sleep(50); 
         i= 10; 
      } 
      //*********Found**********
     catch(InterruptedException e) {} 
   } 
}
​

2.6

public class Java_2{
   public static void main(String args[]) { 
      //*********Found**********
      int a[][] =new int[5][5];
      int i,j,k = 1;
      for(i=0;i<5;i++)
         for(j=0;j<5;j++)
            if((i+j)<5){
               a[i][j] = k;
               //*********Found**********
               k++;
               if (k > 9) k = 1;
            }else
               //*********Found**********
               a[i][j]=0;
      for(i=0;i<5;i++){ 
         for(j=0;j<5;j++)
            System.out.print(a[i][j]+ "   ");
         //*********Found**********
         System.out.println();
      }
   }
}
​

2.7

import java.io.*;
public class Java_2{
   public static void main (String[] args){
      //*********Found**********
      byte buf[] = new byte[5];
      int len= 0 ,c1 = 0,c2=0;
      //*********Found**********
      try{
         //*********Found**********
         FileInputStream in = new FileInputStream("test.txt");
         while((len =in.read(buf,0,5))>0){
            for(int i = 0; i < len;i++)
               if(buf[i]>= '0' && buf[i] <= '9'){
                  c1 ++;
               }
               else 
                  if((buf[i]>= 'a' && buf[i] <= 'z') || buf[i]>= 'A' && buf[i] <= 'Z') 
                     c2++;
            if(len <5) break;
         }
         //*********Found**********
         in.close(); 
      }catch(Exception e ){}
      System.out.println("数字数是 " + c1 + ",字母数是 " + c2);
   }
}
​

2.8

import java.io.*;
​
public class Java_2{
   public static void main(String args[]) { 
      int a[][] = new int[5][5];
      int i,j,k=1;
      for(i=0;i<5;i++)
         //*********Found**********
         for( j=0; j<5 ;j++ )
            //*********Found**********
            if((i+j)< 4)
               a[i][j]=0;
            else{               
               //*********Found**********
               a[i][j]=k++;
            }
      for(i=0;i<5;i++){ 
         for(j=0;j<5;j++)
            //*********Found**********
            if(a[i][j]<10)
               System.out.print(a[i][j]+ "   ");
            else
               System.out.print(a[i][j]+ "  ");
         System.out.println();
      }
   }
}
​

2.9

public class Java_2{
   public static void main(String args[]){
      int i=0;
      String greetings[] ={ "Hello World!","Hello!","HELLO WORLD!!"};
      while (i<4){
         try{
            //*********Found********
            System.out.println(greetings[i]);
         }
     //*********Found********
         catch(ArrayIndexOutOfBoundsException e){
     //*********Found********
            System.out.println("Catch " + e.getMessage());
            System.out.println("Ending the print.");
         }
         finally{
            System.out.println("---------------------");
         }  
     //*********Found********
         i++;
      }
   }
}
​

2.10

import java.io.File;
​
public class Java_2
{
   public static void main(String s[])
   {
      //Getting the Current Working Directory
      String curDir = System.getProperty("user.dir");
      System.out.println("当前的工作目录是:"+curDir);
        
      //*********Found**********
      File ff=new File(curDir);
      String[] files=ff.list();
      for(int i=0; i<files.length; i++)
      {
         String ss=curDir+"\\"+files[i];
         traverse(0,ss);    
      }
   }
    
   /**
   * 递归地遍历目录树
   * @param  level 目录的层次
   * @param  s     当前目录路径名
   */
   public static void traverse(int level,String s)
   {
      File f=new File(s);
      for(int i=0; i<level; i++) System.out.print("   ");
      if(f.isFile()) 
      {
         System.out.println(f.getName());
      }
      else if(f.isDirectory())
      {
         //*********Found**********
         System.out.println("<"+f.getName()+">");
         String[] files=f.list();
         level++;
         //*********Found**********
         for(int i=0; i<files.length;i++)
         {
            String ss=s+"\\"+files[i];
            //*********Found**********
            traverse(level,ss);
         }
      }
      else
      {
         System.out.println("ERROR!");
      }
   }
}

2.11

public class Java_2 {
    public static void main(String[ ] args) {
        Point pt;
        //*********Found**********
        pt = new Point(2, 3);
        System.out.println(pt);
    }
}
​
class Point {
​
    //*********Found**********
    private int x;
    private int y;
​
    //*********Found**********
    public Point(int a, int b) {
        x = a;
        y = b;
    }
​
    int getX( ) {
        return x;
    }
​
    int getY( ) {
        return y;
    }
​
    void setX(int a) {
        x = a;
    }
​
    void setY(int b) {
        y = b;
    }
​
    //*********Found**********
    public String toString ( ) {
        return "( " + x + "," + y + " ) ";
    }
}
​

2.12

public class Java_2 {
    public static void main(String[ ] args) {
        //*********Found**********
        Point[] pt = new Point[2];
        pt[0] = new Point();
        pt[1] = new Point(2, 3);
        //*********Found**********
        for (int i=0; i < pt.length; i++) {
            System.out.print( pt[i] );
        }
    }
}
​
class Point {
​
    private int x;
    private int y;
​
    public Point() {
        this(0, 0);
    }
​
    //*********Found**********
    public Point (int a, int b) {
        x = a;
        y = b;
    }
​
    int getX( ) {
        return x;
    }
​
    int getY( ) {
        //*********Found**********
        return y;
    }
​
    void setX(int a) {
        x = a;
    }
​
    void setY(int b) {
        y = b;
    }
​
    public String toString ( ) {
        return "  ( " + x + "," + y + " ) ";
    }
}
​

2.13

public class Java_2 {
​
    public static void main(String args[]) {
        int [][]a = {{2, 3, 4}, {4, 6, 5}};
        int [][]b = {{1, 5, 2, 8}, {5, 9, 10, -3}, {2, 7, -5, -18}};
        //*********Found**********
        int [][]c = new int[2][4];
        for (int i = 0; i < 2; i++) {
            //*********Found**********
            for (int j = 0; j < 4; j++) {
                //*********Found**********
                c[i][j]=0;
                for (int k = 0; k < 3; k++) 
                    //*********Found**********
                    c[i][j] +=a[i][k]*b[k][j];
                System.out.print(c[i][j] + "  ");
            }
            System.out.println();
        }
    }
}
​

2.14

import java.io.*;
 
public class Java_2 {
    public static void main(String[] args) {
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try { 
            File f = new File("Person.dat");
            //*********Found**********
            oos = new ObjectOutputStream(new FileOutputStream(f));
            oos.writeObject(new Person("小王"));
            oos.close();
            ois = new ObjectInputStream(new FileInputStream(f));
            //*********Found**********
            Person d = (Person) ois.readObject();
            System.out.println(d);
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
//*********Found**********
class Person implements Serializable{
    String name = null;
    public Person(String s) {
        name = s;
    }
    //*********Found**********
    public String toString() {
        return name;
    }
}

2.15

//*********Found**********
public class Java_2  extends Thread{
    private String sThreadName; 
    public static void main(String argv[]){
        Java_2 first = new Java_2("first");
        //*********Found**********
        first.start();
        Java_2 second = new Java_2("second");
        //*********Found**********
        second.start();
    }
    
    //*********Found**********
    public Java_2(String s){
        sThreadName = s;
    }
    
    public String getThreadName(){
        return sThreadName;
    }
​
    public void run(){a
        for(int i = 0; i < 4; i ++){
            //*********Found**********
            System.out.println(getThreadName()+i);
            try{
                 Thread.sleep(100);
            } catch(InterruptedException e){
                System.out.println(e.getMessage());
            }
        }
    }
}

2.16

public class Java_2{
​
    public static void main(String args[]) {
        SubClass subC = new SubClass();
        subC.doSomething();
    }
}
class SuperClass {
​
    int x;
​
    SuperClass() {
        //*********Found********
        x =3;
        System.out.println("in SuperClass : x=" + x);
    }
​
    void doSomething() {
        //*********Found********
        System.out.println("in SuperClass.doSomething()");
    }
}
​
class SubClass extends SuperClass {
​
    int x;
​
    SubClass() {
        super();
        //*********Found********
        x =5;
        System.out.println("in SubClass  :x=" + x);
    }
​
    void doSomething() {
        super.doSomething();
        //*********Found********
        System.out.println("in SubClass.doSomething()");
        System.out.println("super.x=" + super.x + "  sub.x=" + x);
    }
}
​

2.17

//*********Found********
import java.awt.*;
import java.io.*;
import java.awt.event.* ;
import javax.swing.*;
​
//*********Found********
public class Java_2 implements ActionListener{ 
   
    JTextArea ta;
    JFrame f ;
    JLabel label;
    JButton bt;
​
    public static void main(String args[ ]){
        Java_2 t = new Java_2();
        t.go();
    }
​
    void go(){
        f = new JFrame("Save data");
        label = new JLabel("请输入需要保存的文本:");
        ta = new JTextArea(3,20);
        bt = new JButton("保存");
        //*********Found********
        f.add(label,BorderLayout.NORTH);
        f.add(ta,BorderLayout.CENTER);
        f.add(bt,BorderLayout.SOUTH);
        //*********Found********
        bt.addActionListener(this);
        f.setSize(400,400);
        f.pack( );
        f.setVisible(true) ;
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
    }
    
    public void actionPerformed(ActionEvent event){
        try{
            FileWriter  out = new FileWriter("out.txt");
            String str = ta.getText();
            //*********Found********
            out.write(str);  
            out.close();
        } catch( Exception e){
        }
    }    
}
​

2.18

import java.io.*;
​
public class Java_2 {
    public static void main(String args[]) {
        String ShowMes[] = {"在那山的那边海的那边有一群蓝精灵", "它们活泼又聪明它们调皮又灵敏", "它们自由自在生活在那绿色的大森林", "它们善良勇敢相互都欢喜!"};
        try {
            //*********Found********
            FileWriter out = new FileWriter("test.txt");
            BufferedWriter outBW = new BufferedWriter(out);
            for (int i = 0; i < ShowMes.length; i++) {
                outBW.write(ShowMes[i]);
                outBW.newLine();
            }
            //*********Found********
            outBW.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            //*********Found********
            FileReader in = new FileReader(new File("test.txt"));
            BufferedReader inBR = new BufferedReader(in);
            String stext = null;
            int j = 1;
            while ((stext = inBR.readLine()) != null) {
                System.out.println("第" + j + "行内容:" + stext);
                //*********Found********
                j++;
            }
            inBR.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
​

2.19

import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
​
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
​
//*********Found********
public class Java_2 implements ActionListener{
    JTable table = null;
    DefaultTableModel defaultModel = null;
    
        //*********Found********
        public Java_2(){
        JFrame f = new JFrame();
        String[] name = {"字段 1","字段 2","字段 3","字段 4","字段 5"};
        String[][] data = new String[5][5];     
                int value =1;
        for(int i=0; i<data.length; i++){
            for(int j=0; j<data.length ; j++)
                data[i][j] = String.valueOf(value++);
        }       
        defaultModel = new DefaultTableModel(data,name);
        table=new JTable(defaultModel);
        table.setPreferredScrollableViewportSize(new Dimension(400, 80));
        JScrollPane s = new JScrollPane(table);
​
        JPanel panel = new JPanel();
        JButton b = new JButton("增加行");
        panel.add(b);
    
        //*********Found********
            b.addActionListener(this);
        b = new JButton("删除行");
        panel.add(b);
        b.addActionListener(this);
    
        //*********Found********
                Container contentPane = f.getContentPane();
        contentPane.add(panel, BorderLayout.NORTH);
        contentPane.add(s, BorderLayout.CENTER);
​
        //*********Found********
        f.setTitle("增删表格行");
        f.pack();
        f.setVisible(true);
​
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                    System.exit(0);
            }
        });
        //*********Found********
        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if(table.isCellSelected(table.getSelectedRow(), table.getSelectedColumn())){
                    int selRow=table.getSelectedRow();
                    int selCol=table.getSelectedColumn();
                JOptionPane.showMessageDialog(null, 
                        "位于 ("+selRow+","+selCol+")的元素: "+table.getValueAt(selRow,selCol), 
                        "PLAIN_MESSAGE", JOptionPane.PLAIN_MESSAGE);
                }
                }
           });
    }
    public void actionPerformed(ActionEvent e){
        if(e.getActionCommand().equals("增加行"))    
            defaultModel.addRow(new Vector());
        if(e.getActionCommand().equals("删除行")){
            int rowcount = defaultModel.getRowCount()-1; //getRowCount返回行数,rowcount<0代表已经没有任何行了。
            if(rowcount >= 0){
                defaultModel.removeRow(rowcount);               
                defaultModel.setRowCount(rowcount);
            }
        }       
        table.revalidate();
    }
​
    public static void main(String[] args) {
        new Java_2();
    }
}
​

2.20

public class Java_2{
   public static void main(String[] args){
      //*********Found**********
      int [][] aMatrix = new int[4][];
      int i = 0;
      int j = 0;
      int k = 4;
​
      for(i = 0; i < 4; i++){
         //*********Found**********
         aMatrix[i] = new int[k--];
 
         //*********Found**********
         for (j = 0; j < aMatrix[i].length; j++) {
            aMatrix[i][j] = i+1;
            System.out.print(aMatrix[i][j] + " ");
         }
         //*********Found**********
         System.out.println();
      }
   }
}

2.21

import java.util.*;
​
public class Java_2
{  
   public static void main(String[] args)
   {
      Student[] java = new Student[3];
      java[0] = new Student("李明", 80);
      java[1] = new Student("赵冬", 75);
      java[2] = new Student("王晓", 98);
      //*********Found**********
      Arrays.sort(java);
      System.out.println("Java 成绩降序排序的结果是:");
      for (int i = 0; i < java.length; i++)
      {
         Student e = java[i];
      //*********Found**********
         System.out.println("name=" + e.getName()
            + ",fenshu=" + e.getFenshu());
      }
   }
}
​
//*********Found**********
class Student implements Comparable
{
   public Student(String n, double f)
   {
      name = n;
      fenshu = f;
   }
   public String getName()
   {
      return name;
   }
   public double getFenshu()
   {
      return fenshu;
   }
   public int compareTo(Object otherObject)
   {
      Student other = (Student)otherObject;
      if (fenshu < other.fenshu) return 1;
      if (fenshu > other.fenshu) return -1;
      return 0;
   }
   private String name;
   //*********Found**********
   private double fenshu;
}
​

2.22

public class Java_2
{
   public static void main(String[] args)
   {
      System.out.println("观察triple方法参数 double 10.0 的改变:");
      //*********Found**********
      double canshu = 10;
      //*********Found**********
      System.out.println("参数*3前,参数值为 " +canshu);
      triple(canshu);
      System.out.println("在triple方法外,参数值仍为 " + canshu);
      System.out.println("思考:方法能否改变参数值?");
   }
  //*********Found**********
   public static void triple(double x)
   {
      //*********Found**********
      x=3*x;
      //*********Found**********
      System.out.println("在triple方法内,参数 10 变为 " + x);
   }
}
​

2.23

import java.text.*;
​
public class Java_2
{
   public static void main(String[] args)
   {
      Person[] people = new Person[2];
      people[0] = new Worker("老张", 30000);
      people[1] = new Student("小王", "计算机科学");
      for (int i = 0; i < people.length; i++)
      {
         Person p = people[i];
         //*********Found**********
         System.out.println(p.getName() + ", " + p.getDescription());
      }
   }
}
​
//*********Found**********
abstract class Person
{
   public Person(String n)
   {
     name = n;
   }
//*********Found**********
   public abstract String getDescription();
   public String getName()
   {
     return name;
   }
   private String name;
}
​
//*********Found**********
class Worker extends Person
{
   public Worker(String n, double s)
   {
      super(n);
      salary = s;
   }
   public String getDescription()
   {
      NumberFormat formatter = NumberFormat.getCurrencyInstance();
      return "工人,年薪是 " + formatter.format(salary) + "。";
   }
   private double salary;
}
​
//*********Found**********
class Student extends Person
{
   public Student(String n, String m)
   {
      super(n);
      major = m;
   }
   public String getDescription()
   {
      return "学生,专业是 " + major + "。";
   }
   private String major;
}
​

2.24

public  class  Java_2
{    
   public static void main(String[] args)
   {
      Thread t = new SimpleThread("Testing_Thread");
       //*********Found**********
      t.start()  ;   
   }
} 
 //*********Found**********
class SimpleThread extends Thread
{
   public SimpleThread(String str)
   {
      //*********Found**********
      super(str)   ;
   }
    //*********Found**********
   public void run()
   {  
      System.out.println("Running the " + getName() + ":");
      for (int i = 0; i < 5; i++)
      {
         System.out.println("---" + i + "---" + getName());
         try
         {
            sleep((int)(2 * 100));
         }
         //*********Found**********
         catch(InterruptedException e) { }
      }
   }
}

2.25

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
​
public class Java_2
{
   public static void main(String args[])
   {
      if(args.length<2)
      {
         System.out.println("ERROR: need parameters.");    
         System.out.println("\n -usage: java <classname> <file1> <file2>");    
         System.exit(0);
      }
      File f1=new File(args[0]);
      //*********Found**********
      File f2=new File(args[1]);
      try
      {
         //*********Found**********
         FileReader fr=new FileReader(f2);
         FileWriter fw=new FileWriter(f1,true);
         int b;
         //*********Found**********
         while(( b=fr.read() ) != -1 )  fw.write(b);
         fr.close();
         fw.close();
      }
      catch(IOException e)
      {
         e.printStackTrace();
      }
      System.out.println("has done!");
      //*********Found**********
      if(f2.delete()) System.out.print("SUCCESS!");
   }
}
​

2.26

//*********Found**********
import java.io.*;
import java.util.Vector;
​
public class Java_2
{
   public static void main(String args[])
   {
      Vector v=new Vector();
      try
      {
         //*********Found**********
         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
         String str = "";
         System.out.println("请输入用户和密码信息,中间用空格隔开,输入quit退出:");
         //*********Found**********
         while (!(str.equals("quit")||str.equals("QUIT")))
         {
            str = in.readLine();
            if(isValid(str))
               v.add(str);
            else 
            {
               if(!(str.equals("quit")||str.equals("QUIT")))
                  System.out.println("The string is NOT valid!");
            }
         }
        
         System.out.println("请输入保存到的文件名:");
         str=in.readLine();
​
         String curDir = System.getProperty("user.dir");
         File savedfile=new File(curDir+"\\"+   str   );
            
         BufferedWriter out = new BufferedWriter(new FileWriter(savedfile));
         for(int i=0; i<v.size(); i++)
         {
            String tmp=(String)v.elementAt(i);
         //*********Found**********
            out.write(tmp);
            out.write("\n");
         }
         out.close();
        
      }
      catch (Exception e)
      {
         System.out.print("ERROR:"+e.getMessage()); 
      }
   }
    
   /**
   * 判定输入的字符串是否符合规范
   * @param  s  输入的待校验的字符串
   * @return    校验的结果,正确则返回为真
   */
   public static boolean isValid(String s)
   {
      if(s.indexOf(" ")>0)
         return true;
      else
         return false;
   }
}
​
  • 10
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yueqingll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值