目录
2.简单应用:
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; } }
2.27
//*********Found********** import javax.swing.*; public class Java_2{ public static void main( String args[] ){ int frequency1 = 0, frequency2 = 0, frequency3 = 0, frequency4 = 0, frequency5 = 0, frequency6 = 0, face; //骰子旋转500次的代码 for ( int roll = 1; roll <= 500; roll++ ) { face = 1 + (int) ( Math.random() * 6 ); //*********Found********** switch ( face) { case 1: ++frequency1; break; case 2: ++frequency2; break; case 3: ++frequency3; break; case 4: ++frequency4; break; case 5: ++frequency5; break; case 6: ++frequency6; break; } } //*********Found********** JTextArea outputArea = new JTextArea( 7, 10 ); outputArea.setText( "面\t频率" + "\n1\t" + frequency1 + "\n2\t" + frequency2 + "\n3\t" + frequency3 + "\n4\t" + frequency4 + "\n5\t" + frequency5 + "\n6\t" + frequency6 ); //*********Found********** JOptionPane.showMessageDialog( null, outputArea, "骰子旋转500次", JOptionPane.INFORMATION_MESSAGE ); //*********Found********** System.exit( 0 ); } }
2.28
import java.io.*; import java.util.Vector; public class Java_2{ public static void main(String s[]){ Vector v=new Vector(); try{ //*********Found********** BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //键盘输入 String str = ""; System.out.println("请输入用户和密码信息,中间用空格隔开,输入quit退出:"); while (!(str.equals("quit")||str.equals("QUIT"))){ str = in.readLine(); //*********Found********** 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("请输入保存到的文件名:"); //*********Found********** str=in.readLine(); String curDir = System.getProperty("user.dir"); File savedfile=new File(curDir+"\\"+str); //*********Found********** BufferedWriter out = new BufferedWriter(new FileWriter(savedfile)); for(int i=0; i<v.size(); i++){ String tmp=(String)v.elementAt(i); out.write(tmp); //*********Found********** out.write("\n "); //换行 } out.close(); } //*********Found********** 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; } }
2.29
import javax.swing.*; import java.awt.event.*; public class Java_2 extends JFrame { private JButton b; public Java_2(String s){ setTitle(s); b=new JButton("Hello"); getContentPane().add(b); //*********Found******** b.addActionListener( new HandleButton() ); setSize(150,150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //*********Found******** setVisible(true); } class HandleButton implements ActionListener{ public void actionPerformed(ActionEvent e){ //*********Found******** if ( "Hello".equals(b.getText()) ) b.setText("你好"); else b.setText("Hello"); } } public static void main(String args[]){ //*********Found******** new Java_2("二级Java"); } }
2.30
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Java_2{ public static void main(String[] args){ RadioButtonFrame frame = new RadioButtonFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //*********Found********** frame.show(); } } class RadioButtonFrame extends JFrame{ public RadioButtonFrame(){ setTitle("Radio按钮实例"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); Container contentPane = getContentPane(); label = new JLabel("热烈庆祝Java程序语言开考三周年"); label.setForeground(Color.yellow); contentPane.setBackground(Color.red); label.setFont(new Font("黑体", Font.PLAIN, DEFAULT_SIZE)); contentPane.add(label, BorderLayout.CENTER); buttonPanel = new JPanel(); group = new ButtonGroup(); addRadioButton("小", 8); addRadioButton("中", 12); addRadioButton("大", 18); addRadioButton("特大", 30); contentPane.add(buttonPanel, BorderLayout.SOUTH); } public void addRadioButton(String name, final int size){ boolean selected = size == DEFAULT_SIZE; //*********Found********** JRadioButton button = new JRadioButton(name, selected); group.add(button); buttonPanel.add(button); ActionListener listener = new ActionListener(){ //*********Found********** public void actionPerformed(ActionEvent evt){ label.setFont(new Font("黑体", Font.PLAIN, size)); } }; //*********Found********** button.addActionListener(listener); } public static final int DEFAULT_WIDTH = 340; public static final int DEFAULT_HEIGHT = 200; private JPanel buttonPanel; private ButtonGroup group; private JLabel label; private static final int DEFAULT_SIZE = 12; }
2.31
import javax.swing.*; import java.awt.*; public class Java_2{ public static void main(String[] args){ WelcomFrame frame = new WelcomFrame(); //*********Found********** frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); frame.setVisible(true); } } //*********Found********** class WelcomFrame extends JFrame{ public WelcomFrame(){ setTitle("Java等级考试"); //*********Found********** setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); WelcomPanel panel = new WelcomPanel(); Container contentPane = getContentPane(); contentPane.add(panel); } public static final int DEFAULT_WIDTH = 250; public static final int DEFAULT_HEIGHT = 100; } //*********Found********** class WelcomPanel extends JPanel{ public void paintComponent(Graphics g){ super.paintComponent(g); g.drawString("欢迎参加Java等级考试!",MESSAGE_X, MESSAGE_Y); } public static final int MESSAGE_X = 60; public static final int MESSAGE_Y = 50; }
2.32
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class Java_2{ public static void main(String[] args){ //*********Found********** ActionListener listener = new TimePrinter(); Timer t = new Timer(10000, listener); t.start(); JOptionPane.showMessageDialog(null, "退出程序吗?"); System.exit(0); } } //*********Found********** class TimePrinter implements ActionListener{ //*********Found********** public void actionPerformed(ActionEvent event){ Date now = new Date(); System.out.println("At the tone, the time is " + now); Toolkit.getDefaultToolkit().beep(); } }
2.33
//*********Found********** import javax.swing.*; public class Java_2{ public static void main(String[] args){ //*********Found********** String input = JOptionPane.showInputDialog("你想抽几个数?"); int k = Integer.parseInt(input); input = JOptionPane.showInputDialog("你想在自然数中抽的最大数是几?"); int n = Integer.parseInt(input); int lotteryOdds = 1; //*********Found********** for (int i = 1; i <= k; i++) lotteryOdds = lotteryOdds * (n - i + 1)/i; //*********Found********** System.out.println("你中奖的几率是1/" + lotteryOdds + ". Good luck!"); System.exit(0); } }
2.34
import java.util.Random; public class Java_2{ //*********Found********** public static void main(String args[]){ Random random = new Random(); //*********Found********** float x = random.nextFloat();//产生0.0与1.0之间的一个浮点数 //*********Found********** int n = Math.round(21*x); //构造20以内的一个整数 long f = 1 ; //保存阶乘的结果 int k = 1 ; //循环变量 do { //*********Found********** f*= k++; }while(k<=n); System.out.println(n+"!= "+f); } }
2.35
import java.awt.*; import java.awt.geom.*; //*********Found********** import javax.swing.*; public class Java_2 { public static void main(String[] args) { DrawFrame frame = new DrawFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //*********Found********** frame.setVisible(true); } } //*********Found********** class DrawFrame extends JFrame { public DrawFrame() { setTitle("千里共婵娟"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); DrawPanel panel = new DrawPanel(); //*********Found********** Container contentPane = getContentPane(); //*********Found********** contentPane.add(panel); } public static final int DEFAULT_WIDTH = 400; public static final int DEFAULT_HEIGHT = 240; } //*********Found********** class DrawPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; double l = 0; double r = 0; double w = 400; double h = 400; Rectangle2D re = new Rectangle2D.Double(l,r,w,h); g2.setPaint(Color.BLUE); g2.fill(re); double leftX = 50; double topY = 50; double width = 50; double height = 50; Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height); Ellipse2D ellipse = new Ellipse2D.Double(); ellipse.setFrame(rect); g2.setPaint(Color.YELLOW); g2.fill(ellipse); } }
2.36(*)
import java.awt.*; import javax.swing.*; public class Java_2{ int grades[][] = { { 77, 68, 86, 73 }, { 96, 87, 89, 81 }, { 70, 90, 86, 81 } }; int students, exams; String output; JTextArea outputArea; public Java_2(){ students = grades.length; exams = grades[ 0 ].length; JFrame f = new JFrame(); f.setSize(300,300); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //*********Found********** outputArea = new JTextArea(); Container c = f.getContentPane(); //*********Found********** c.add(outputArea); output = "数组是:"; buildString(); output += "\n\n最高分: " + maximum() + "\n"; //*********Found********** for ( int i = 0; i < students; i++ ) output += "\n第" + (i+1) + "个学生的平均分是: " + average( grades[ i ] ); //*********Found********** outputArea.setText( output ); } //找最高分 public int maximum(){ int highGrade = 0; for ( int i = 0; i < students; i++ ) for ( int j = 0; j < exams; j++ ) if ( grades[ i ][ j ] > highGrade ) //*********Found********** highGrade = grades[i][j]; return highGrade; } //对各组学生确定平均分 public int average( int setOfGrades[] ){ int total = 0; for ( int i = 0; i < setOfGrades.length; i++ ) //*********Found********** total += setOfGrades[i]; return total /exams; } //输出格式 public void buildString(){ output += " "; for ( int i = 0; i < exams; i++ ) output += "[" + i + "] "; for ( int i = 0; i < students; i++ ) { output += "\ngrades[" + i + "] "; for ( int j = 0; j < exams; j++ ) output += grades[ i ][ j ] + " "; } } public static void main(String[ ]args){ new Java_2(); } }
2.37
class Point{ public int x,y; public Point() { } public Point(int x,int y){ this.x = x; this.y = y; } //*********Found********** public Point(Point p){ x = p.x; y = p.y; } public int getX(){ return x; } public int getY(){ return y; } public void moveTo(int x,int y){ this.x = x; this.y = y; } public void moveTo(Point p){ x = p.x; y = p.y; } public String toString(){ return "("+ x + ","+ y + ")"; } public void translate(int dx,int dy){ //平移 this.x += dx; //*********Found********** this.y + = dy; } } public class Java_2 { public static void main(String args[]){ //*********Found********** Point p = new Point(5,5); System.out.println("点的当前坐标:("+p.x + "," + p.y+")"); p.translate(3,4); //*********Found********** System.out.println("平移到:"+p.toString()); } }
2.38
import javax.swing.*; import java.awt.event.*; import java.io.*; import java.awt.*; public class Java_2 implements ActionListener { private JFrame frame; private JButton button,saveButton; private JTextArea textArea; private JFileChooser dia; private JPanel buttonPanel; public void init() { frame=new JFrame("file chooser"); dia=new JFileChooser(); button=new JButton("open file"); button.setActionCommand("open"); //*********Found********** button.addActionListener(this); saveButton=new JButton("save file"); //*********Found********** saveButton.addActionListener(this); buttonPanel=new JPanel(); buttonPanel.add(button); buttonPanel.add(saveButton); //*********Found********** textArea= new JTextArea("",10,10); //*********Found********** frame.getContentPane().add(buttonPanel,BorderLayout.NORTH); frame.getContentPane().add(textArea,BorderLayout.CENTER); frame.setSize(300,300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } //*********Found********** public void actionPerformed(ActionEvent event) { if(event.getActionCommand().equals("open")) dia.showOpenDialog(frame); else dia.showSaveDialog( frame ); dia.setVisible(true); File file=dia.getSelectedFile(); if (file!=null){ String fileName=file.getAbsolutePath(); textArea.append("path of selected file: "+fileName+"\r\n"); } } public static void main(String args[]){ Java_2 example=new Java_2(); //*********Found********** example.init(); } }
2.39
import javax.swing.*; public class Java_2{ public static void main( String args[] ){ StringBuffer buf = new StringBuffer( "你好!祝你成功!" ); String output = "buf = " + buf.toString() + "\nCharacter at 0: " + buf.charAt( 0 ) + "\nCharacter at 4: " + buf.charAt( 4 ); //*********Found********** char charArray[] = new char[ buf.length() ]; //*********Found********** buf.getChars( 0, buf.length(), charArray, 0 ); output += "\n\n在字符串缓存中的字符是: "; //*********Found********** for ( int i = 0; i < charArray.length; ++i ) output += charArray[ i ]; buf.setCharAt( 0, '您' ); buf.setCharAt( 6, '材' ); //*********Found********** output += "\n\nbuf = " + buf.toString(); buf.reverse( ); output += "\n\nbuf = " + buf.toString(); JOptionPane.showMessageDialog( null, output, "字符串缓存的字符相关方法示范", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } }
2.40
public class Java_2 { public static void main(String[] args) { Person p = new Person("Zhao",20); Student s = new Student("Wang",18,"Cambridge"); System.out.println(p); System.out.println(s); } } class Person { private String name; private int age; public Person(String name, int age) { //*********Found******** this.name= name; //*********Found******** this.age = age; } public void setName(String n) { //*********Found******** name= n; } public String toString() { return "Name: " + name + " Age: " + age; } } class Student extends Person { private String school; public Student(String name, int age, String s) { //*********Found******** super(name,age); school = s; } public String toString() { //*********Found******** return super.toString() + " School: " + school; } }
2.41
import java.io.*; import java.lang.Thread; //**************found***************** class MyThread extends Thread{ public int x = 0; public void run(){ //**************found***************** System.out.println(++x); } } //**************found***************** class R implements Runnable{ private int x = 0; //**************found***************** public void run(){ System.out.println(++x); } } public class Java_2 { public static void main(String[] args) throws Exception{ for(int i=0;i<5;i++){ Thread t = new MyThread(); t.start(); } Thread.sleep(1000); R r = new R(); //**************found***************** for(int i=0;i<5 ;i++){ Thread t = new Thread(r); //**************found***************** t.start(); } } }
2.42
//***************************Found********************* class PrintStrings implements Runnable{ int ind = 0 ; //***************************Found********************* String[] strings = { "one", "two", "three", "four", "five"}; public PrintStrings( int n) { if( n < 0) n = 0; else if ( n >= strings.length) //***************************Found********************* n = strings.length-1 ; ind = n; } //***************************Found********************* public void run( ){ while(ind < strings.length){ System.out.print(strings[ind] + " "); //***************************Found********************* ind++; } System.out.println(); } } public class Java_2{ public static void main(String[] args){ PrintStrings p = new PrintStrings(-1); //***************************Found********************* Thread t = new Thread(p); t.start( ); } }
2.43(*)
//**********found********** public class Java_2 extends Thread { public static void main(String[ ] args) throws Exception{ int i=0; //**********found********** Thread t = new Java_2( ); //**********found********** t.start(); while( true){ System.out.println("Good Morning"+ i++); if (i == 2 && t.isAlive()){ System.out.println("Main waiting for Hello!"); //**********found********** t.join(); //等待线程t运行结束 } //**********found********** if (i==5) break; } } //**********found********** public void run(){ int i =0; while( true){ System.out.println("Hello"+ i++); if (i==5) break ; } } }
2.44
import java.io.*; public class Java_2 { public static void main(String[] args) { try { //**********found********** FileInputStream in = new FileInputStream("in.txt"); FileOutputStream out = new FileOutputStream("out.txt"); BufferedInputStream bufferedIn = new BufferedInputStream(in); //**********found********** BufferedOutputStream bufferedOut = new BufferedOutputStream(out); //**********found********** byte[] data = new byte[1]; //**********found********** while(bufferedIn.read(data) != -1) { bufferedOut.write(data); } bufferedOut.flush(); bufferedIn.close(); //**********found********** bufferedOut.close(); //**********found********** } catch(ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
2.45
import java.lang.*; abstract class Figure { //**********Found********** public abstract double area(); } class Circle extends Figure{ double r; Circle(double r){ this.r=r; } public double area(){ //**********Found********** return Math.PI*r*r; } } class Rectangle extends Figure{ double a,b; Rectangle(double a,double b) { this.a=a; this.b=b; } public double area() { //**********Found********** return a*b; } } public class Java_2 { public static void main(String[] args){ Figure[] fig=new Figure[3]; fig[0]=new Circle(1.0); fig[1]=new Circle(2.0); //**********Found********** fig[2]=new Rectangle(2.0,3.0) ; for(int i=0;i<3;i++) //**********Found********** System.out.println("The area of figure "+i+" is:"+ fig[i].area() ); } }
2.46
//**********Found********** class Account { private float balance = 1000; public float getBalance() { return balance; } public void setBalance(float balance) { this.balance = balance; } public synchronized void withdrawals(float money) { if (balance >= money) { System.out.println("被取走" + money + "元!"); try{ Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } //**********Found********** balance -= money; } else { System.out.println("对不起,余额不足!"); } } } //**********Found********** class TestAccount1 extends Thread { private Account account; public TestAccount1(Account account) { this.account = account; } //**********Found********** public void run() { account.withdrawals(600); System.out.println("余额为:" + account.getBalance() + "元!"); } } //**********Found********** class TestAccount2 extends Thread { private Account account; public TestAccount2(Account account) { this.account = account; } public void run() { account.withdrawals(500); System.out.println("余额为:" + account.getBalance() + "元!"); } } public class Java_2 { public static void main(String[] args) { Account account = new Account(); TestAccount1 testAccount1 = new TestAccount1(account); testAccount1.start(); //**********Found********** TestAccount2 testAccount2 = new TestAccount2(account); testAccount2.start(); } }
2.47
import java.util.*; //**********Found********** class Java_2 extends Thread { String name; //**********Found********** public Java_2( String n) { name = n; } //**********Found********** public static void main(String args[]) throws Exception { int i = 0; //**********Found********** Java_2 t = new Java_2("date" ); t.start(); while( true){ //**********Found********** System.out.println("in main: Hello! "+ t); if (i == 2 && t.isAlive()){ System.out.println("Main waiting for date!"); t.join( ); } //**********Found********** if (i==5) break ; } } public void run() { int i; for (i=0;i<3; i++){ System.out.println("in "+name+": "+new Date()); } } }
2.48(*)
class Mystack { int index=0; private char[] data=new char [10]; //**********Found********** public synchronized void push(char c){ while(index>=10) { try { this.wait(); }catch(InterruptedException e) { e.printStackTrace(); } } this.notifyAll(); //**********Found********** data[index] = c ; index++; } public synchronized char pop(){ while(index<=0) { try { this.wait(); }catch(InterruptedException e) { e.printStackTrace(); } } this.notifyAll(); //**********Found********** index--; return data[index]; } } class PushChar extends Thread { Mystack s; char c; PushChar(Mystack s){ this.s=s; } public void run(){ System.out.println ("start push"); for (int i=0; i<20; i++){ c=(char)(Math.random()*26+'A'); //**********Found********** s.push(c); System.out.println("A:push "+c); } } } class PopChar extends Thread { Mystack s; char c; PopChar(Mystack s){ //**********Found********** this.s=s; } public void run(){ System.out.println ("start pop"); for(int j=0;j<20;j++) { c=s.pop(); System.out.println("B:pop "+c); } } } public class Java_2 { public static void main (String[] args) { //**********Found********** Mystack s=new Mystack(); PushChar a=new PushChar(s); PopChar b=new PopChar(s); a.start(); b.start(); } }
2.49
//**********Found********** class Tree { public void root(){ String sSite = "土壤中"; String sFunction = "吸收养份"; print("位置:"+sSite); print("功能:"+sFunction); } //**********Found********** public void bolo(){ String sSite = "地面"; String sFunction = "传递养份"; print("位置:"+sSite); print("功能:"+sFunction); } public void branch(){ String sSite = "树干上"; String sFunction = "传递养份"; print("位置:"+sSite); print("功能:"+sFunction); } public void leaf(){ String sSite = "树梢"; String sFunction = "光合作用"; String sColor = "绿色"; print("位置:"+sSite); print("功能:"+sFunction); print("颜色:"+sColor); } //**********Found********** public void print(Object oPara){ System.out.println(oPara); } } //**********Found********** class Java_2 extends Tree{ public void leaf(){ super.leaf(); String sShape = "长形"; super.print("形状:"+sShape); } //**********Found********** public void flower(){ print("哈哈,柳树没有花!!"); } public static void main(String[] args){ //**********Found********** Java_2 o = new Java_2(); o.print("柳树树根:"); o.root(); o.print("柳树树干:"); o.bolo(); o.print("柳树树枝:"); o.branch(); o.print("柳树树叶:"); o.leaf(); o.print("柳树花:"); o.flower(); } }
2.50(*)
//**********Found********** class MyException extends Exception { private static final long serialVersionUID = 1L; public MyException() { } public MyException(String msg) { super(msg); } public MyException(String msg, int x) { super(msg); i = x; } //**********Found********** public int val() { return i; } //**********Found********** private int i; } public class Java_2 { //**********Found********** public static void a() throws MyException { System.out.println("Throwing MyException from a()"); throw new MyException(); } public static void b() throws MyException { System.out.println("Throwing MyException from b()"); throw new MyException("Originated in b()"); } public static void c() throws MyException { System.out.println("Throwing MyException from c()"); //**********Found********** throw new MyException("Originated in c()", 47); } public static void main(String[] args) { try { a(); //**********Found********** } catch (MyException e) { e.getMessage(); } try { b(); } catch (MyException e) { e.toString(); } try { c(); } catch (MyException e) { e.printStackTrace(); System.out.println("error code: " + e.val()); } } }
2.51
import java.util.Scanner; import java.io.*; public class Java_2 { int fourthPower(int n) { return n*n*n*n; } int narcissiExt(int fromNum,int number[]) { int i=0; int m=fromNum; int m1=m%10; int m2=(m/10)%10; int m3=(m/100)%10; //**********Found********** int m4 = m/1000; for(m=fromNum;m<=9999;m++) { int sum=fourthPower(m1)+fourthPower(m2)+fourthPower(m3)+fourthPower(m4); //**********Found********** if(m == sum ) { number[i]=m; //**********Found********** ++i; } m1=m1+1; if(m1==10) { m1=0; m2=m2+1; if(m2==10) { //**********Found********** m2 = 0; m3=m3+1; if(m3==10) { m3=0; m4=m4+1; } } } } return i; } public static void main(String[] args) throws Exception{ Scanner input = new Scanner(System.in); System.out.println("Input a number:"); int n = input.nextInt(); input.close(); int[] num= new int [10]; int counter=new Java_2().narcissiExt(n,num); //**********Found********** PrintWriter pw=new PrintWriter ("java_2.txt"); pw.print("There are "+counter+" extended Narcissistic numbers "); pw.println(" >= "+n+". They are:"); for(int i=0;i<counter;i++) { pw.println(num[i]); } //**********Found********** pw.close(); } }
2.52
public class Java_2 { public static void main(String []args) { Shape[] s = new Shape[3]; s[0] = new Circle(5.0); s[1] = new Rectangle(3.0, 4.0); s[2] = new Rectangle(5.0, 6.0); //**********Found********** System.out.println("Total Area = " + Poly.dostuff(s)); } } //**********Found********** abstract class Shape { abstract public double calcArea(); } class Circle extends Shape { private double radius; public Circle(double radius) { //**********Found********** this.radius = radius; } //**********Found********** public double calcArea() { return radius * radius * 3.14; } } class Rectangle extends Shape { private double length, width; public Rectangle(double a, double b) { length = a; width = b; } public double calcArea() { //**********Found********** return length*width ; } } class Poly { static double dostuff(Shape[] s) { double total = 0; for (int i = 0; i < s.length; i++) { //**********Found********** total +=s[i].calcArea(); } return total; } }
2.53
import java.io.*; public class Java_2{ String[] number = new String[5]; String[] name = new String[5]; int[][] grade = new int[5][3]; float[] sum = new float[5]; public static void main(String[] args) throws Exception{ Java_2 student = new Java_2(); student.input(); //**********Found********** student.output(); } void input( ) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ for(int i=0;i<5;i++){ System.out.println("请输入学生学号:"); number[i] = br.readLine(); //**********Found********** System.out.println("请输入第"+(i+1)+"名学生姓名及三门课成绩:"); name[i] = br.readLine(); for(int j=0;j<3;j++){ grade[i][j] = Integer.parseInt( br.readLine() ); } System.out.println(); sum[i] = grade[i][0] + grade[i][1] + grade[i][2]; } }catch(NumberFormatException e){ System.out.println("输入数据有误!"); } } void output( )throws IOException{ //**********Found********** FileWriter fw = new FileWriter("student.txt"); BufferedWriter bw = new BufferedWriter(fw); bw.write("No. "+"name "+"grade 1 "+"grade 2 "+"grade 3 "+"average "); bw.newLine(); for(int i=0;i<5;i++){ bw.write(number[i]); //**********Found********** bw.write(" "+ name[i]); for(int j=0;j<3;j++) bw.write(" "+grade[i][j]); //**********Found********** bw.write(" "+sum[i]/3); bw.newLine(); } //**********Found********** bw.close(); } }
2.54
public class Java_2 { public static void main(String[] args){ Workshop shop; shop = new Workshop(); Thread w1 = new Thread(shop); Thread w2 = new Thread(shop); w1.setName("Worker A"); w2.setName("Worker B"); w1.start(); w2.start(); } } //**********Found********** class Workshop implements Runnable{ //**********Found********** private int products = 0; //**********Found********** public void run( ){ for (int i = 0; i<10; i++){ produce(); //**********Found********** try{ Thread.sleep(2); //**********Found********** }catch(Exception e){ } } } public void produce(){ //**********Found********** synchronized(this){ if(products <10){ products++; System.out.print(Thread.currentThread().getName()); System.out.println( " adds one product, and totally " + products +" products produced."); } } } }