java概念2

时间:2022-05-06
本文章向大家介绍java概念2,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1 文件操作

 public class FileTest { 
 public static void main(String[] args) throws IOException{ 
        //从硬盘文件到内存,然后从内存中写文件到硬盘另外一个地方,并在屏幕上打印出来。 
        String srcPath="D:\poem.txt"; 
        String desPath="D:\desFile\poem.txt"; 
        File fileSrc=new File(srcPath); 
        InputStream is=new FileInputStream(fileSrc); 
        OutputStream os=new FileOutputStream(desPath); 
 byte buffer[]=new byte[1024]; 
 int count=0; 
        //使用缓存区 
 //     while((count=is.read(buffer))>0){ 
 //         os.write(buffer,0,count); 
 //         System.out.print(count); 
 //     } 
        //不使用缓存区 
 while((count=is.read())>0){ 
            os.write(count); 
            System.out.print((char)count); 
        } 
        os.close(); 
        is.close(); 
        System.out.println(); 
        //从键盘输入内容保存到文件里面,并在屏幕上打印出来。 
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
        BufferedWriter bw=new BufferedWriter(new FileWriter("D:\desFile\shuchu.txt")); 
        String str=br.readLine(); 
 while(!str.equals("exit")){ 
            bw.write(str); 
            bw.newLine(); 
            bw.flush(); 
            str=br.readLine(); 
        } 
        br.close(); 
        bw.close(); 
     } 
 } 

2 线程实现

 //该程序有两个线程,其多个线程运行的顺序和程序代码的顺序无关,写在后面的线程也可能先运行 
 public class XianCheng2{ 
     public static void main(String args[]) 
     { 
        Runner1 r=new Runner1();//新建一个线程t的操作 
        Thread t=new Thread(r); 
        t.start();//线程启动 
        for(int i=0;i<100;i++)//主线程main的操作 
     System.out.println("Main thread ---------- "+i); 
     } 
 } 
 class Runner1 implements Runnable{ 
     public void run()//线程实体 
     { 
        for(int i=0;i<100;i++) 
        System.out.println("Runner1 thread : "+i); 
     } 
 }   

3 异步操作

 public class TestSync implements Runnable { 
   Timer timer = new Timer(); 
   public static void main(String[] args) { 
     TestSync test = new TestSync(); 
     Thread t1 = new Thread(test); 
     Thread t2 = new Thread(test); 
     t1.setName("t1"); 
     t2.setName("t2"); 
     t1.start(); 
     t2.start(); 
   } 
   public void run(){ 
     timer.add(Thread.currentThread().getName()); 
   } 
 } 
 class Timer{ 
   private static int num = 0; 
   public synchronized void add(String name){ 
     //synchronized (this) { 
         num ++; 
         try {Thread.sleep(1);} 
         catch (InterruptedException e) {} 
         System.out.println(name+", 你是第"+num+"个使用timer的线程"); 
       //} 
   } 
 } 

4 网络编程

TcpServer端

 import java.net.*; 
 import java.io.*; 
 public class TCPServer { 
     public static void main(String[] args) throws Exception { 
        ServerSocket ss = new ServerSocket(6666); 
        while(true) { 
            Socket s = ss.accept(); 
 System.out.println("a client connect!"); 
            DataInputStream dis = new DataInputStream(s.getInputStream()); 
            System.out.println(dis.readUTF()); 
            dis.close(); 
            s.close(); 
        } 
     } 
 } 

TcpClient端

 import java.net.*; 
 import java.io.*; 
 public class TCPClient { 
     public static void main(String[] args) throws Exception { 
        Socket s = new Socket("127.0.0.1", 6666); 
        OutputStream os = s.getOutputStream(); 
        DataOutputStream dos = new DataOutputStream(os); 
        Thread.sleep(30000); 
        dos.writeUTF("hello server!"); 
        dos.flush(); 
        dos.close(); 
        s.close(); 
     } 
 } 

UdpServer端

 import java.net.*; 
 import java.io.*; 
 public class TestUDPServer 
 { 
     public static void main(String args[]) throws Exception 
     { 
        byte buf[] = new byte[1024]; 
        DatagramPacket dp = new DatagramPacket(buf, buf.length); 
        DatagramSocket ds = new DatagramSocket(5678); 
        while(true) 
        { 
            ds.receive(dp); 
            ByteArrayInputStream bais = new ByteArrayInputStream(buf); 
            DataInputStream dis = new DataInputStream(bais); 
            System.out.println(dis.readLong()); 
        } 
     } 
 } 

UdpClient端

 import java.net.*; 
 import java.io.*; 
 public class TestUDPClient 
 { 
     public static void main(String args[]) throws Exception 
     { 
        long n =10000L; 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
        DataOutputStream dos = new DataOutputStream(baos); 
        dos.writeLong(n); 
        byte[] buf = baos.toByteArray(); 
 System.out.println(buf.length); 
        DatagramPacket dp = new DatagramPacket(buf, buf.length, 
                                           new InetSocketAddress("127.0.0.1", 5678) 
                                           ); 
        DatagramSocket ds = new DatagramSocket(9999); 
        ds.send(dp); 
        ds.close(); 
     } 
 } 

5 Java经典练习题

2.1 斐波那契数列

2.1.1题目:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

2.1.2源程序

 public class Fibonacci { 
 public static final int MONTH = 15; 
 public static void main(String[] args) { 
 long f1 =1L, f2 =1L; 
 long f; 
 for (int i = 3; i < MONTH; i++) { 
            f = f2; 
            f2 = f1 + f2; 
            f1 = f; 
            System.out.print("第" + i + "个月的兔子对数: "); 
            System.out.println(" " + f2); 
        } 
     } 
 } 

2.1.4源程序揭秘

    斐波那契数列公式

2.2 判断素数

2.2.1题目:判断101-200之间有多少个素数,并输出所有素数。 2.2.2 源程序

 public class Prime { 
 public static int count = 0; 
 public static void main(String[] args) { 
 for (int i = 101; i < 200; i++) { 
 boolean b = true;// 默认此数就素数 
 for (int j = 2; j <= Math.sqrt(i); j++) { 
 if (i % j == 0) { 
                   b = false; // 此数不是素数 
 break; 
               } 
            } 
 if (b) { 
 count++; 
               System.out.print(i + " "); 
            } 
        } 
        System.out.println("n素数的个数:" + count); 
     } 
 } 

2.2.3运行结果:

101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199

素数的个数:21

2.2.4源程序揭秘

    判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数。

2.3 水仙花数

2.3.1题目:打印出所有的"水仙花数(narcissus number)",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。 2.3.2 源程序

 public class shuixian { 
 static int b, bb, bbb; 
 public static void main(String[] args) { 
 for (int num = 101; num < 1000; num++) { 
            shuixian tnn = new shuixian(); 
            tnn.f(num); 
        } 
     } 
 public void f(int m) { 
 bbb = m / 100; 
 bb = (m % 100) / 10; 
 b = (m % 100) % 10; 
 if ((bbb * bbb * bbb + bb * bb * bb + b * b * b) == m) { 
            System.out.println(m); 
        } 
     } 
 } 

2.3.3运行结果:

153

370

371

407

2.3.4源程序揭秘

    利用for循环控制100-999个数,每个数分解出个位,十位,百位。

2.4 分解质因数

2.4.1题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 2.4.2 源程序

 import java.util.Scanner; 
 public class ZhiYinShu { 
 static int n, k = 2; 
 public static void main(String[] args) { 
        Scanner s = new Scanner(System.in); 
 n = s.nextInt(); 
        System.out.print(n + "="); 
        ZhiYinShu fpf = new ZhiYinShu(); 
        fpf.f(n); 
     } 
 public void f(int n) { 
 while (k <= n) { 
 if (k == n) { 
               System.out.println(n); 
 break; 
            } else if (n > k && n % k == 0) { 
               System.out.print(k + "*"); 
               n = n / k; 
               f(n); 
 break; 
            } else if (n > k && n % k != 0) { 
 k++; 
               f(n); 
 break; 
            } 
        } 
     } 
 } 

2.4.3运行结果:

200

200=2*2*2*5*5

2.4.4源程序揭秘

    对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:     (1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。     (2)如果n>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数你n,重复执行第一步。     (3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。

2.5 杨辉三角

2.5.1题目:打印出杨辉三角形(要求打印出10行如下图)         1         1 1        1 2 1        1 3 3 1       1 4 6 4 1      1 5 10 10 5 1

2.5.2源程序

 public class YangHuiSanJiao { 
 public static void main(String[] args) { 
 int[][] a = new int[10][10]; 
 for (int i = 0; i < 10; i++) { 
            a[i][i] = 1; 
            a[i][0] = 1; 
        } 
 for (int i = 2; i < 10; i++) { 
 for (int j = 1; j < i; j++) { 
               a[i][j] = a[i - 1][j - 1] + a[i - 1][j]; 
            } 
        } 
 for (int i = 0; i < 10; i++) { 
 for (int k = 0; k < 2 * (10 - i) - 1; k++) { 
               System.out.print(" "); 
            } 
 for (int j = 0; j <= i; j++) { 
               System.out.print(a[i][j] + "   "); 
            } 
            System.out.println(); 
        } 
     } 
 } 

2.5.3运行结果:

                   1  

                 1   1  

               1   2   1  

             1   3   3   1  

           1   4   6   4   1  

         1   5   10   10   5   1  

       1   6   15   20   15   6   1  

     1   7   21   35   35   21   7   1  

   1   8   28   56   70   56   28   8   1  

 1   9   36   84   126   126   84   36   9   1  

2.5.4源程序揭秘

    杨辉三角形性质:

        每行数字左右对称,由1开始逐渐变大,然后变小,回到1。  

        第n行的数字个数为n个。  

        第n行数字和为2^(n-1)。  

        每个数字等于上一行的左右两个数字之和。可用此性质写出整个杨辉三角形。   

        第n行的第1个数为1,第二个数为1×(n-1),第三个数为1×(n-1)×(n-2)/2,第四个数为1×(n-1)×(n-2)/2×(n-3)/3…依此类推。  

    算法原理:

        使用一个二维数组yh[][]存储杨辉三角形的数据,行和列的大小为所需要输出的行数Row(本程序中Row为10)。

        使用for循环使杨辉三角中除了最外层(不包括杨辉三角底边)的数为1 ;

        使用语句yh[i][j] = yh[i - 1][j - 1] + yh[i - 1][j]使第i行第j列的数据等于第(i-1)行第(j-1)列的数据与第(i-1)行第(j)列的数据之和,即每个数字等于上一行的左右两个数字之和。

2.6 学习成绩查询

2.6.1题目:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。

2.3.2源程序

 import java.util.Scanner; 
 public class ChaXun { 
 static int grade; 
 public static void main(String[] args) { 
        Scanner str = new Scanner(System.in); 
 int s = str.nextInt(); 
        ChaXun fc = new ChaXun(); 
 grade = fc.compare(s); 
 if (grade == 1) { 
            System.out.print('A'); 
        } else if (grade == 2) { 
            System.out.print('B'); 
        } else { 
            System.out.println('C'); 
        } 
     } 
 public int compare(int s) { 
 return s > 90 ? 1 : s > 60 ? 2 : 3; 
     } 
 } 

2.6.3运行结果:

90

B

2.6.4源程序揭秘

    利用(a>b)?a:b条件运算符来处理。

2.7 求最大公约数与最小公倍数

2.7.1题目:输入两个正整数m和n,求其最大公约数和最小公倍数。 2.7.2 源程序

 import java.util.Scanner; 
 public class YueBei { 
 public static void main(String[] args) { 
 int a, b; 
        Scanner s1 = new Scanner(System.in); 
        Scanner s2 = new Scanner(System.in); 
        a = s1.nextInt(); 
        b = s2.nextInt(); 
        YueBei scd = new YueBei(); 
 int m = scd.division(a, b); 
 int n = a * b / m; 
        System.out.println("最大公约数: " + m); 
        System.out.println("最小公倍数: " + n); 
     } 
 public int division(int x, int y) { 
 int t; 
 if (x < y) { 
            t = x; 
            x = y; 
            y = t; 
        } 
 while (y != 0) { 
 if (x == y) 
 return 1; 
 else { 
 int k = x % y; 
               x = y; 
               y = k; 
            } 
        } 
 return x; 
     } 
 } 

2.7.3运行结果:

56

78

最大公约数: 2

最小公倍数: 2184

2.7.4源程序揭秘

    在循环中,只要除数不等于0,用较大数除以较小的数,将小的一个数作为下一轮循环的大数,取得的余数作为下一轮循环的较小的数,如此循环直到较小的数的值为0,返回较大的数,此数即为最小公约数,最小公倍数为两数之积除以最小公倍数。

2.8 完全平方数

2.8.1题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少? 2.8.2 源程序

 public class WanQuan { 
 public static void main(String[] args) { 
 for (long l =1L; l < 100000; l++) { 
 if (Math.sqrt((long) (l + 100)) % 1 == 0) { 
 if (Math.sqrt((long) (l + 268)) % 1 == 0) { 
                   System.out.println(l + "加100是一个完全平方数,再加168又是一个完全平方数"); 
               } 
            } 
        } 
     } 
 } 

2.8.3运行结果:

21加100是一个完全平方数,再加168又是一个完全平方数

261加100是一个完全平方数,再加168又是一个完全平方数

1581加100是一个完全平方数,再加168又是一个完全平方数

2.8.4源程序揭秘

    在10万以内判断,先将该数加上100后再开方,再将该数加上268后再开方,如果开方后的结果满足如下条件,即是结果。

2.9 统计字母、空格、数字和其它字符个数

2.9.1题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 2.9.2 源程序

 import java.util.*; 
 public class Number { 
 static int digital = 0; 
 static int character = 0; 
 static int other = 0; 
 static int blank = 0; 
 public static void main(String[] args) { 
 char[] ch = null; 
        Scanner sc = new Scanner(System.in); 
        String s = sc.nextLine(); 
        ch = s.toCharArray(); 
 for (int i = 0; i < ch.length; i++) { 
 if (ch[i] >= '0' && ch[i] <= '9') { 
 digital++; 
            } else if ((ch[i] >= 'a' && ch[i] <= 'z') || ch[i] > 'A' 
                   && ch[i] <= 'Z') { 
 character++; 
            } else if (ch[i] == ' ') { 
 blank++; 
            } else { 
 other++; 
            } 
        } 
        System.out.println("数字个数: " + digital); 
        System.out.println("英文字母个数: " + character); 
        System.out.println("空格个数: " + blank); 
        System.out.println("其他字符个数:" + other); 
     } 
 } 

2.9.3运行结果:

sadf239  asl!~@#*(#)

数字个数: 3

英文字母个数: 7

空格个数: 2

其他字符个数:8

2.9.4源程序揭秘

    利用while语句,条件为输入的字符不为 'n '。

2.10 求主对角线之和

2.10.1题目:求一个3*3矩阵对角线元素之和。

2.10.2源程序

 import java.util.Scanner; 
 public class DuiJiaoXian { 
 public static void main(String[] args) { 
        Scanner s = new Scanner(System.in); 
 int[][] a = new int[3][3]; 
 for (int i = 0; i < 3; i++) { 
 for (int j = 0; j < 3; j++) { 
               a[i][j] = s.nextInt(); 
            } 
        } 
        System.out.println("输入的3 * 3 矩阵是:"); 
 for (int i = 0; i < 3; i++) { 
 for (int j = 0; j < 3; j++) { 
               System.out.print(a[i][j] + " "); 
            } 
            System.out.println(); 
        } 
 int sum = 0; 
 for (int i = 0; i < 3; i++) { 
 for (int j = 0; j < 3; j++) { 
 if (i == j) { 
                   sum += a[i][j]; 
               } 
            } 
        } 
        System.out.println("对角线和是 " + sum); 
     } 
 } 

2.10.3运行结果:

2 3 4 5

34 4 56 67

12 34 5 6

输入的3 * 3 矩阵是:

2 3 4

5 34 4

56 67 12

对角线和是 48

2.10.4源程序揭秘

    利用双重for循环控制输入二维数组,再将a[i][i]累加后输出。

2.11 完数求解

2.11.1题目:一个数如果恰好等于它的因子之和,这个数就称为 "完数 "。例如6=1+2+3.编程 找出1000以内的所有完数。 2.11.2 源程序

 public class WanShu { 
 public static void main(String[] args) { 
        System.out.println("1到1000的完数有: "); 
 for (int i = 1; i < 1000; i++) { 
 int t = 0; 
 for (int j = 1; j <= i / 2; j++) { 
 if (i % j == 0) { 
                   t = t + j; 
               } 
            } 
 if (t == i) { 
               System.out.print(i + " "); 
            } 
        } 
     } 
 } 

2.11.3运行结果:

1到1000的完数有:

6 28 496

2.12 求s=a+aa+aaa+aaaa+aa...a的值

2.12.1题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有键盘控制。 2.12.2 源程序

 import java.util.Scanner; 
 public class DuoXun { 
 static long a = 2, b = 0; 
 public static void main(String[] args) { 
        Scanner s = new Scanner(System.in); 
 int n = s.nextInt(); 
 int i = 0; 
 long sum = 0; 
 while (i < n) { 
 b = b + a; 
            sum = sum + b; 
 a = a * 10; 
            ++i; 
        } 
        System.out.println("input number: " + n); 
        System.out.println(sum); 
     } 
 } 

2.12.3运行结果:

60

input number: 60

2334310206858307444

2.12.4源程序揭秘

    定义一个变量b, 赋初值为0;定义一变量sum, 赋初值为0,进入循环后,将a + b 的值赋给b,将sum + b 的值赋给sum;同时,将a 增加十倍, ++ i; 继续循环;循环结束后,输出sum 的值。

2.13 高度计算

2.13.1题目:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下, 求它在 第10次落地时,共经过多少米?第10次反弹多高?

2.13.2源程序

 public class HighComput { 
 static double height = 100; 
 static double distance = 100; 
 public static void main(String[] args) { 
 for (int i = 1; i < 10; i++) { 
 distance = distance + height; 
 height = height / 2; 
        } 
        System.out.println("路程:" + distance); 
        System.out.println("高度:" + height / 2); 
     } 
 } 

2.13.3运行结果:

路程:299.609375

高度:0.09765625

2.14 乘法口诀

2.14.1题目:输出9*9口诀。 2.14.2 源程序

 public class KouJue { 
 public static void main(String[] args) { 
 for (int i = 1; i < 10; i++) { 
 for (int j = 1; j <= i; j++) { 
               System.out.print(j + "*" + i + "=" + j * i + " "); 
            } 
            System.out.println(); 
        } 
     } 
 } 

2.14.3运行结果:

1*1=1

1*2=2 2*2=4

1*3=3 2*3=6 3*3=9

1*4=4 2*4=8 3*4=12 4*4=16

1*5=5 2*5=10 3*5=15 4*5=20 5*5=25

1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36

1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49

1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64

1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81

2.14.4源程序揭秘

    分行与列考虑,共9行9列,i控制行,j控制列。

2.15 无重复三位数

2.4.1题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? 2.15.2 源程序

 public class NoChFu { 
 public static void main(String[] args) { 
 int count = 0; 
 for (int x = 1; x < 5; x++) { 
 for (int y = 1; y < 5; y++) { 
 for (int z = 1; z < 5; z++) { 
 if (x != y && y != z && x != z) { 
                      count++; 
                      System.out.print(x * 100 + y * 10 + z + "   "); 
 if (count % 4 == 0) { 
                          System.out.println(); 
                      } 
                   } 
               } 
            } 
        } 
        System.out.println("共有" + count + "个三位数"); 
     } 
 } 

2.15.3运行结果:

123   124   132   134  

142   143   213   214  

231   234   241   243  

312   314   321   324  

341   342   412   413  

421   423   431   432  

共有24个三位数

2.15.4源程序揭秘

    可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去掉不满足条件的排列。

2.16 菱形打印

2.16.1题目:打印出如下图案(菱形)    *    ***   *****   *******   *****    ***    *

2.16.2源程序

 public class LingXing { 
 static final int HEIGHT = 7; 
 static final int WIDTH = 8; 
 public static void main(String[] args) { 
 for (int i = 0; i < (HEIGHT + 1) / 2; i++) { 
 for (int j = 1; j < WIDTH / 2 - i; j++) { 
               System.out.print(" "); 
            } 
 for (int k = 1; k < (i + 1) * 2; k++) { 
               System.out.print('*'); 
            } 
            System.out.println(); 
        } 
 for (int i = 1; i <= HEIGHT / 2; i++) { 
 for (int j = 1; j <= i; j++) { 
               System.out.print(" "); 
            } 
 for (int k = 1; k <= WIDTH - 2 * i - 1; k++) { 
               System.out.print('*'); 
            } 
            System.out.println(); 
        } 
     } 
 } 

2.16.3运行结果:

   *

  ***

 *****

*******

 *****

  ***

   *

2.16.4源程序揭秘

    先把图形分成两部分来看待,前四行一个规律,后三行一个规律,利用双重 for循环,第一层控制行,第二层控制列。

2.17 利润计算

2.17.1题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%; 利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分, 可可提成7.5%;20万到40万之间时,高于20万元的部分, 可提成5%;40万到60万之间时高于40万元的部分,可提成3%; 60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成, 从键盘输入当月利润I,求应发放奖金总数? 2.17.2 源程序

 import java.text.DecimalFormat; 
 import java.util.*; 
 public class LiRun { 
 static double profit = 0; 
 static double award = 0; 
 public static void main(String[] args) { 
        Scanner s = new Scanner(System.in); 
 profit = s.nextInt(); 
        System.out.println("输入的利润是" + profit + "万"); 
 if (profit > 0 && profit <= 10) { 
 award = profit * 0.1; 
        } else if (profit > 10 && profit <= 20) { 
 award = 10 * 0.1 + (profit - 10) * 0.075; 
        } else if (profit > 20 && profit <= 40) { 
 award = 10 * 0.1 + 10 * 0.075 + (profit - 20) * 0.05; 
        } else if (profit > 40 && profit <= 60) { 
 award = 10 * 0.1 + 10 * 0.075 + 20 * 0.05 + (profit - 40) * 0.03; 
        } else if (profit > 60 && profit <= 100) { 
 award = 20 * 0.175 + 20 * 0.05 + 20 * 0.03 + (profit - 60) * 0.015; 
        } else if (profit > 100) { 
 award = 20 * 0.175 + 40 * 0.08 + 40 * 0.015 + (profit - 100) * 0.01; 
        } 
        DecimalFormat df = new DecimalFormat("#0.00000"); 
        System.out.println("应该提取的奖金是 " + df.format(award) + "万"); 
     } 
 } 

2.17.3运行结果:

78

输入的利润是78.0万

应该提取的奖金是 5.37000万

2.17.4源程序揭秘

用数轴来分界,定位。注意定义时需把奖金定义成长整型。 注意: 要精确到小数点后多少位,用 DecimalFormat df = new DecimalFormat("#0.0000");

2.18 第几天判断

2.18.1题目:输入某年某月某日,判断这一天是这一年的第几天?

2.18.2源程序

 import java.util.Scanner; 
 import java.io.*; 
 public class TianShu { 
 public static void main(String[] args) { 
 int year, month, day; 
 int days = 0; 
 int d = 0; 
        TianShu fymd = new TianShu(); 
        System.out.print("Input the year:"); 
        year = fymd.input(); 
        System.out.print("Input the month:"); 
        month = fymd.input(); 
        System.out.print("Input The Day:"); 
        day = fymd.input(); 
 if (year < 0 || month < 0 || month > 12 || day < 0 || day > 31) { 
            System.out.println("Input error, please run this program again!"); 
            System.exit(0); 
        } 
 for (int i = 1; i < month; i++) { 
 switch (i) { 
 case 1: 
 case 3: 
 case 5: 
 case 7: 
 case 8: 
 case 10: 
 case 12: 
               days = 31; 
               // d += days; 
 break; 
 case 4: 
 case 6: 
 case 9: 
 case 11: 
               days = 30; 
               // d += days; 
 break; 
 case 2: 
 if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) { 
                   days = 29; 
               } else { 
                   days = 28; 
               } 
               // d += days; 
 break; 
            } 
            d += days; 
        } 
        System.out.println(year + ":" + month + ":" + day + "是今年的第" + (d + day) 
               + "天。"); 
     } 
 public int input() { 
 int value = 0; 
        Scanner s = new Scanner(System.in); 
        value = s.nextInt(); 
 return value; 
     } 
 } 

2.18.3运行结果:

Input the year:2011

Input the month:4

Input The Day:26

2011:4:26是今年的第116天。

2.18.4源程序揭秘

    以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。

2.19 从小到大输出数列

2.19.1题目:输入三个整数x,y,z,请把这三个数由小到大输出。

2.19.2源程序

 import java.util.*; 
 public class SmallToBig { 
 public static void main(String[] args) { 
        SmallToBig fnc = new SmallToBig(); 
 int a, b, c; 
        System.out.println("Input 3 numbers:"); 
        a = fnc.input(); 
        b = fnc.input(); 
        c = fnc.input(); 
 if (a > b) { 
 int t = a; 
            a = b; 
            b = t; 
        } 
 if (a > c) { 
 int t = a; 
            a = c; 
            c = t; 
        } 
 if (b > c) { 
 int t = b; 
            b = c; 
            c = t; 
        } 
        System.out.println(a + " " + b + " " + c); 
     } 
 public int input() { 
 int value = 0; 
        Scanner s = new Scanner(System.in); 
        value = s.nextInt(); 
 return value; 
     } 
 public void compare(int x, int y) {// 此方法没用 
 if (x > y) { 
 int t = x; 
            x = y; 
            y = t; 
        } 
     } 
 } 

2.19.3运行结果:

Input 3 numbers:

100

20

40

20 40 100

2.19.4源程序揭秘

    我们想办法把最小的数放到x上,先将x与y进行比较,如果x> y则将x与y的值进行交换,然后再用x与z进行比较,如果x> z则将x与z的值进行交换,这样能使x最小。

2.20 猴子吃桃问题

2.20.1题目:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个 第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下 的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。 2.20.2 源程序

 public class Monkey { 
 public static void main(String[] args) { 
 int lastdayNum = 1; 
 for (int i = 2; i <= 10; i++) { 
            lastdayNum = (lastdayNum + 1) * 2; 
        } 
        System.out.println("猴子第一天摘了 " + lastdayNum + " 个桃子"); 
     } 
 } 

2.20.3运行结果:

猴子第一天摘了 1534 个桃子

2.20.4源程序揭秘

    采取逆向思维的方法,从后往前推断。

2.21 乒乓球比赛

2.21.1题目:两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。 2.21.2 源程序

 public class Compete { 
 static char[] m = { 'a', 'b', 'c' }; 
 static char[] n = { 'x', 'y', 'z' }; 
 public static void main(String[] args) { 
 for (int i = 0; i < m.length; i++) { 
 for (int j = 0; j < n.length; j++) { 
 if (m[i] == 'a' && n[j] == 'x') { 
 continue; 
               } else if (m[i] == 'a' && n[j] == 'y') { 
 continue; 
               } else if ((m[i] == 'c' && n[j] == 'x') 
                      || (m[i] == 'c' && n[j] == 'z')) { 
 continue; 
               } else if ((m[i] == 'b' && n[j] == 'z') 
                      || (m[i] == 'b' && n[j] == 'y')) { 
 continue; 
               } else 
                   System.out.println(m[i] + " vs " + n[j]); 
            } 
        } 
     } 
 } 

2.21.3运行结果:

a vs z

b vs x

c vs y

2.22 求分数之和

2.22.1题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。

2.3.2源程序

 import java.text.DecimalFormat; 
 public class FenShu { 
 public static void main(String[] args) { 
 int x = 2, y = 1, t; 
 double sum = 0; 
        DecimalFormat df = new DecimalFormat("#0.0000"); 
 for (int i = 1; i <= 20; i++) { 
            sum += (double) x / y; 
            t = y; 
            y = x; 
            x = y + t; 
            System.out.println("第 " + i + " 次相加,和是 " + df.format(sum)); 
        } 
     } 
 } 

2.22.4源程序揭秘

    抓住分子与分母的变化规律。

2.23 求阶乘的和

2.23.1题目:求1+2!+3!+...+20!的和 2.23.2 源程序

 public class JieCheng { 
 static long sum = 0; 
 static long fac = 0; 
 public static void main(String[] args) { 
 long sum = 0; 
 long fac = 1; 
 for (int i = 1; i <= 10; i++) { 
            fac = fac * i; 
            sum += fac; 
        } 
        System.out.println(sum); 
     } 
 } 

2.23.3运行结果:

4037913

2.23.4源程序揭秘

    把累加变成了累乘。

2.24 递归求法

2.24.1题目:利用递归方法求5!。 2.24.2 源程序

 import java.util.Scanner; 
 public class DiGui { 
 public static void main(String[] args) { 
        Scanner s = new Scanner(System.in); 
 int n = s.nextInt(); 
        DiGui tfr = new DiGui(); 
        System.out.println(tfr.recursion(n)); 
     } 
 public long recursion(int n) { 
 long value = 0; 
 if (n == 1 || n == 0) { 
            value = 1; 
        } else if (n > 1) { 
            value = n * recursion(n - 1); 
        } 
 return value; 
     } 
 } 

2.24.3运行结果:

12

479001600

2.24.4源程序揭秘

    递归公式:fn = (fn-1)+(fn-2)。

2.25 求不多于5的正整数

2.25.1题目:给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。

2.25.2源程序

 import java.util.Scanner; 
 public class ZhZhShu { 
 public static void main(String[] args) { 
        ZhZhShu tn = new ZhZhShu(); 
        Scanner s = new Scanner(System.in); 
 long a = s.nextLong(); 
 if (a < 0 || a > 100000) { 
            System.out.println("Error Input, please run this program Again"); 
            System.exit(0); 
        } 
 if (a >= 0 && a <= 9) { 
            System.out.println(a + "是一位数"); 
            System.out.println("按逆序输出是" + 'n' + a); 
        } else if (a >= 10 && a <= 99) { 
            System.out.println(a + "是二位数"); 
            System.out.println("按逆序输出是"); 
            tn.converse(a); 
        } else if (a >= 100 && a <= 999) { 
            System.out.println(a + "是三位数"); 
            System.out.println("按逆序输出是"); 
            tn.converse(a); 
        } else if (a >= 1000 && a <= 9999) { 
            System.out.println(a + "是四位数"); 
            System.out.println("按逆序输出是"); 
            tn.converse(a); 
        } else if (a >= 10000 && a <= 99999) { 
            System.out.println(a + "是五位数"); 
            System.out.println("按逆序输出是"); 
            tn.converse(a); 
        } 
     } 
 public void converse(long l) { 
        String s = Long.toString(l); 
 char[] ch = s.toCharArray(); 
 for (int i = ch.length - 1; i >= 0; i--) { 
            System.out.print(ch[i]); 
        } 
     } 
 } 

2.25.3运行结果:

67

67是二位数

按逆序输出是

76

2.26 回文判断

2.26.1题目:一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。 2.26.2 源程序

 import java.util.Scanner; 
 public class HuiWen { 
 public static void main(String[] args) { 
        Scanner s = new Scanner(System.in); 
        System.out.print("请输入一个正整数:"); 
 long a = s.nextLong(); 
        String ss = Long.toString(a); 
 char[] ch = ss.toCharArray(); 
 boolean is = true; 
 int j = ch.length; 
 for (int i = 0; i < j / 2; i++) { 
 if (ch[i] != ch[j - i - 1]) { 
               is = false; 
            } 
        } 
 if (is == true) { 
            System.out.println("这是一个回文数"); 
        } else { 
            System.out.println("这不是一个回文数"); 
        } 
     } 
 } 

2.26.3运行结果:

请输入一个正整数:12345654321

这是一个回文数

2.27 星期判断

2.27.1题目:请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续 判断第二个字母。 2.27.2 源程序

 import java.util.Scanner; 
 public class XingQi { 
     Scanner s = new Scanner(System.in); 
 public static void main(String[] args) { 
        XingQi tw = new XingQi(); 
 char ch = tw.getChar(); 
 switch (ch) { 
 case 'M': 
            System.out.println("Monday"); 
 break; 
 case 'W': 
            System.out.println("Wednesday"); 
 break; 
 case 'F': 
            System.out.println("Friday"); 
 break; 
 case 'T': { 
            System.out.println("please input the second letter!"); 
 char ch2 = tw.getChar(); 
 if (ch2 == 'U') { 
               System.out.println("Tuesday"); 
            } else if (ch2 == 'H') { 
               System.out.println("Thursday"); 
            } 
        } 
            ; 
 break; 
 case 'S': { 
            System.out.println("please input the scecond letter!"); 
 char ch2 = tw.getChar(); 
 if (ch2 == 'U') { 
               System.out.println("Sunday"); 
            } else if (ch2 == 'A') { 
               System.out.println("Saturday"); 
            } 
        } 
            ; 
 break; 
        } 
     } 
 public char getChar() { 
        String str = s.nextLine(); 
 char ch = str.charAt(0); 
 if (ch < 'A' || ch > 'Z') { 
            System.out.println("Input error, please input a capital letter"); 
            getChar(); 
        } 
 return ch; 
     } 
 } 

2.7.3运行结果:

Monday

Monday

2.28 插数入数组

2.28.1题目:有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。

2.28.2源程序

 import java.util.Scanner; 
 public class ChaRu { 
 public static void main(String[] args) { 
 int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7 }; 
 int[] b = new int[a.length + 1]; 
 int t1 = 0, t2 = 0; 
 int i = 0; 
        Scanner s = new Scanner(System.in); 
 int num = s.nextInt(); 
 if (num >= a[a.length - 1]) { 
            b[b.length - 1] = num; 
 for (i = 0; i < a.length; i++) { 
               b[i] = a[i]; 
            } 
        } else { 
 for (i = 0; i < a.length; i++) { 
 if (num >= a[i]) { 
                   b[i] = a[i]; 
               } else { 
                   b[i] = num; 
 break; 
               } 
            } 
 for (int j = i + 1; j < b.length; j++) { 
               b[j] = a[j - 1]; 
            } 
        } 
 for (i = 0; i < b.length; i++) { 
            System.out.print(b[i] + " "); 
        } 
     } 
 } 

2.28.3运行结果:

3

1 2 3 3 4 5 6 7

2.28.4源程序揭秘

    定义两个数组a,b,一个a的长度比另一个b大1,a看做是已经排好序的。接下来的过程是

l         如果num 比最后一个数大,把num赋值给数组b的最后一个数再按顺序把a 的每个元素赋给b

l         否则(num 不比a 的最后一个数大),如果a 的元素比num 小,则将这些元素按顺序赋给b,将num 赋给比num大的b数组的元素,跳出第一个for循环。

l         定义一个循环控制变量,从num传给数组后num的下标值加一开始;直到b的结尾,将剩下的a 的值赋给b,赋值的过程是b[j] = a[i-1]。

2.29 取整数的任意位

2.29.1题目:取一个整数a从右端开始的4~7位。

 import java.util.Scanner; 
 public class QuWei { 
 public static void main(String[] args) { 
        Scanner s = new Scanner(System.in); 
 boolean is = true; 
        System.out.print("请输入一个7位以上的正整数:"); 
 long a = s.nextLong(); 
        String ss = Long.toString(a); 
 char[] ch = ss.toCharArray(); 
 int j = ch.length; 
 if (j < 7) { 
            System.out.println("输入错误!"); 
        } else { 
            System.out.println("截取从右端开始的4~7位是:" + ch[j - 7] + ch[j - 6] 
                   + ch[j - 5] + ch[j - 4]); 
        } 
     } 
 } 

2.30 按顺序输出数列

2.30.1题目:输入3个数a,b,c,按大小顺序输出

 import java.util.Scanner; 
 public class ShunXu { 
 public static void main(String[] args) { 
        Scanner s = new Scanner(System.in); 
 int a = s.nextInt(); 
 int b = s.nextInt(); 
 int c = s.nextInt(); 
 if (a < b) { 
 int t = a; 
            a = b; 
            b = t; 
        } 
 if (a < c) { 
 int t = a; 
            a = c; 
            c = t; 
        } 
 if (b < c) { 
 int t = b; 
            b = c; 
            c = t; 
        } 
        System.out.println("从大到小的顺序输出:"); 
        System.out.println(a + " " + b + " " + c); 
     } 
 } 

2.31 位置替换

2.31.1题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。

 import java.util.Scanner; 
 public class TiHuan { 
 static final int N = 8; 
 public static void main(String[] args) { 
 int[] a = new int[N]; 
        Scanner s = new Scanner(System.in); 
 int index1 = 0, index2 = 0; 
        System.out.println("please input numbers"); 
 for (int i = 0; i < N; i++) { 
            a[i] = s.nextInt(); 
            System.out.print(a[i] + " "); 
        } 
 int max = a[0], min = a[0]; 
 for (int i = 0; i < a.length; i++) { 
 if (a[i] > max) { 
               max = a[i]; 
               index1 = i; 
            } 
 if (a[i] < min) { 
               min = a[i]; 
               index2 = i; 
            } 
        } 
 if (index1 != 0) { 
 int temp = a[0]; 
            a[0] = a[index1]; 
            a[index1] = temp; 
        } 
 if (index2 != a.length - 1) { 
 int temp = a[a.length - 1]; 
            a[a.length - 1] = a[index2]; 
            a[index2] = temp; 
        } 
        System.out.println("after swop:"); 
 for (int i = 0; i < a.length; i++) { 
            System.out.print(a[i] + " "); 
        } 
     } 
 } 

2.32 字符串排序

2.32.1题目:字符串排序。

 public class StringSort { 
 public static void main(String[] args) { 
        String temp = null; 
        String[] s = new String[5]; 
        s[0] = "china".toLowerCase(); 
        s[1] = "apple".toLowerCase(); 
        s[2] = "MONEY".toLowerCase(); 
        s[3] = "BOOk".toLowerCase(); 
        s[4] = "yeah".toLowerCase(); 
        /* 
         * for(int i=0; i<s.length; i++) { for(int j=i+1; j<s.length; j++) { 
         * if(s[i].compareToIgnoreCase(s[j]) > 0) { temp = s[i]; s[i] = s[j]; 
         * s[j] = temp; } } } 
         */ 
 for (int i = 0; i < s.length; i++) { 
 for (int j = i + 1; j < s.length; j++) { 
 if (compare(s[i], s[j]) == false) { 
                   temp = s[i]; 
                   s[i] = s[j]; 
                   s[j] = temp; 
               } 
            } 
        } 
 for (int i = 0; i < s.length; i++) { 
            System.out.println(s[i]); 
        } 
     } 
 static boolean compare(String s1, String s2) { 
 boolean result = true; 
 for (int i = 0; i < s1.length() && i < s2.length(); i++) { 
 if (s1.charAt(i) > s2.charAt(i)) { 
               result = false; 
 break; 
            } else if (s1.charAt(i) < s2.charAt(i)) { 
               result = true; 
 break; 
            } else { 
 if (s1.length() < s2.length()) { 
                   result = true; 
               } else { 
                   result = false; 
               } 
            } 
        } 
 return result; 
     } 
 } 

6 冒泡排序

 public class BubbleSort{ 
 private static void BubbleSort(int [] a){ 
        //接受数组作为参数,数组传递的是地址,因此直接修改数组内的数据 
 for(int i = 0; i < a.length-1; i++){ 
            //外循环,循环的次数为数组的长度 
 for(int j = 0; j < a.length-i-1;j++){ 
               //内循环,一次对相邻的两个元素进行比较,并通过temp值将两个数据按照要求排放 
 if(a[j+1]<a[j]){ 
 int temp = a[j];//交换数据 
                   a[j] = a[j+1]; 
                   a[j+1] = temp; 
               } 
            } 
        } 
     } 
 public static void main(String[] args) { 
 int[] test1 = { 49, 38, 65, 97, 76, 13, 27 }; // 测试数组 
        Example1_3.BubbleSort(test1); 
 for (int i = 0; i < test1.length; i++) { 
            System.out.print(test1[i] + " "); 
        } 
     } 
 } 

7 选择排序

 public class ChooseSort { 
 private static void ChooseSort (int [] a){ 
 for(int i = 0; i < a.length; i++){ 
            //对数组循环,假设数据排在前面的元素总比后面的小,然后与后面的数据进行比较 
 int k = i; 
 for(int j = i+1; j <a.length; j++){//对数据遍历,寻找最小的数据元素的数组下标 
 if(a[j]<a[k]) 
                   k = j; 
            } 
            //最少值与a[i]交换 
 if(i != k){ 
            //对i和k进行比较,如果不相等,则i和j下标表示的元素不是同一个元素,则交换a[i],a[k]的值,保证最小值总在最前面 
 int temp = a[i]; 
               a[i] = a[k]; 
               a[k] = temp; 
            } 
        } 
     } 
 public static void main(String[] args) { 
 int[] test1 = { 51, 38, 49, 27, 62, 5, 16  }; // 测试数组 
 chooseSort(test1); 
 for (int i = 0; i < test1.length; i++) { 
            System.out.print(test1[i] + " "); 
        } 
     } 
 } 

8 插入排序

 public class SortAscending { 
 public SortAscending () { 
        System.out.println("直接插入排序法"); 
     } 
 public static int[] sortAscending(int[] with) { // 直接插入法递增排序 
 int length = with.length;                 // 待排数组的长度 
 int[] temp = new int[length];             //建立一个新的数组用于存放排序结果 
        temp[0] = with[0];                        //初始化temp数组的元素为with[0] 
 for (int i = 1; i < length; i++) {        //遍历with数组 
 for (int j = i - 1; j >= 0; j--) { 
 if (with[i] >= temp[j]) {          // 如果待排序列中的元素大于等于有有序序列中的元素,则插入 
                   temp[j + 1] = with[i]; 
 break; 
               } else { 
                   temp[j + 1] = temp[j];          
                   // 如果遍历到的元素小于已存在temp中的数组,则预留空间,在内循环的下次遍历中会temp[j]的空间会被with[i]填充,或者继续向前预留空间 
 if (j == 0) 
                      temp[j] = with[i]; // with[[i]是有序序列中最小的,因此排在开头 
               } 
            } 
        } 
 return temp; 
     } 
 public static void main(String[] args) { 
 int[] test1 = { 49  38  65  97  76  13  27  49 }; // 测试数组 
 int[] temp1; // 中间变量 
        temp1 = sortAscending(test1); 
 for (int i = 0; i < temp1.length; i++) { 
            System.out.print(temp1[i] + " "); 
        } 
     } 
 } 

9 快速排序

 public class QuickSort { 
 private static void QuickSort(int[] a, int low, int high) { 
        // 该方法接受三个参数,分别为待排序的数组,数组的低端下标,数组的高端下标 
 int i, j, temp; 
        // 定义变量temp,作为标准数据元素 
 if (low < high) { 
            i = low; 
            j = high; 
            temp = a[i]; 
            // temp作为标准数据元素 
 while (i < j) { 
 while (i < j && a[j] > temp) 
                   j--; 
               // 从数组的右端扫描,并与标准数据元素temp比较,如果a[j]>temp,数据位置不变,继续向左端扫描 
 if (i < j) { 
                   // 数据元素a[j]<temp,则与a[i]交换,使小于temp的元素在temp的左边,并把i值加1,并从数组的左端向右端扫描 
                   a[i] = a[j]; 
                   i++; 
               } 
 while (i < j && a[i] < temp) 
                   i++; 
               // 数组的左端向右端扫描 
 if (i < j) { 
                   a[j] = a[i]; 
                   j--; 
                   // 数据元素a[i]>emp,则与a[j]交换,使大于temp的元素在temp的右边边,并把j值减1,并从数组的由端向左端扫描 
                   a[i] = a[j]; 
               } 
            } 
            a[i] = temp; 
 QuickSort(a, low, i - 1); 
            // 对左端子集合进行递归 
 QuickSort(a, i + 1, high); 
            // 对右端子集合进行递归 
        } 
     } 
 public static void main(String[] args) { 
 int[] test1 = { 2, 300, 5, 110, 7, 9, 10, 256, 248, 14 }; // 测试数组 
 QuickSort(test1, 0, 9); 
 for (int i = 0; i < test1.length; i++) { 
            System.out.print(test1[i] + " "); 
        } 
     } 
 } 

10 二分法查找

 public class binarySearch { 
 public static int binarySearch(int[] dataset ,int data) { 
 int beginIndex = 0;             //定义起始位置 
 int endIndex = dataset.length - 1;  //定义结束位置 
 int midIndex = -1;                 //定义中点 
 if(data <dataset[beginIndex]||data>dataset[endIndex]||beginIndex>endIndex){ 
 return -1; //用二分法查找的数据必须是排好序的,因此只要比较第一个元素和最后一个元素就可以确定所查找的数据是否在数组中   
        } 
 while(beginIndex <= endIndex) { 
            midIndex = (beginIndex+endIndex)/2;//初始化中点 
 if(data <dataset[midIndex]) { 
               endIndex = midIndex-1; //如果查找的数据小于中点位置的数据,则把查找的结束位置定义在中点 
            } else if(data>dataset[midIndex]) { //如果查找的数据小于中点位置的数据,则把查找的起始位置定义在中点 
               beginIndex = midIndex+1; 
            }else { 
 return midIndex; //返回查找到的数据的位置 
            } 
        } 
 return -1; 
     } 
 public static void main(String[] args) { 
 int[] test1 = { 38,48,59,61,72,99,101 }; // 测试数组 
            System.out.print("你查找的数据位置在:"+ binarySearch.binarySearch(test1,59)); 
     } 
 }