Java学习---程序设计_基础题[1]

 180813 补全没有的答案!

0、 数组排序大全[冒泡/选择/快速/插入]

  1 package com.ftl;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStreamReader;
  6 import java.util.ArrayList;
  7 import java.util.Arrays;
  8 import java.util.Collections;
  9 import java.util.Iterator;
 10 import java.util.List;
 11 
 12 /**
 13  * 排序算法复习
 14  * @author 小a玖拾柒
 15  * Date:   2018年8月18日  
 16  * 【更多参考】 https://blog.csdn.net/snow_5288/article/details/60140265
 17  */
 18 
 19 public class Test2018 {
 20     
 21     public static void main(String[] args) throws IOException {
 22         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 23         List<Double> l = null;
 24         System.out.println("[eg.]请输入数据,如:1,12,32,2,3");
 25         String input = br.readLine();
 26         //方案一: 多数排序
 27         check(input);
 28         //方案二: 冒泡排序
 29         check2(input);
 30         //方案三: 快速选择排序
 31         check3(input);
 32         //方案四: 插入排序
 33         check4(input);
 34         //方案五: 快速排序
 35         check5(input);
 36     }
 37     
 38     //方案一: list排序:利用Collections工具类实现
 39     public static void check(String str){
 40         String[] s = str.split(",");
 41         int[]  ch = new int[s.length];
 42         List<Integer> list = new ArrayList<Integer>();
 43         for(int i = 0; i < s.length; i++){
 44             ch[i] = Integer.parseInt(s[i]);
 45             list.add(ch[i]);
 46         }
 47         Collections.sort(list);
 48         System.out.println("【方案一】list排序 :" + list);
 49         
 50     }
 51     //方案二: 冒泡排序: 相邻2个数字比较,一次排序后最大/最小的数字排列最后
 52     /**
 53      *  比较相邻的元素。如果第一个比第二个大,就交换他们两个。
 54         对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
 55         针对所有的元素重复以上的步骤,除了最后一个。
 56         持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
 57         冒泡排序需要n-1(i)趟冒泡,每趟冒泡需要比较n-1-i(j)次比较,总共的比较次数为(n-1)+(n-2)+……+1,
 58         所以冒泡排序算法最坏情况和平均复杂度是O(n²)。
 59         由于占用空间有限,冒泡排序的空间复杂度为O(1)。
 60      */
 61     public static void check2(String str){
 62         String[] s = str.split(",");
 63         int[]  ch = new int[s.length];
 64         for(int i = 0; i < s.length; i++){
 65             ch[i] = Integer.parseInt(s[i]);
 66         }
 67         for(int i = 1; i < ch.length; i++){
 68             for(int j = 0; j < ch.length; j++){
 69                 if(ch[i] < ch[j]){
 70                     int tmp = ch[i];
 71                     ch[i] = ch[j];
 72                     ch[j] = tmp;
 73                 }
 74             }
 75         }
 76         System.out.println("【方案二】冒泡排序后:" + Arrays.toString(ch));
 77     }
 78     //方案三: 快速选择排序: 第一个数字依次跟后面的数字比较大小
 79     /**
 80      *  是直观的排序,通过确定一个Key最大或最小值,再从带排序的的数中找出最大或最小的交换到对应位置。再选择次之
 81      *  双重循环时间复杂度为O(n^2)
 82      */
 83     public static void check3(String str){
 84         String[] s = str.split(",");
 85         int[]  ch = new int[s.length];
 86         for(int i = 0; i < s.length; i++){
 87             ch[i] = Integer.parseInt(s[i]);
 88         }
 89         for(int i = 0; i < ch.length; i++){
 90             for(int j = i+1; j < ch.length ; j++){
 91                 if(ch[i] > ch[j]){
 92                     int tmp = ch[i];
 93                     ch[i] = ch[j];
 94                     ch[j] = tmp;
 95                 }
 96             }
 97         }
 98         System.out.println("【方案三】选择排序后:" + Arrays.toString(ch));
 99     }
100     //方案四: 插入排序:往前比较,如果当前数比前一个小则进行第二个循环操作,反之则直接进入下次外层循环
101     //比冒泡更优秀一点,冒泡是无论大小都会继续比较,这里是如果当前数字比前面的小,交换位置[降序则反之即可]
102         public static void check4(String str){
103             String[] s = str.split(",");
104             int[]  ch = new int[s.length];
105             for(int i = 0; i < s.length; i++){
106                 ch[i] = Integer.parseInt(s[i]);
107             }
108             for(int i = 1; i < ch.length; i++){
109                 int tmp = ch[i];
110                 // 升序: 如果前面的数字比当前的tmp大,则交换位置
111                 for(int j = i - 1; j >=0 && tmp < ch[j]; j--){
112                     ch[j+1] = ch[j];
113                     ch[j] = tmp;
114                 }
115             }
116             System.out.println("【方案四】插入排序后:" + Arrays.toString(ch));
117         }
118         //方案五:快速排序:选择一个基准,大于该值放在右侧,小于则放在左侧
119         /**
120          *  选择一个关键值作为基准值。比基准值小的都在左边序列(一般是无序的),比基准值大的都在右边(一般是无序的)。一般选择序列的第一个元素。
121             一次循环:从后往前比较,用基准值和最后一个值比较,如果比基准值小的交换位置,如果没有继续比较下一个,直到找到第一个比基准值小的值才交换。找到这个值之后,又从前往后开始比较,如果有比基准值大的,交换位置,如果没有继续比较下一个,直到找到第一个比基准值大的值才交换。直到从前往后的比较索引>从后往前比较的索引,结束第一次循环,此时,对于基准值来说,左右两边就是有序的了。
122             接着分别比较左右两边的序列,重复上述的循环。
123             快速排序是一种快速的分而治之的算法,它是已知的最快的排序算法,其平均运行时间为O(N*1ogN) 。它的速度主要归功于一个非长紧凑的并且高度优化的内部循环。但是他也是一种不稳定的排序,当基准数选择的不合理的时候他的效率又会编程O(N*N)。
124             快速排序的最好情况:  快速排序的最好情况是每次都划分后左右子序列的大小都相等,其运行的时间就为O(N*1ogN)。
125             快速排序的最坏情况:  快速排序的最坏的情况就是当分组重复生成一个空序列的时候,这时候其运行时间就变为O(N*N)
126             快速排序的时间复杂度为O(N*lgN),快速排序的空间复杂度为O(lgN).
127          */
128         public static void check5(String str){
129             String[] s = str.split(",");
130             int[]  ch = new int[s.length];
131             for(int i = 0; i < s.length; i++){
132                 ch[i] = Integer.parseInt(s[i]);
133             }
134             if(ch.length  <=1) return ;
135             int start = 0;
136             int end = ch.length-1;
137             check5sort(ch, start, end);
138             System.out.println("【方案五】快速排序后:" + Arrays.toString(ch));
139         }
140         
141         public static void check5sort(int[] a,int low,int high){
142              int start = low;
143              int end = high;
144              int key = a[low];   // 设定基准为第一个数字
145              
146              
147              while(end>start){
148                  //从后往前比较
149                  while(end>start&&a[end]>=key)  //如果没有比关键值小的,比较下一个,直到有比关键值小的交换位置,然后又从前往后比较
150                      end--;
151                  if(a[end]<=key){
152                      int temp = a[end];
153                      a[end] = a[start];
154                      a[start] = temp;
155                  }
156                  //从前往后比较
157                  while(end>start&&a[start]<=key)//如果没有比关键值大的,比较下一个,直到有比关键值大的交换位置
158                     start++;
159                  if(a[start]>=key){
160                      int temp = a[start];
161                      a[start] = a[end];
162                      a[end] = temp;
163                  }
164              //此时第一次循环比较结束,关键值的位置已经确定了。左边的值都比关键值小,右边的值都比关键值大,但是两边的顺序还有可能是不一样的,进行下面的递归调用
165              }
166              //递归
167              if(start>low) check5sort(a,low,start-1); //左边序列。第一个索引位置到关键值索引-1
168              if(end<high) check5sort(a,end+1,high);   //右边序列。从关键值索引+1到最后一个
169          }
170 }
View Code

[排序算法更多参考] https://blog.csdn.net/snow_5288/article/details/60140265

[排序算法更多参考] 值得收藏的十大经典排序算法

0、 实现会员注册,要求用户名长度不小于3,密码长度不小于6,注册时两次输入密码必须相同

 1 package com.ftl;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 
 7 
 8 // 实现会员注册,要求用户名长度不小于3,密码长度不小于6,注册时两次输入密码必须相同
 9 
10 public class Test2018 {
11     public static void main(String[] args) {
12         Boolean flag = true ;
13         while(flag){
14             try {
15                 System.out.println("请输入姓名:");
16                 String name = new BufferedReader(new InputStreamReader(System.in)).readLine();
17                 if(name == null || "".equals(name)){
18                     System.out.println("输入为空,请重新输入!");
19                     continue;
20                 }
21                 if(name.length() < 3){
22                     System.out.println("输入用户名长度不得小于3,请重新输入!");
23                     continue;
24                 }
25                 System.out.println("请输入密码:");
26                 String passwd = new BufferedReader(new InputStreamReader(System.in)).readLine();
27                 if(passwd == null || "".equals(passwd)){
28                     System.out.println("输入为空,请重新输入!");
29                     continue;
30                 }
31                 if(passwd.length() < 6){
32                     System.out.println("输入密码长度不得小于6,请重新输入!");
33                     continue;
34                 }
35                 System.out.println("请再次输入密码:");
36                 String passwd2 = new BufferedReader(new InputStreamReader(System.in)).readLine();
37                 if(passwd2 == null || "".equals(passwd2)){
38                     System.out.println("输入为空,请重新输入!");
39                     continue;
40                 }
41                 if(passwd.length() == passwd2.length() && passwd.equals(passwd2)){
42                     System.out.println("注册成功,欢迎您!");
43                     flag = false;
44                     break;
45                 }else{
46                     System.out.println("2次输入的密码不一致,请重新注册!");
47                     continue;
48                 }
49                 
50             } catch (IOException e) {
51                 // TODO Auto-generated catch block
52                 e.printStackTrace();
53             }
54         }
55         
56     }
57 }
View Code

1、 一个景区根据游人的年龄收取不同价格的门票。请编写游人类,根据年龄段决定能够购买的门票价格并输出,然后写出测试类测试该类

 1 package com.ftl;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 import java.util.ArrayList;
 7 import java.util.List;
 8 
 9 // 实现会员注册,要求用户名长度不小于3,密码长度不小于6,注册时两次输入密码必须相同
10 
11 public class Test2018 {
12     public static void main(String[] args) {
13         Boolean flag = true;
14         String name = null;
15         String info = null;
16         List<String> list = new ArrayList<>();
17         int price = 120;
18         int age = 0;
19 
20         while (flag) {
21             try {
22                 System.out.println("请输入游客的姓名:");
23                 name = new BufferedReader(new InputStreamReader(System.in)).readLine();
24                 if (name == null || "".equals(name)) {
25                     System.out.println("输入为空,请重新输入!");
26                     continue;
27                 }
28                 System.out.println("请输入游客的年龄:");
29                 age = Integer.parseInt(new BufferedReader(new InputStreamReader(System.in)).readLine());
30                 if (age < 0 || age > 100) {
31                     System.out.println("输入错误,请从新输入");
32                     continue;
33                 }
34             info = "游客信息: 姓名[" + name + "]" + ", age[" + age + "]";
35             if(age < 18 ){
36                 int pri = price / 2;
37                 info = info + ",门票:" + pri;
38             }else if(age < 60){
39                 int pri = price;
40                 info = info + ",门票:" + pri;
41             }else{
42                 info = info + ",门票:" + "免费";
43             }
44             list.add(info);
45             System.out.println("是否继续售票[Y/N] ?");
46             String con = new BufferedReader(new InputStreamReader(System.in)).readLine();
47             if(con.toUpperCase().equals("Y") || con.equals("Y")){
48                 flag = true;
49             }else{
50                 flag = false;
51                 for (String string : list) {
52                     System.out.println(string);
53                     System.out.println("------------------------------");
54                 }
55             }
56             } catch (IOException e) {
57                 e.printStackTrace();
58             }
59             
60         }
61         
62     }
63 }
View Code

2、 编写一个Java程序,用if-else语句判断某年份是否为闰年

 1 // Programme Name LeapYear.java
 2 
 3 public class LeapYear{
 4 
 5 public static void main(String args[]){
 6 
 7 int year=2010; 
 8 
 9 if(args.length!=0)
10 
11   year=Integer.parseInt(args[0]);
12 
13 if((year%4==0 && year%100!=0)||(year%400==0))
14 
15  System.out.println(year+" 年是闰年。");
16 
17 else
18 
19  System.out.println(year+" 年不是闰年。");
20 
21    }
22 
23  }//if-else语句
View Code

3、编写一个Java程序在屏幕上输出1!+2!+3!+……+10!的和

 1 public class ForTest { 
 2 
 3 public static void main( String args[] ) {
 4 
 5   int  i,j,mul,sum=0;
 6 
 7 for(i=1;i<=10;i++) {
 8 
 9 mul=1;
10 
11 for(j=1,j<=i;j++) {
12 
13 mul=mul*j;
14 
15 }
16 
17       sum=sum+mul;
18 
19 }
20 
21 System.out.println(“1!+2!+3!+……+10!= ”+sum);
22 
23 }
24 
25 }
View Code

5、编写一个Java应用程序,从键盘读取用户输入两个字符串,并重载3个函数分别实现这两个字符串的拼接、整数相加和浮点数相加。要进行异常处理,对输入的不符合要求的字符串提示给用户,不能使程序崩溃

 1 import java.io.*;
 2 
 3 public class Strinput
 4 
 5 {
 6 
 7   public static void main(String args[]) {
 8 
 9    String s1,s2,ss,si,sf;
10 
11        int i1,i2;
12 
13        float f1,f2;
14 
15        BufferedReader strin=new  BufferedReader(new InputStreamReader(System.in));
16 
17        try{System.out.print ("输入第一个字符串:" );
18 
19 s1= strin.readLine();
20 
21            System.out.print ("输入第二个字符串:" );
22 
23 s2= strin.readLine();}
24 
25 catch(Exception e){ System.out.println(e.getMessage());}
26 
27 i1 = Integer.parseInt(s1);
28 
29        i2 = Integer.parseInt(s2);
30 
31        f1 = Float.parseFloat(s1);
32 
33        f2 = Float.parseFloat(s2);
34 
35        ss = strAdd(s1,s2);
36 
37        si = strAdd(i1,i2);
38 
39        sf = strAdd(f1,f2);
40 
41        System.out.println ("输入的二个字符串相加结果为:"+ss );
42 
43        System.out.println ("输入字符串转换为整数相加结果为:"+si );
44 
45        System.out.println ("输入字符串转换为浮点数相加结果为:"+sf );
46 
47  }
48 
49    String strAdd(String str1,String str2) {
50 
51 return str1+str2;
52 
53 }
54 
55 String strAdd(int int1,int int2) {
56 
57 return  String.valueOf(int1+int2);
58 
59 }
60 
61 String strAdd(float flt1,float flt2) {
62 
63 return  String.valueOf (flt1+flt2);
64 
65 }
66 
67  }
View Code

6. 应用FileInputStream类,编写应用程序,从磁盘上读取一个Java程序,并将源程序代码显示在屏幕上。(被读取的文件路径为:E:/myjava/Hello.java)

 1 import java.io.*;
 2 
 3   public class FISDemo {
 4 
 5   public static void main(String args[]) {
 6 
 7     byte[] buf=new byte[2056];
 8 
 9     try{
10 
11      FileInputStream fileIn=new FileInputStream("e:/myjava/Hello.java");
12 
13      int bytes=fileIn.read(buf,0,2056);
14 
15      String str=new String(buf,0,bytes);
16 
17      System.out.println(str);
18 
19 }catch(Exception e){
20 
21  e.printStackTrace( );
22 
23 }
24 
25 }
View Code

7、编写一个Java程序将当100,101,102,103,104,105个数以数组的形式写入到Dest.txt文件中,并以相反的顺序读出显示在屏幕上

 1  import java.io.*;
 2 
 3   public class IODemo {
 4 
 5   public static void main( String args[] ) {
 6 
 7     int data[] = {100,101,102,103,104,105};
 8 
 9 int t;
10 
11 try
12 
13 { DataOutputStream out = new  DataOutputStream (new  FileOutputStream(“dest.txt”));
14 
15   for(int i=0;i<data.length;i++) 
16 
17     out.WriteInt(data[i]);
18 
19   out.close();
20 
21  DataInputStream in = new  DataInputStream (new  FileInputStream(“dest.txt”));
22 
23  for(int i= data.length-1;i>= 0;i--) {
24 
25     t=in.readInt(data[i]);
26 
27 System.out.print(“ ”+t);
28 
29     }
30 
31   System.out.println( );
32 
33   in.close();
34 
35 }catch(IOException e)
36 
37 { System.out.println(e.getMessage());}
38 
39   }
40 
41 }
View Code

9、编写一个Java程序实现多线程,在线程中输出线程的名字,隔300毫秒输出一次,共输出20次。

 1  // 声明一个子线程类Threaddemo;
 2 
 3  class ThreadDemo extends Thread {
 4 
 5   public ThreadDemo(String str) {
 6 
 7 super(str);
 8 
 9 }
10 
11   public void run() {
12 
13     for(int i=0;i<20;i++){
14 
15 System.out.print(“ ”+this.getName());
16 
17 Try {
18 
19 Sleep(300);
20 
21 }catch(InterruptedException e){
22 
23 System.out.println(e.getMessage());
24 
25 Return;
26 
27 }
28 
29 }
30 
31 System.out.println(“  /end”);
32 
33 }
34 
35 }
36 
37 public class TestThread {
38 
39 public static void main( String args[] ) {
40 
41    ThreadDemo thread1=new ThreadDemo(“T1”);
42 
43    ThreadDemo thread2=new ThreadDemo(“T2”);
44 
45    ThreadDemo thread3=new ThreadDemo(“T3”);
46 
47    thread1.start();
48 
49    thread2.start();
50 
51    thread3.start();
52 
53  }
54 }
View Code

10. 编写程序,在屏幕上显示带标题的窗口,并添加一个按钮。当用户单击按钮时,结束程序。

 1 import javax.swing.*;
 2 
 3 import java.awt.event.*;
 4 
 5 public class ButtonEventDemo extends JPanel implements ActionListener{
 6 
 7 protected JButton b1; //声明一个按钮对象
 8 
 9 public ButtonEventDemo() { //构造方法
10 
11 ImageIcon ButtonIcon = new ImageIcon("images/green.png");  //创建按钮的图标对象
12 
13   b1 = new JButton("退出按钮", ButtonIcon);   //生成按钮对象
14 
15 b1.setMnemonic(KeyEvent.VK_E);   //设置b1的助记符是Alt+E
16 
17         b1.setToolTipText("这是退出按钮。"); // 设置按钮提示条
18 
19         this.add(b1);   //往面板对象中加载按钮
20 
21         b1.addActionListener(this);  //本类对象注册为按钮的事件监听器
22 
23      }
24 
25 public void actionPerformed(ActionEvent e){ //按钮事件响应方法
26 
27 System.exit(0);   //按b1则退出主程序        
28 
29 }
30 
31     private static void createGUI() { //创建窗体
32 
33         JFrame.setDefaultLookAndFeelDecorated(true); //设置java隐含观感
34 
35         JFrame frame = new JFrame("按钮测试"); //生成应用程序主窗体
36 
37         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置关闭时隐含操作
38 
39  ButtonEventDemo CPane = new ButtonEventDemo();  //生成主类对象--面板
40 
41         CPane.setOpaque(true);    //面板要求不透明
42 
43         frame.setContentPane(CPane); //设置主类对象为主窗体的内容面板
44 
45         frame.pack(); //主窗体紧缩显示
46 
47         frame.setVisible(true);  //设置主窗体可见
48 
49     }
50 
51     public static void main(String[] args) {  //将createGUI()列入线程
52 
53         javax.swing.SwingUtilities.invokeLater(new Runnable() {
54 
55             public void run() {
56 
57                 createGUI(); 
58 
59             }
60 
61         });
62 
63     }
64 
65 }
View Code

11、定义一个表示学生信息的类Student,要求如下:

(1)类Student的成员变量:

sNO 表示学号;sName表示姓名;sSex表示性别;sAge表示年龄;sJava:表示Java课程成绩。

(2)类Student带参数的构造方法:

在构造方法中通过形参完成对成员变量的赋值操作。

(3)类Student的方法成员:

getNo():获得学号;

getName():获得姓名;

getSex():获得性别;

getAge()获得年龄;

getJava():获得Java 课程成绩

(4)根据类Student的定义,创建五个该类的对象,输出每个学生的信息,计算并输出这五个学生Java语言成绩的平均值,以及计算并输出他们Java语言成绩的最大值和最小值。

 1 public class Student {
 2 
 3 String sNO,sName,sSex;
 4 
 5 int sAge,sJava;
 6 
 7 public Student(String XH,String XM,String XB,int NL,int XF) {
 8 
 9 super();
10 
11 sNO=XH;
12 
13 sName=XM;
14 
15 sSex=XB;
16 
17 sAge=NL;
18 
19 sJava=XF;
20 
21 }
22 
23 public String getNO() {
24 
25 return sNO;
26 
27 }
28 
29 public String getName() {
30 
31 return sName;
32 
33 }
34 
35 public String getSex() {
36 
37 return sSex;
38 
39 }
40 
41 public int getAge() {
42 
43 return sAge;
44 
45 }
46 
47 public int getJava() {
48 
49 return sJava;
50 
51 }
52 
53 public static void main(String[] args) {
54 
55 Student[] st=new Student[5];
56 
57 st[0]=new Student("09zc01","张三","男",19,94);
58 
59 st[1]=new Student("09zc02","李四","男",20,85);
60 
61 st[2]=new Student("09zc03","王五","女",18,96);
62 
63 st[3]=new Student("09zc04","赵六","男",17,90);
64 
65 st[4]=new Student("09zc05","杨七","女",21,88);
66 
67 int max=0,min=100,sum=0;
68 
69     System.out.println("    学生信息:");
70 
71 for (int i=0;i<st.length;i++) {
72 
73 if (st[i].sJava < min)
74 
75 min=st[i].sJava;
76 
77 if (st[i].sJava > max)
78 
79 max=st[i].sJava;
80 
81 sum=sum+st[i].sJava;
82 
83 System.out.println("学生编号:"+st[i].getNO()+", 姓名:"+st[i].getName()+", 性别:"+st[i].getSex()+", 年龄:"+st[i].getAge()+",  Java课学分:"+st[i].getJava());
84 
85     }
86 
87     System.out.println();
88 
89     System.out.println("    共有学生:"+st.length+", 平均成绩:"+sum/st.length);
90 
91     System.out.println("    最小学分:"+min+", 最大学分:"+max);
92 
93 }
94 
95 }
View Code

 12. 100~200内的素数判断

 1 package com.ftl;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 /**
 6     判断101-200之间有多少个素数,并输出所有素数。
 7  *1.程序分析:判断素数的方法:用一个数分别去除2~sqrt(n)或者2~n/2,常用2~n/2,
 8  *因为一个数的一半的平方大于其本身是从5开始的,解方程:n/2的平方>n .如果能被整除【取余运算】, 
 9  *则表明此数不是素数,反之是素数。
10  *
11  * @author 小a玖拾柒
12  * Date:   2018年8月18日  
13  *
14  */
15 public class Test2018 {
16     public static void main(String[] args) {
17         List<Integer> list = new ArrayList<Integer>();
18         for(int i = 100; i < 200; i++){
19             if(isPrimeNumber(i)){
20                 list.add(i);
21             }
22         }
23         System.out.println("100~200 共有" + list.size() + "个数字");
24         System.out.println(list);
25     }
26     public static boolean isPrimeNumber(int num){
27         boolean flag = true;
28         if(num == 2) return flag;
29         for(int i = 2; i <= num/2; i++){
30             if(num % i == 0){
31                 flag = false;
32                 return flag;
33             }
34         }
35         return flag;
36     }
37 }
View Code

13. 水仙花问题

 1 package com.ftl;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 /**
 6   题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如: 
 7     153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。 
 8     1.程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。
 9  *
10  * @author 小a玖拾柒
11  * Date:   2018年8月18日  
12  *
13  */
14 public class Test2018 {
15     public static void main(String[] args) {
16         // 方案一
17         List<Integer> list = new ArrayList<Integer>();
18         for(int i = 100; i < 999; i++){
19             if(i == isPrimeNumber(i)){
20                 list.add(i);
21             }
22         }
23         System.out.println("【方案一】100~999 共有" + list.size() + "个水仙花");
24         System.out.println(list);
25         System.out.println("-------------------------------------------");
26         // 方案二:
27         List<Integer> list2 = new ArrayList<Integer>();
28         for(int i = 100; i < 999; i++){
29             if(i == isPrimeNumber2(i)){
30                 list2.add(i);
31             }
32         }
33         System.out.println("【方案二】100~999 共有" + list2.size() + "个水仙花");
34         System.out.println(list2);
35         System.out.println("-------------------------------------------");
36         // 方案三:
37                 List<Integer> list3 = new ArrayList<Integer>();
38                 for(int i = 100; i < 999; i++){
39                     if(i == isPrimeNumber2(i)){
40                         list3.add(i);
41                     }
42                 }
43                 System.out.println("【方案三】100~999 共有" + list3.size() + "个水仙花");
44                 System.out.println(list2);
45     }
46     // 方案一: 直接拆分数字
47     public static int isPrimeNumber(int num){
48         int sum = 0;
49         int bai = num / 100;
50         int shi  = num /10 % 10;
51         int ge  = num % 10;
52         sum = (int) (Math.pow(bai, 3) + Math.pow(shi, 3) + Math.pow(ge, 3));
53         return sum;
54     }
55     // 方案二: 利用String来切割数字
56     public static int isPrimeNumber2(int num){
57         String sth = String.valueOf(num);
58         int sum = 0;
59         int bai = Integer.parseInt(String.valueOf(sth.charAt(0)));
60         int shi  = Integer.parseInt(String.valueOf(sth.charAt(1)));
61         int ge  = Integer.parseInt(String.valueOf(sth.charAt(2)));
62         sum = (int) (Math.pow(bai, 3) + Math.pow(shi, 3) + Math.pow(ge, 3));
63         //System.out.println("百" + bai + "十" + shi + "个" + ge);
64         return sum;
65     }
66     // 方案三: 数字计算的优化
67         public static int isPrimeNumber3(int num){
68             String sth = String.valueOf(num);
69             int sum = 0;
70             for(int i = 0; i < sth.length(); i++){
71                 sum += Math.pow(Integer.parseInt(String.valueOf(sth.charAt(i))), 3);
72             }
73             //System.out.println("百" + bai + "十" + shi + "个" + ge);
74             return sum;
75         }
76 }
View Code

14.分解质因数

 1 package com.ftl;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 /**
 6 题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 
 7 程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成: 
 8 (1)运用两层循环。 
 9 (2)外循环得到2~n之间的所有质数,内循环将n循环除以质数,知道不能整除。 
10 (3)要是内循环n等于1了就说明n被完全整除了。
11  *
12  * @author 小a玖拾柒
13  * Date:   2018年8月18日  
14  *
15  */
16 public class Test2018 {
17     public static void main(String[] args) {
18         check(180);
19     }
20     
21  public static boolean isPrimeNumber(int n){
22         if(n == 2) return true;
23         for(int i=2; i<=n/2; i++){
24             if(n % i == 0) return false;
25         }
26         return true;
27     }    
28     public static void check(int num){
29         StringBuffer sb = new StringBuffer();
30         sb.append(num+"=");
31         // 这里一定是小于等于,耗时30mins+
32         for(int i = 2; i <= num; i++){
33 //            System.out.print("质数:" + i+"\t");
34             if(isPrimeNumber(i)){
35                 while(num%i==0){
36                     sb.append(i);
37                     num = num / i;
38                     if(num == 1) break;
39                     sb.append("*");
40                 }
41             }else{
42                 continue;
43             }
44         }
45         System.out.println("\n" + sb);
46     }
47 }
View Code

 15. 求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字

 1 package com.ftl;
 2 
 3 import java.util.Scanner;
 4 /**
 5  * 求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有键盘控制。 
 6  * 2  = 2 * 10^0
 7  * 22 = 2 * 10^1 + 2
 8  * 222= 2 * 10^2 + 22
 9  * @author 小a玖拾柒
10  * Date:   2018年8月18日  
11  *
12  */
13 
14 public class Test2018 {
15     public static void main(String[] args) {
16         int n = 0;      // 中间
17         int num = 0;      // 键盘输入的数字
18         int sum = 0;      // 求和
19         int fac = 0;      // 中间值
20         int roate = 0;    // 循环次数
21         boolean flag = true; 
22         while(flag){
23             Scanner scan = new Scanner(System.in);
24             System.out.println("请输入一个数组[0-9]:");
25             num = scan.nextInt();
26             if(num < 0 || num > 9){
27                 System.out.println("输入错误,请重新输入");
28                 continue;
29             }
30             System.out.println("请输入循环次数[10以内]:");
31             roate = scan.nextInt();
32             if(roate >= 10 || roate <=0 ){
33                 System.out.println("输入错误,请重新输入");
34                 continue;
35             }
36             flag = false;
37         }
38         StringBuffer sb = new StringBuffer();
39             for(int j = 0; j < roate; j++){
40                 n = (int)Math.pow(10, j) * num;
41                 fac += n; 
42                 sb.append(fac).append("+");
43                 sum += fac;
44             }
45         System.out.println(sum + "=" + sb.substring(0, sb.length()-1));
46     }
47 }
View Code

16. 求完数,数字=因子之和

 1 package com.ftl;
 2 
 3 import java.util.Scanner;
 4 /**
 5     题目:一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程 找出1000以内的所有完数。
 6  * @author 小a玖拾柒
 7  * Date:   2018年8月18日  
 8  *
 9  */
10 
11 public class Test2018 {
12     public static void main(String[] args) {
13         for(int i=1; i<1000; i++){
14             if(isWanShu(i)){
15                 System.out.print(i + ",");
16             }
17         }
18     }
19 
20     private static boolean isWanShu(int a) {
21         int cup = 0;
22         for(int i=1; i<a; i++){
23             if(a%i == 0)
24                 cup = cup + i;
25         }
26         return (cup == a);
27     }
28 }
View Code

 17. 弹球高度计算

 1 package com.ftl;
 2 
 3 import java.util.Scanner;
 4 /**
 5     一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
 6     1 100  
 7     2 50
 8     3 25
 9     4 12.5
10     5 6.25
11     6 3.125
12      
13  * @author 小a玖拾柒
14  * Date:   2018年8月18日  
15  *
16  */
17 
18 public class Test2018 {
19     public static void main(String[] args) {
20         // 方案一: 直接计算
21         int sum = 0;
22         double height= 100;
23         for(int i = 2; i < 11 ; i++){
24             // 因为第一次是100米,第二次50米,
25             sum += height;
26             height = height/2;
27         }
28         System.out.println("第十次:" + height);
29         System.out.println("总路程:" + sum);
30         
31         // 方案二: 递归解决
32         System.out.println(height(100, 10));
33 
34     }
35     
36         public static double height(double h, int n){
37             if(n==2)  return h/2;
38             else return height(h/2,n-1);
39         }
40 }
View Code

18. 排列组合[互不相同且无重复数字的三位数]

 1 package com.ftl;
 2 
 3 import java.util.List;
 4 import java.util.Vector;
 5 /**
 6     题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? 
 7      
 8  * @author 小a玖拾柒
 9  * Date:   2018年8月18日  
10  *
11  */
12 
13 public class Test2018 {
14     public static void main(String[] args) {
15         int[] arr = {1,2,3,4};
16         int tmp = 0;
17         List<Integer> list = new Vector<>();
18         for(int i = 0; i < 4; i++){
19             for(int j = 0; j < 4; j++){
20                 if(arr[i] != arr[j]){
21                     for(int k = 0; k < 4; k++){
22                         if(arr[i] != arr[k] && arr[j] != arr[k]){
23                             tmp = 100 * arr[i] + 10 * arr[j] + arr[k];
24                             list.add(tmp);
25                         }
26                     }
27                 }
28             }
29         }
30         System.out.println("共有:" + list.size());
31         for(int i = 0; i < list.size(); i++){
32             if(i % 7 != 0){
33                 System.out.print(list.get(i) + "\t");
34             }else{
35                 System.out.println();
36             }
37         }
38     }
39 }
View Code

19. 完全平方数

 1 package com.ftl;
 2 
 3 /**
 4     一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少? 
 5     1. 任何数对1取余数都是0
 6      
 7  * @author 小a玖拾柒
 8  * Date:   2018年8月18日  
 9  *
10  */
11 
12 public class Test2018 {
13     public static void main(String[] args) {
14         
15         for(int i = 0; i < 1000; i++){
16              if(Math.sqrt(i + 100) % 1 == 0 && Math.sqrt(i + 268) % 1 == 0){
17                 System.out.println(i);
18             }
19         }
20     }
21 }
View Code

20. 输出9*9口诀

 1 package com.ftl;
 2 
 3 /**
 4  * 输出9*9口诀
 5  * @author 小a玖拾柒
 6  * Date:   2018年8月18日  
 7  */
 8 
 9 public class Test2018 {
10     
11     public static void main(String[] args)  {
12         for(int i = 1; i <=9; i++){
13             for(int j = 1; j <=i; j++){
14                 System.out.print(i + "*" + j + "=" + (i * j)+"\t");
15             }
16             System.out.println();
17         }
18     }
19 }
View Code

21. 猴子偷桃

 1 package com.ftl;
 2 
 3 /**
 4  *猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个 第二天早上又将剩下的桃子吃掉一半,又多吃了一个。
 5  *以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。 
 6  1.程序分析:采取逆向思维的方法,从后往前推断(递归)
 7      day1: 1
 8      day2: (1+1)*2 = 4
 9      day3: (4+1)*2 = 10
10      day4: (10+1)*2 = 22
11      day5: (22+1)*2 = 46
12  * @author 小a玖拾柒
13  * Date:   2018年8月18日  
14  */
15 
16 public class Test2018 {
17     
18     public static void main(String[] args)  {
19         // 方案一: 循环解决
20         int n = 1;
21         int sum = 1;
22         for(int i = 2; i <= 5; i++){
23             n = ( n + 1 ) * 2;
24         }
25         System.out.println("方案一:" + n);
26         //方案二: 递归
27         System.out.println("方案二:" + getNum(5));
28     }
29     
30     public static int getNum(int d){
31         int sum = 0;
32         if(d==1) return 1;
33         // 这里实际上就是题目说的,前一天的量吃完一半后还余一个的算法
34         else return (getNum(d-1) + 1) * 2;
35                 
36     }
37     
38     
39 }
View Code

22. 乒乓球比赛名单

 1 package com.ftl;
 2 
 3 /**
 4     两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。
 5     已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。
 6  * @author 小a玖拾柒
 7  * Date:   2018年8月18日  
 8  */
 9 
10 public class Test2018 {
11     
12     public static void main(String[] args)  {
13         char[] a = {'a', 'b', 'c'};
14         char[] b = {'x', 'y', 'z'};
15         // 方案一:
16         for(int i = 0; i < 3; i++){
17             for(int j = 0; j < 3; j++){
18                 if(a[i] == 'a' && b[j] != 'x'){
19                     System.out.println(a[i] + "--->" + b[j]);
20                 }else if(a[i] == 'c' && b[j] != 'x' && b[j] != 'z'){
21                     System.out.println(a[i] + "--->" + b[j]);
22                 }else if(a[i] == 'b' ){
23                     System.out.println(a[i] + "--->" + b[j]);
24                 }
25             }
26         }
27         System.out.println("==============");
28         // 方案二:
29         for(int i = 0; i < 3; i++){
30             for(int j = 0; j < 3; j++){
31                 if(a[i] == 'a' && b[j] == 'x'){
32                     continue;
33                 }else if(a[i] == 'c' &&( b[j] == 'x' || b[j] == 'z')){
34                     continue;
35                 }else{
36                     System.out.println(a[i] + "--->" + b[j]);
37                 }
38             }
39         }
40         
41         System.out.println("==============");
42         // 方案三:
43         for(int i=0; i<3; i++){
44             for(int j=0; j<3; j++){
45                 if(i == 0 && j == 0)//a说他不和x比
46                     continue;
47                 else if(i == 2 && (j == 0 || j == 2))
48                     continue;//c说他不和x,z比
49                 else{
50                     System.out.println(a[i] + "<-->" + a[j]);
51                 }
52             }
53         }
54     }
55 }
View Code

23. 打印菱形

 1 package com.ftl;
 2 
 3 /**
 4     打印出如下图案(菱形) 
 5          * 
 6         *** 
 7        ***** 
 8       ******* 
 9        ***** 
10         *** 
11          * 
12          程序分析:先把图形分成两部分来看待,前四行一个规律,后三行一个规律,利用双重 for循环,第一层控制行,第二层控制列。
13          n=4
14                 0    1    2    3    4    5    6         
15        0       空        空    空      *   空      空    空         
16        1       空        空    *   *   *   空    空                
17        2       空         *    *   *   *   *    空                                    
18        3   *    *    *   *   *   *   *                
19  * @author 小a玖拾柒
20  * Date:   2018年8月18日  
21  */
22 
23 public class Test2018 {
24     
25     public static void print(int n){
26         int i = 0;
27         int j = 0;
28         for(i=0; i<n; i++){//前四行
29             for(j=0; j<n+i;j++){
30                 if(j < n-i-1)
31                     System.out.print(" ");
32                 else
33                     System.out.print("*");
34             }
35             System.out.println();
36         }
37         
38         for(i=1; i<n; i++){//后三行
39             for(j=0; j<(2*n-i-1); j++){
40                 if(j < i)
41                     System.out.print(" ");
42                 else
43                     System.out.print("*");
44             }
45             System.out.println();
46         }
47     }
48     
49     public static void main(String[] args) {
50         print(4);
51     }
52 }
View Code

 23. 分数计算

 1 package com.ftl;
 2 
 3 /**有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
 4     1.程序分析:请抓住分子与分母的变化规律。
 5  * @author 小a玖拾柒
 6  * Date:   2018年8月18日  
 7  */
 8 
 9 public class Test2018 {
10     
11     public static void main(String[] args) {
12         double fenmu = 2;
13         double fenzi = 1;
14         double num = 0;
15         double sum = 0;
16         for(int i = 0; i < 20; i++){
17             num = fenmu / fenzi;
18             double tmp = fenmu;
19             fenmu = fenzi + tmp;
20             fenzi = tmp;
21 //            System.out.println(fenmu + "\t" + fenzi + "\t" + num);
22             sum += num;
23         }
24         System.out.println(sum);
25     }
26 }
View Code

24. 阶乘计算

 1 package com.ftl;
 2 
 3 import org.omg.Messaging.SyncScopeHelper;
 4 
 5 /**
 6     题目:求1+2!+3!+...+20!的和
 7  * @author 小a玖拾柒
 8  * Date:   2018年8月18日  
 9  */
10 
11 public class Test2018 {
12     
13     public static void main(String[] args) {
14         // 方案一:循环
15         long sum = 0;
16         for(int i = 1; i <=20; i++){
17             long fac = 1;
18             for(int j = 1; j <=i; j++){
19                 fac *= j;
20             }
21             sum += fac;
22         }
23         System.out.println(sum);
24         
25         // 方案二: 阶乘
26         long ans = 0;
27         for(int i=1; i<=20; i++){
28             ans = ans + jieCheng(i);
29         }
30         System.out.println(ans);
31     
32     }
33     
34     public static long jieCheng(int num){
35         if(num == 1) return 1;
36         else return jieCheng(num-1) * num;
37         
38     }
39 }
View Code

25. 年龄递归计算

 1 package com.ftl;
 2 
 3 /**
 4         有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。
 5         问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?
 6  * @author 小a玖拾柒
 7  * Date:   2018年8月18日  
 8  */
 9 
10 public class Test2018 {
11     
12     public static void main(String[] args) {
13         int num = 5;
14         System.out.println(jieCheng(num));
15     }
16     
17     public static int jieCheng(int num){
18         if(num == 1) return 10;
19         else return jieCheng(num-1) + 2;
20     }
21 }
View Code

26. 分解数字和数字反转

 1 package com.ftl;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.Iterator;
 6 import java.util.List;
 7 
 8 /**
 9         有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。
10         问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?
11  * @author 小a玖拾柒
12  * Date:   2018年8月18日  
13  */
14 
15 public class Test2018 {
16     
17     public static void main(String[] args) {
18         String str = "1234567";
19         // 方案一: 直接反转计算
20         System.out.println("反转前:" + str);
21         List<String> list = new ArrayList<String>();
22         for(int i = 0; i < str.length(); i++){
23             list.add(String.valueOf(str.charAt(i)));
24         }
25         Collections.reverse(list);
26         System.out.println("【方案一】反转后:" + list + ",共有" + list.size() + "个数字");
27         
28         // 方案二: 分解数字
29         Iterator<Integer> iter = explodeNumber(Integer.parseInt(str)).iterator();
30         
31         while(iter.hasNext()){
32             System.out.print(iter.next());
33         }
34     }
35     
36     public static  List<Integer> explodeNumber(int n){
37         List<Integer> li = new ArrayList<Integer>();
38         int count = 0;
39         while(n != 0){
40             li.add((int)n%10);
41             count++;
42             n = n / 10;
43         }
44         System.out.print("【方案二】:");
45         System.out.println("共有" + count + "个数字");
46         return li;
47     }
48 }
View Code

27. 数列: 1,1,2,3,5,8,13,21...

 1 package com.ftl;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 /**
 7  *  数列: 1,1,2,3,5,8,13,21...
 8  *    ==> 0,1,1,2,3,5,8,13,21...
 9  *
10  * @author 小a玖拾柒
11  * Date:   2018年8月18日  
12  *
13  */
14 public class Test2018 {
15     public static void main(String[] args) {
16         int first = 0;
17         int second = 1;
18         int sum = 0;
19         int month = 0;
20         try {
21             BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
22             System.out.println("请输入月份:");
23             month = Integer.parseInt(buf.readLine());
24         } catch (NumberFormatException e) {
25             // TODO Auto-generated catch block
26             e.printStackTrace();
27         } catch (IOException e) {
28             // TODO Auto-generated catch block
29             e.printStackTrace();
30         }
31         for(int i = 1; i < month; i++){
32             sum = first + second;
33             first = second;
34             second = sum;
35         }
36         System.out.println("5个月后:" + sum);
37     }
38 }
View Code

 28. 输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。

 1 package com.ftl;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Arrays;
 5 import java.util.Collections;
 6 import java.util.List;
 7 import java.util.Scanner;
 8 
 9 /**
10        输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
11  * @author 小a玖拾柒
12  * Date:   2018年8月18日  
13  */
14 
15 public class Test2018 {
16     public static void sort(int[] a){//类似冒泡排序
17         int cup = 0;
18         int l = a.length-1;
19         for(int i=1; i<a.length-1; i++){
20             if(a[i] > a[0]){
21                 cup = a[i];
22                 a[i] = a[0];
23                 a[0] = cup;
24             }
25             if(a[i] < a[l]){
26                 cup = a[i];
27                 a[i] = a[l];
28                 a[l] = cup;
29             }
30         }
31     }
32     
33     public static void printArray(int[] a){
34         for(int i=0; i<a.length; i++){
35             System.out.print(a[i]+" ");
36         }
37         System.out.println();
38     }
39     
40     public static void main(String[] args) {
41         int[] a = new int[]{2,3,5,1,2,34,1,0,24};
42         printArray(a);
43         sort(a);
44         printArray(a);
45     }
46 }
View Code

 

 

 

【更多学习参考】

链接:https://pan.baidu.com/s/1Xm4Qt6eWD5cE2t_ZpKk-ow    密码:z6qh

posted @ 2018-07-21 09:56  小a玖拾柒  阅读(1502)  评论(0编辑  收藏  举报