当前位置: 首页 > news >正文

二级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 matrixfor (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]+ "   ");elseSystem.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 DirectoryString 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(){afor(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;elsereturn false;}
}
​

相关文章:

  • 5_springboot_shiro_jwt_多端认证鉴权_禁用Cookie
  • C语言经典面试题目(十九)
  • JSONP漏洞详解
  • 算法——贪心算法
  • Qt文件以及文件夹相关类(QDir、QFile、QFileInfo)的使用
  • 第七节:Vben Admin权限-后端获取路由和菜单
  • 使用Docker在windows上安装IBM MQ
  • Android 辅助功能 -抢红包
  • VUE3生命周期钩子
  • HCIA_IP路由基础问题?
  • SOPHON算能服务器SDK环境配置和相关库安装
  • 【代码】YOLOv8标注信息验证
  • Element UI +Vue页面生成二维码的方法
  • C++_day6:2024/3/18
  • AWS监控,AWS 性能监控工具
  • 【Under-the-hood-ReactJS-Part0】React源码解读
  • JavaScript对象详解
  • JavaSE小实践1:Java爬取斗图网站的所有表情包
  • Java的Interrupt与线程中断
  • Lucene解析 - 基本概念
  • php面试题 汇集2
  • quasar-framework cnodejs社区
  • VirtualBox 安装过程中出现 Running VMs found 错误的解决过程
  • vue--为什么data属性必须是一个函数
  • Vue小说阅读器(仿追书神器)
  • Zsh 开发指南(第十四篇 文件读写)
  • 阿里云ubuntu14.04 Nginx反向代理Nodejs
  • 电商搜索引擎的架构设计和性能优化
  • 分布式任务队列Celery
  • 解决jsp引用其他项目时出现的 cannot be resolved to a type错误
  • 开放才能进步!Angular和Wijmo一起走过的日子
  • 理解在java “”i=i++;”所发生的事情
  • 区块链技术特点之去中心化特性
  • 入手阿里云新服务器的部署NODE
  • 首页查询功能的一次实现过程
  • - 语言经验 - 《c++的高性能内存管理库tcmalloc和jemalloc》
  • Prometheus VS InfluxDB
  • 数据库巡检项
  • # 睡眠3秒_床上这样睡觉的人,睡眠质量多半不好
  • #【QT 5 调试软件后,发布相关:软件生成exe文件 + 文件打包】
  • #QT(一种朴素的计算器实现方法)
  • #微信小程序(布局、渲染层基础知识)
  • (1)(1.13) SiK无线电高级配置(五)
  • (51单片机)第五章-A/D和D/A工作原理-A/D
  • (6)【Python/机器学习/深度学习】Machine-Learning模型与算法应用—使用Adaboost建模及工作环境下的数据分析整理
  • (Git) gitignore基础使用
  • (PyTorch)TCN和RNN/LSTM/GRU结合实现时间序列预测
  • (多级缓存)缓存同步
  • (使用vite搭建vue3项目(vite + vue3 + vue router + pinia + element plus))
  • (已更新)关于Visual Studio 2019安装时VS installer无法下载文件,进度条为0,显示网络有问题的解决办法
  • (转) Face-Resources
  • (转)AS3正则:元子符,元序列,标志,数量表达符
  • (轉貼) VS2005 快捷键 (初級) (.NET) (Visual Studio)
  • .htaccess配置重写url引擎
  • .net framework4与其client profile版本的区别