java基础编程题练习(一)

1.编程实现用户输入4个整数,按从大到小的顺序排列输出。

思路:将输入的数据存入数组,使用冒泡排序对数组数据进行排序后输出数组

冒泡排序的代码如下:

 1 import java.util.Scanner;
 2 import java.util.Arrays;
 3         /*
 4         import的作用是:
 5         在你写一个类的时候。里面用到了其他的类,而用到的这个类和你现在写的这个类不是同一个包里,
 6         就需要导入那个类的全名
 7         Scanner类:
 8         使用该类创建一个对象.
 9                 Scanner Sc=new Scanner(System.in);
10         然后Sc对象调用下列方法(函数),读取用户在命令行输入的各种数据类型:
11         next.Byte(),nextDouble(),nextFloat,nextInt(),nextLin(),nextLong(),nextShot() 。
12         这些方法执行时都会造成堵塞,等待用户在命令行输入数据回车确认。
13         */
14 public class sort001 {
15         public static void main(String[] args) {
16                 System.out.println("请依次输入四个整数:");
17                 Scanner input = new Scanner(System.in);//对象为input
18                 int[] arr=new int[4];                  //数组名为arr
19                 int temp;
20                 for(int i=0;i<arr.length;i++){
21                         arr[i]=input.nextInt();        //input对象循环使用nextInt()函数读取用户输入的数据
22                 }
23                 System.out.println("排序前数组为:"+Arrays.toString(arr));
24                 for (int x=0;x<arr.length;x++){
25                         /*
26                                 冒泡排序,相邻两个数依次对比,若前面的比后面的小,则二者交换
27                          */
28                         for(int y=x+1;y<arr.length;y++){
29                                 if (arr[x]<arr[y]){
30                                         temp=arr[x];
31                                         arr[x]=arr[y];
32                                         arr[y]=temp;
33                                 }
34                         }
35                 }
36                 System.out.print("排序后数组为:"+Arrays.toString(arr));
37         }
38 }
冒泡排序

拓展思考:1:若用户输入的不是整数,是浮点型,双精度型,字符串等如何处理

     2:若数据过大,超出整型变量范围如何处理?

     3:冒泡排序时间复杂度过高,可用更高效的排序算法替代。

改用插入排序后的代码如下:

 1 import java.util.Arrays;
 2 import java.util.Scanner;
 3 
 4 public class sort001Optimized {
 5     public static void main(String[] args){
 6         System.out.println("请依次输入4个整数:");
 7         Scanner sc = new Scanner(System.in);
 8         long[] arr=new long[4];               //数组名为arr
 9                                               //Scanner是全部输入完才能抛出异常
10             int count=0;                      //输入异常问题有待解决
11             while(count<4&&sc.hasNextLong()){
12                 arr[count]=sc.nextLong();
13                 count++;
14             }
15 
16         System.out.println("排序前数组为:"+ Arrays.toString(arr)); //输出排序前数组
17 
18         //插入排序,排序的结果在数组中是按从小到大排列的
19         for (int i=1;i<arr.length;i++){
20             int k=i;
21             for (int j=arr.length-1;j>i;j--){
22                 if (arr[j]<arr[k]){
23                     k=j;
24                 }
25             }
26             long temp=arr[i];
27             arr[i]=arr[k];
28             arr[k]=temp;
29         }
30 
31         for (int c=arr.length-1;c>=0;c--){      //根据输出要求,将数组元素逆序输出得到从大到小的排列
32             System.out.print(arr[c]+"	");
33         }
34 
35     }
36 }
插入排序

改用快速排序后的代码如下:

2.编程实现求一元二次方程的解。

思路:二次项系数,一次项系数,常数项都需要用户输入,根据判别式b^2-4*a*c判断是否有解,若有解再讨论二次项系数和一次项系数是否都为0,若都为0则无解,二次项系数不为0时使用求根公式求解并输出。

需要注意的问题:条件逻辑关系要正确(网上很多代码实现都出现了逻辑漏洞);数据定义最好采用double(网上很多代码实现都是定义为int型,测试数据时很容易出错),防止sqrt()函数求根时出现小数;编写代码的过程中为了熟悉数组的使用特意选择使用数组存放数据

 1 import java.util.Scanner;
 2 
 3 public class equation {
 4     public static void main(String[] args){
 5         //定义系数数组coef和解的数组sol
 6         double[] coef=new double[3];
 7         double[] sol=new double[2];
 8         Scanner sc=new Scanner(System.in);
 9         System.out.println("请输入不为0的二次项系数:");
10         coef[0]=sc.nextDouble();
11         System.out.println("请输入一次项系数:");
12         coef[1]=sc.nextDouble();
13         System.out.println("请输入常数项:");
14         coef[2]=sc.nextDouble();
15         double dist=coef[1]*coef[1]-4*coef[0]*coef[2];  //dist为判别式变量
16         if(dist<0){
17             System.out.println("方程无解!");           //判别式<0,方程无解
18         } else{
19             if (coef[0]==0){                            //二次项系数为0时判断以此向系数
20                 if (coef[1]==0){                        //一次项系数也为0时无解
21                     System.out.println("方程无解!");
22                 }else{                                  //一次项系数不为0时
23                     sol[0]=(-coef[2])/coef[1];
24                     System.out.println("方程有一个解:"+sol[0]);
25                 }
26             }else {                                     //二次项系数不为0时求根并输出
27                 sol[0] = (-coef[1] + Math.sqrt(dist)) / (2 * coef[0]);
28                 sol[1] = (-coef[1] - Math.sqrt(dist)) / (2 * coef[0]);
29                 System.out.println("方程的两解为:"+sol[0]+"	"+sol[1]);
30             }
31         }
32     }
33 }
一元二次方程求解

3.编写程序,输入一个字符,判断它是否为小写字母,如果是,将它转换成大写字母,否则,不转换。(将大写字母转化城小写的也完成)

思路:判断字符大小写的方法选择,使用ASCII码比较;使用Pattern和Matcher进行匹配判断,再用toUpperCase()和toLowerCase()进行转换;使用isUpperCase()判断是否大写字母。使用方法在代码注释中有注明。

 1 public class zimu {
 2     public static void main(String[] args){
 3 
 4         Scanner input=new Scanner(System.in);
 5         char zm=input.next().charAt(0);
 6         if (zm>=97&&zm<=122){
 7             System.err.println("你输入的是小写字母:"+zm);
 8             zm=(char)(zm-32);   //基本数据类型之间强制类型转换时后面的运算加上括号,否则会报int转char可能会有损失
 9             System.err.println("转换后的字母为:"+zm);
10         }else{
11             System.err.println("你输入的不是小写字母。");
12         }
13     }
14 }
ASCII码实现
 1 import java.util.Scanner;
 2 import java.util.regex.Matcher;
 3 import java.util.regex.Pattern;
 4 
 5 public class practice {
 6     public static void main(String[] args){
 7         String str;
 8         System.out.println("请输入一个字母:");
 9         Scanner input=new Scanner(System.in);
10         str=input.next();
11         Pattern p1=Pattern.compile("[A-Z]");//定义用于大写字母A-Z的匹配模板
12         Pattern p2=Pattern.compile("[a-z]");//定义用于小写字母a-z的匹配模板
13         Matcher m1=p1.matcher(str);         //定义状态器m1
14         Matcher m2=p2.matcher(str);         //定义状态器m2
15         /*****
16          Matcher类的构造方法也是private的所以也是通过调用方法来创建的.
17          Matcher.matches()是必须全部匹配,待匹配的字符按串在目标模板里全都有
18          Matcher.lookingAt()匹配的字符必须要在字符串的最前面
19          Matcher.find()匹配的字符可以在字符串的任意的地方
20          *****/
21         if (m1.matches()){
22             //m1调用matches()对str在A-Z之间匹配
23             System.out.println("你输入的是大写字母:"+str);
24             str=str.toLowerCase();          //将大写字母转化为小写
25         }else if(m2.matches()){
26             //m2调用matches()对str在a-z之间匹配
27             System.out.println("你输入的是小写字母:"+str);
28             str=str.toUpperCase();          //将小写字母转化为大写
29         }else{
30             System.out.println("你输入的既不是大写字母也不是小写字母!");
31         }
32         System.out.println("转化后的字母为:"+str);
33     }
34 }
匹配实现

4.输入 3 个正数,判断能否构成一个三角形

思路:任意两边之和大于第三边,使用&&

 1 import java.util.Scanner;
 2 
 3 public class triangle {
 4     public static void main(String[] args){
 5         System.out.println("请输入三个整数:");
 6         Scanner sc=new Scanner(System.in);
 7             int a=sc.nextInt(),b=sc.nextInt(),c=sc.nextInt();
 8             if (a<=0||b<=0||c<=0){
 9                 System.out.println("请输入正整数:");
10             }
11             if ((a+b)>c&&(a+c)>b&&(b+c)>a){     //任意两边之和大于第三边
12                 System.out.println("可以构成三角形");
13             }else{
14                 System.out.println("不能构成三角形!");
15             }
16     }
17 }
三角形判定

5.编写程序,对输入的年、月、日,给出该天是该年的第多少天

思路:需要根据月份将前面所有月的天数相加再加上该月天数得到结果,每年有12个月,数量较多,结构选择switch结构,需要注意的是平年与闰年的2月天数不同,需要根据年数对4和400取整是否为0确定。

 1 import java.util.Scanner;
 2 
 3 public class dateCount {
 4     public static void  main(String[] args){
 5         System.out.println("请依次输入年,月,日:");
 6         int year,month,day,count=0;
 7         Scanner sc=new Scanner(System.in);
 8         year=sc.nextInt();
 9         month=sc.nextInt();
10         day=sc.nextInt();
11         switch (month){         //switch语句后续符合条件的语句都会执行,所以要将月份倒着写
12             case 12:count+=30;
13             case 11:count+=31;
14             case 10:count+=30;
15             case 9:count+=31;
16             case 8:count+=31;
17             case 7:count+=30;
18             case 6:count+=31;
19             case 5:count+=30;
20             case 4:count+=31;
21             case 3:if (year%4==0||year%400==0){     //根据年数算出平年或闰年,得到2月的天数
22                         count+=29;
23                     }else{
24                         count+=28;
25                     }
26             case 2:count+=31;
27             case 1:count+=day;
28         }
29         System.out.println("这是该年第"+count+"天");
30     }
31 }
根据年月日计算第多少天

6.编写程序,从键盘输入一个 0~99999 之间的任意数,判断输入的数是几位数?

思路一:使用if else条件结构嵌套根据数字对1000,100,10取整确定位数。

思路二:将输入的整数以字符串的形式存储,输出字符串长度。

 1 import java.util.Scanner;
 2 
 3 public class numberBits {
 4     public static void main(String[] args){
 5         Scanner sc=new Scanner(System.in);
 6         System.out.println("请输入一个0~9999的整数:");
 7         int num=sc.nextInt();
 8         if (num/1000>=1){
 9             System.out.println("这是一个四位数,");
10         }else if (num/100>=1){
11             System.out.println("这是一个三位数。");
12         }else if (num/10>=1){
13             System.out.println("这是一个两位数。");
14         }else{
15             System.out.println("这是一个一位数。");
16         }
17     }
18 }
numberBits

7.编写程序,给定一个学生成绩,给出相应等级:

90~100 优秀

80~89 良好

70~79 中等

60~69 及格

0~59 不及格

 思路:与上题类似,不再赘述。

8.编写程序,对输入的一个整数,按相反顺序输出该数。例如,输入为 3578,输出为 8753

思路:将输入的整数以字符串的形式存储,将每一位视作字符,以输入顺序的逆序输出。

 1 import java.util.Scanner;
 2 
 3 public class test {
 4     public static void main(String[] args){
 5         System.out.println("请输入一个整数:");
 6         Scanner sc=new Scanner(System.in);
 7         int num=sc.nextInt();
 8         String str=num+"";
 9         char zifu[]=str.toCharArray();  //将字符串str转为字符型数组
10         String temp="";                 //将temp设为空字符串
11         for(int i=zifu.length-1;i>=0;i--){
12             temp=temp+zifu[i];          //将zifu[]数组中的字符逆序加到temp形成新的字符串
13         }
14         System.out.println(temp);
15     }
16 }
整数翻转输出

更简单的方法:将输入的整数转化为字符串,使用reverse()将字符串顺序翻转。

import java.util.Scanner;

public class test {
    public static void main(String[] args){
        System.out.println("请输入一个整数:");
        Scanner sc=new Scanner(System.in);
        int num=sc.nextInt();
        StringBuilder sb=new StringBuilder(String.valueOf(num));
        System.out.println(sb.reverse());
    }
}
reverse方法
StringBuilder:
当对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类.
StringBuffer 和 StringBuilder 类的对象能够被多次的修改,并且不产生新的未使用对象;
和 StringBuffer 之间的最大不同在于 StringBuilder 的方法不是线程安全的(不能同步访问);
由于 StringBuilder 相较于 StringBuffer 有速度优势,所以多数情况下建议使用 StringBuilder 类;
在应用程序要求线程安全的情况下,则必须使用 StringBuffer 类;

String.valueOf():
将目标对象转换成字符串类型,本例中是将int型的read变量转换成String型。

9.用 while 循环,计算 1~200 之间所有 3 的倍数之和

思路:1~200的数依次判断能否被3整除,如果可以就相加,如果不行则自增。

第一次编写的错误代码及错误解析。

 1 public class distAdd3 {
 2     public static void main(String[] args){
 3         int i=1,sum=0;
 4         while(i>=1&&i<=200){    //运行无结果,因为i>=1始终为true,应该去掉这个条件
 5             if (i/3==0){        //判断整除应该用取余是否为0,用%,不是取整
 6                 sum+=i;
 7             }else {             //else语句是在if后的判定语句不成立的情况下才运行,而不管i能否被3整除i都应该自增要弄清单if和if else的区别
 8                 i++;
 9             }
10         }
11         System.out.println("1~200中所有3的倍数之和为:"+sum);
12     }
13 }
错误代码及解析

修改过后的正确代码:

 1 public class distAdd3 {
 2     public static void main(String[] args){
 3         int i=1,sum=0;
 4         while(i<=200){
 5             if (i%3==0){
 6                 sum+=i;
 7             }            
 8             i++;
 9         }
10         System.out.println("1~200中所有3的倍数之和为:"+sum);
11     }
12 }
distAdd3

10.编写程序,输出 200~500 之间的所有素数

思路:素数只能被1和它本身整除,判断一个数i是否为素数,可以用一个数j对它进行测试,如果 i%j == 0 ,而 j 又不是 1 或 它本身, 那么这个数就不是素数;如果 i%j != 0 ,那么 j 一直增加下去,看 j 能不能有一个值可以整除 i , 如果 j是一个素数,那么j可以一直增加到 i 为止,这样就可以看出它是不是素数了

 1 public class prime {
 2     public static void main(String[] args){
 3         int count=0;                //素数个数标记
 4         for (int i=200;i<=500;i++){
 5             boolean flag=true;      //素数判定标记
 6             for (int j=2;(3*j)<i;j++){  //检验i从能否被从2到i/3中的某个数整除
 7                 if (i%j==0){            //一旦出现整除则i不是质数,跳出j自增的循环,进入i自增的循环,检验i+1
 8                     flag=false;
 9                     break;
10                 }
11             }
12             if (flag){
13                 count++;        
14                 System.out.println("第"+count+"个素数为:"+i);
15             }
16         }
17     }
18 }
素数输出

11.编写程序解决“百钱买百鸡”问题。公鸡五钱一只,母鸡三钱一只,小鸡一钱三只,现有百钱欲买百鸡,共有多少种买法?

思路:公鸡,母鸡,小鸡数量为a,b,c,a+b+c=100,5a+3b+(c/3)=100,因为a<20,b<33可以缩小范围

 1 public class buychicken {
 2     public static void main(String[] args){
 3         for (int a=0;a<20;a++){         //公鸡5元一只,5*a<100
 4             for (int b=0;b<33;b++){     //母鸡3元一只,3*b<100
 5                 int c=100-a-b;
 6                     if (c % 3 == 0 &&5*a+3*b+c/3==100) {        //小鸡1元3只,c必定是3的倍数,且三种鸡的价格之和为100
 7                         System.out.println("公鸡"+a+"只母鸡"+b+"只小鸡"+c+"只");
 8                     }
 9                 }
10             }
11         }
12     }
百元买百鸡

12.使用循环语句输出下面的图形。

#

# # #

# # # # #

# # # # # # #

# # # # # # # # #

思路:循环嵌套,一个循环控制换行,一个 循环控制每一行输出#的个数

 1 public class printTarget {
 2     public static void main(String[] args){
 3         int count=-1;
 4         for (int i=0;i<5;i++){      //该层循环控制换行
 5             count+=2;               //每一行多打两个#
 6             for (int b=0;b<count;b++){  //控制每一行输出#的个数
 7                 System.out.print("#"+"	");
 8             }
 9             System.out.println();
10         }
11     }
12 }
printTarget

13.验证“鬼谷猜想”:对任意自然数,若是奇数,就对它乘以 3 再加 1;若是偶数,就对它除以 2,这样得到一个新数,再按上述计算规则进行计算,一直进行下去,最终必然得到 1

思路:使用while循环控制算法进行直到得到1为止,使用if else结构控制为奇数和偶数的运算。

 1 import java.util.Scanner;
 2 
 3 public class guiguGuess {
 4     public static void main(String[] args){
 5         System.out.println("请输入一个正整数:");    //根据题意,0是自然数但是不符合鬼谷猜想。
 6         Scanner sc=new Scanner(System.in);
 7         int num=sc.nextInt();
 8         while(num!=1){              //直到得到1时循环结束
 9             if (num%2==0){
10                 num=num/2;          //为偶数时除以2
11             }else{
12                 num=num*3+1;        //为奇数时乘3加1
13             }
14         }
15         System.out.print("该数经过鬼谷猜想运算得到的结果为:"+num);
16     }
17 }
guiguGuess

14.编程求 1~10000 之间的所有“完全数”,完全数是该数的所有因子之和等于该数的数。例如,6 的因子有 1、2、3,且 6=1+2+3,所以 6 是完全数

思路:将功能分开写,分解因数并判定的功能写在函数里,在主函数中调用

 1 public class perfectNumber {
 2     public static boolean yinzi(int num){   //定义函数yinzi(),作用是求一个数所有因子的和并判断是否与该数相等
 3         int sum=0;
 4         for (int y = 1; y < num; y++) {     //一个正整数的所有因子都在1和其完全平方根间
 5             if (num % y == 0) {                          //循环检验该数能否被改区间的所有数整除
 6                 sum += y;                             //可以整除的因子进行求和
 7             }
 8         }
 9         return sum==num;        //函数中的结果是boolen型,返回值是判别式sum==num的结果,相等则为true,反之false
10     }
11 
12     public static void main(String[] args){
13         for (int a=1;a<=10000;a++) {    //在1-10000内循环
14             int num=a;
15             if (yinzi(num)) {   //调用函数yinzi()判断num的所有因子之和是否与num相等
16                 System.out.println(num + "是一个完全数。");
17             }
18         }
19     }
20 }
perfectNumber

15.一个整数的各位数字之和能被 9 整除,则该数也能被 9 整除。编程验证给定的整数能否被 9 整除。

思路:将输入的数字以字符串存储,将字符串转换成整型数组,将数组求和再对9取余

 1 import java.util.Scanner;
 2 
 3 public class dist9{
 4     public  static void main(String[] args){
 5         Scanner sc=new Scanner(System.in);
 6         String str=sc.next();               //将输入的数字以字符串的形式存储
 7         int[] num=new int[str.length()];    //得到字符串长度并定义相同长度的整型数组
 8         int sum=0;
 9         for (int i=0;i<str.length();i++){
10             num[i]=Integer.parseInt(str.substring(i,i+1));//将字符串转化成整型数组
11             /*
12             substring(i,i+1)表示截取字符串从第i各到第i+1各字符,包含起始位置不包含结束位置
13              */
14             System.out.print(num[i]);
15             sum+=num[i];                    //各位求和
16         }
17         if (sum%9==0){
18             System.out.println("该数可以被9整除。");
19         }else{
20             System.out.println("该数不能被9整除。");
21         }
22     }
23 }
dist9

16.猴子吃桃问题。猴子第一天摘下若干个桃子,当时就吃了一半,还不过瘾,就又吃了一个。第二天又将剩下的桃子吃掉一半,又多吃了一个。以后每天都吃前一天剩下的一半零一个。到第 10 天在想吃的时候就剩一个桃子了,求第一天共摘下来多少个桃子?

思路:找到数列规律,n2=2*(1+n1)

1 public class monkePeach {
2     public static void main(String[] args){
3         int p=1;
4         for (int i=1;i<10;i++){
5             p=2*(p+1);
6         }
7         System.out.print("第一天一共摘了"+p+"个桃子。");
8     }
9 }
monkeyPeach

17.水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。(例如:1^3 + 5^3 + 3^3 = 153)。编程求出所有三位的水仙花数。

 1 import java.util.Scanner;
 2 
 3 public class shuixianhua {
 4     public static void main(String[] args){
 5         int a, b, c, sum;
 6         for (int num=100;num<1000;num++) {
 7             a = num / 100;
 8             b = num % 100 / 10;
 9             c = num % 10;
10             sum = a * a * a + b * b * b + c * c * c;
11             if (num == sum) {
12                 System.out.println(num + "是一个水仙花数。");
13             }
14         }
15     }
16 }
shuixianhua

18.已知 XYZ+YZZ=532,其中,X、Y、Z 为数字,编程求出 X、Y 和 Z 的值。

 1 public class solEquation {
 2     public static void main(String[] args){
 3         int sum;
 4         for(int x=0;x<=9;x++){
 5             for (int y=0;y<=9;y++){
 6                 for (int z=0;z<=9;z++){
 7                     sum=100*x+110*y+12*z;
 8                     if(sum==532){
 9                         System.out.println("X:"+x+"	Y:"+y+"	Z:"+z);
10                     }
11                 }
12             }
13         }
14     }
15 }
solEquation

19.古典问题:有一对兔子,从出生后第 3 个月起每个月都生一对兔子,小兔

子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数

为多少?

思路:第一个月,第二个月兔子总数为2,第三个月为4,第四个月为6,这是一个斐波那契(Fibonacci)数列,某一项等于相邻前两项的和(n3=n2+n1),可以使用递归和非递归的思路实现。

 1 import java.util.Scanner;
 2 
 3 public class fibonacci {
 4     public static int f(int x){     //定义函数f,功能为求第x个月的总数
 5         if (x==1||x==2){            //第一第二月都是2
 6             return 2;
 7         }else{
 8             return f(x-1)+f(x-2);       //第x月等于前两月之和
 9         }
10     }
11 
12 public static void main(String[] args){
13         System.out.println("请输入月份:");
14         Scanner sc=new Scanner(System.in);
15         int month=sc.nextInt();
16         for (int i=1;i<=month;i++) {    //  将month月之前的每个月兔子总数输出
17             System.out.println("第"+ i + "月的兔子总数为:" + f(i));
18         }
19     }
20 }
递归实现
 1 import java.util.Scanner;
 2 
 3 public class fibonacci {
 4         public static void main(String[] args){
 5         System.out.println("请输入月份:");
 6         Scanner sc=new Scanner(System.in);
 7         int month=sc.nextInt();
 8         int num1=1,num2=1,temp;
 9         if (month==1||month==2){
10             System.out.println("兔子总数为:"+2*num2);
11         }
12         for (int i=3;i<=month;i++){
13             temp=num2;          //第i月等于前两月之和
14             num2=num1+num2;
15             num1=temp;
16             System.out.println(month+"月兔子的总数为:"+2*num2);
17         }
18     }
19 }
非递归实现

20.将一个正整数分解质因数。例如:输入 90,打印出 90=2*3*3*5

思路:从2开始到num,找num的因数,若找到一个就一直除,除到无法再被该因数整除时就往后找新的因数直到没有因数。

import java.util.Scanner;

public class resolve {
    public static void main(String[] args){
        System.out.println("请输入一个整数:");
        Scanner sc=new Scanner(System.in);
        int num=sc.nextInt();
        System.out.print(num+"=");
        for (int i=2;i<num;i++){    //从2开始找因数
            while(num%i==0){        //若num能被i整除则一直除到无法被i整除为止
                num/=i;
                System.out.print(i+"*");
            }
        }
        System.out.print(num);
    }
}
resolve
原文地址:https://www.cnblogs.com/edward-life/p/10483613.html