Java基础练习2

Java基础练习2

以图文讲解

在这里插入图片描述

package Demo2.Tt;

public class Test1and2 {
    public static void main(String[] args) {
        System.out.println("第一道题:");
       double a=9.5,b=4.5,c=2.5,d=45.5,e=3.5;
       int f=3;
        System.out.println((a*b-c*f)/(d-e));


        System.out.println("-------------");

        System.out.println("第二道题(1):");

                double sum = 0;
                int aa=11;
                double bb=1.0;
                    for (int i = 1; i <=aa; i += 2) {
                        sum +=4*(bb/i);
                        bb=-bb;
                }
        System.out.println("结果是"+sum);
           }
        }

在这里插入图片描述

package Demo2.Tt;

public class Test1and2 {
    public static void main(String[] args) {
        System.out.println("第二道题(2):");
        int ii=1;
        double bbb=1.0;
        double summ=0;
        do {

                        summ+=4*(bbb/ii);
                        bbb=-bbb;
                        ii+=2;
                    }while(ii<=13);
             System.out.println("结果是"+summ);
            }

        }

在这里插入图片描述

package Demo2.Tt;

public class Test3and4 {
    public static void main(String[] args) {
        /*
        (圆的面积和周长)编写程序,使用以下公式计算并显示半径为5.5的圆的面积和周长。 周长=2×半径×π 面积=半径×半径×π
       */
        double r=5.5;
        System.out.println("周长为:"+2*r*Math.PI);
        System.out.println("面积为:"+Math.pow(r,2)*Math.PI);

         }
}
  • 在这里插入图片描述
package Demo2.Tt;

public class Test3and4 {
    public static void main(String[] args) {
        /*
        (以英里计的平均速度)假设一个跑步者45分钟30秒内跑了14公里。编写一个程序显示以每小时多少英里为单位的平均速度值。(注意,1英里等于1.6公里。)
         */

        //转换:英里/时=(千米/1.6)/(分/60)
        double mile=14/1.6;
        double per_hour=45.5/60;
        System.out.println("平均速度值"+mile/per_hour);



         }
}
  • 在这里插入图片描述
package Demo2.Tt;

import java.util.Scanner;

public class Test5and6 {
    public static void main(String[] args) {
        /*
        (以公里计的平均速度)假设一个跑步者1小时40分钟35秒内跑了24英里。编写一个程序显示以每小时多少公里为单位的平均速度值。(注意,1英里等于1.6公里。)
         */
        double v;
        v=(1.6*24)/(1+40/60+35/3600);
        System.out.println(v);
    }
}

  • 在这里插入图片描述

package Demo;
 
public class Demo2.Test7 {
    public static void main(String[] args) {
 
        final double A,B,C,D,E,F;
        A = 3.4; B = 50.2; C = 2.1;
        D = 0.55; E = 44.5; F = 5.9;
 
        double x,y;
        x = (E * D - B * F) / (A * D - B * C);
        y = (A * F - E * C) / (A * D - B * C);
 
        System.out.println("X is " + x);
        System.out.println("Y is " + y);
    }
}

在这里插入图片描述

public class Demo08 {
    public static void main(String[] args) {
        long totalMilliseconds = System.currentTimeMillis();
        //获取当前时间距离1970-01-01 00:00:00 的毫秒数
        long totalSeconds = totalMilliseconds / 1000; // 毫秒转换为秒
        //求出现在的秒 
        long currentSeconds = totalSeconds % 60;
        //求出现在的分
        long totalMinutes = totalSeconds / 60;
        long currentMinutes = totalMinutes % 60;
        //求出现在的小时
        long totalHours = totalMinutes / 60;
        long currentHours = totalHours % 24;
 
        System.out.println("当前的格林威治时间为:" + currentHours + ":" + currentMinutes + ":" + currentSeconds);
    }
}

  • 在这里插入图片描述

import java.util.Scanner;
 
public class Demo08 {
    public static void main(String[] args) {
        Scanner Scanner = new Scanner(System.in);
        //  提示用户输入总钱数
        System.out.print("请输入总钱数(例如11.56):");
        double moeny = Scanner.nextDouble();
        System.out.println(moeny);
        //  转化为1分币的个数
        int pennyCount = (int)(moeny * 100);
        // System.out.println(pennyCount);
        //  计算美元数
        int dollar = pennyCount / 100;
        // System.out.println(dollar);
        int penny = pennyCount % 100;
        //  计算2角5分币数
        int quarter = penny / 25;
        // System.out.println(quarter);
        penny = penny % 25;
        //  计算1角币数
        int dime = penny / 10;
        // System.out.println(dime);
        penny = penny % 10;
        //  计算5分币数
        int nickel = penny / 5;
        // System.out.println(nickel);
        penny = penny % 5;
        //  剩余的钱就是1分币的个数
        // System.out.println(penny);
        //   显示结果
        System.out.println("dollar数:" + dollar + ", quarter数:" + quarter + 
        ", dime数:" + dime + ", nickel数:" + nickel + ", penny数:" + penny);
    }
}

  • 在这里插入图片描述



  • 在这里插入图片描述
import java.util.Scanner;
 public class Test9{
    public static void main(String[] args){
        Scanner input=new Scanner (System.in);
        System.out.print("随机输入一个1000以内的数");
        int x=input.nextInt();
        int n = x%10;
		x = x-n;
		int m = x/10;
		int sum=0;
		sum = sum+n;
		
		while(m!=0)
		{
			sum = sum+m%10;
			m=m/10;
		}
		 System.out.print("整数各位数的和是"+sum);

    }
}
  • 在这里插入图片描述
    1)调用 Systm.currentTimeMIllis( ) 方法获取1970年1月1日午夜到现在的毫秒数(例如:1203183086328毫秒),并且存放在变量 totalMilliseconds 中。

2)通过将毫秒数 totalMilliseconds 除以 1000 得到总毫秒数 totalseconds (例如:1203183086328毫秒 / 1000 = 1203183068)。

3)通过 totalSeconds % 60 得到当前秒数(例如:1203183068秒 % 60 = 8,这个值就是当前秒数)。

4)通过将 totalSeconds 除以 60 得到总的分钟数 totalMinutes (例如:1203182068秒 / 60 = 20023051分钟)。

5)通过 totalMinutes % 60 得到当前分钟数(例如:20053051 分钟 % 60 = 31,这个值就是当前分钟数)。

6)通过 totalMinutes 除以 60 获得总的小时数 totalHouse(例如:20053051分钟 / 60 = 334217小时)。

7)通过 totalHouse % 24 得到当前的小时数(例如: 334217 小时 % 24 = 17,该值就是当前小时数)。

package Chapter_03;
 
import java.util.Scanner;
 
public class Code_01 {
public static void main(String[] args) {
	long totalMilliseconds = System.currentTimeMillis();
	
	long totalSeconds = totalMilliseconds / 1000;
	
	long currentSecond = totalSeconds % 60;
	
	long totalMinutes = totalSeconds / 60;
	
	long currentMinute = totalMinutes % 60;
	
	long totalHours = totalMinutes / 60;
	
	long currentHour = totalHours % 24;
	
	System.out.println("Current time is " + currentHour + ":" + currentMinute + ":"+currentSecond + " GMT");
	}
}

  • 在这里插入图片描述
package chapter02;

import java.util.Scanner;

public class Code_02{
    public static void main(String[] args) {
        double Joule,WaterKilo,InitTemp,FinalTemp;

        System.out.print("Enter the amount of water in kilograms : ");
        Scanner WaterInput = new Scanner(System.in);
        WaterKilo = WaterInput.nextDouble();

        System.out.print("Enter the initial temperature : ");
        Scanner InitTempInput = new Scanner(System.in);
        InitTemp = InitTempInput.nextDouble();

        System.out.print("Enter the final temperature : ");
        Scanner FinalTempInput = new Scanner(System.in);
        FinalTemp = FinalTempInput.nextDouble();

        Joule = WaterKilo * (FinalTemp - InitTemp) * 4184;
        System.out.println("The energy needed is " + Joule);
    }
}
  • 在这里插入图片描述
/**
 * 财务应用程序:复利值。
 * 假设每个月向银行帐号存100美元,年利率为5%,那么每月利率就是5%/12=0.00417。
 * 第一个月之后,账户上的值就变成:100 * (1 + 0.00417) = 100.47。
 * 第二个月:(100 + 100.47) * (1 + 0.00417) = 201.252。
 * 编写程序显示六个月后账户的钱数。
 */
package Test;
 
public class Code_03{
	public static void main(String[] args) {
		final double save = 100;
		double sum = 0;
		double yearRates = 0.05;
		double monthRates = 0.00417;
		for (int i = 1; i < 7; i++){
			sum = (sum + save) * Math.pow(1 + monthRates, 1);
			System.out.println("The " + i + " months is " + sum + " douls!");
		}
		
		System.out.println(sum);
	}
 
}

  • 在这里插入图片描述
import java.util.Scanner;

public class Code_04 {
    public static void main(String[] args) {
        // 获取数据
        Scanner input = new Scanner(System.in);
        System.out.println("Enter x1 and y1: ");
        double x1 = input.nextDouble();
        double y1 = input.nextDouble();
        System.out.println("Enter x2 and y2: ");
        double x2 = input.nextDouble();
        double y2 = input.nextDouble();

        // 计算两点距离
        double distance = Math.pow((Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2)), 0.5);

        // 输出
        System.out.println("The distance between the two points is " + distance);
    }
}
  • 在这里插入图片描述
import java.util.Scanner;

public class Code_05 {
    public static void main(String[] args) {
        // 接收输入(三个点x y坐标)
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the coordinates of three points separated by spaces like x1 y1 x2 y2 x3 y3: ");
        double x1 = input.nextDouble(), y1 = input.nextDouble();
        double x2 = input.nextDouble(), y2 = input.nextDouble();
        double x3 = input.nextDouble(), y3 = input.nextDouble();

        // 求出三条边的长度
        double side1 = Math.pow((Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)), 0.5);
        double side2 = Math.pow((Math.pow(x1 - x3, 2) + Math.pow(y1 - y3, 2)), 0.5);
        double side3 = Math.pow((Math.pow(x2 - x3, 2) + Math.pow(y2 - y3, 2)), 0.5);

        // 求s和area
        double s = (side1 + side2 + side3) / 2;
        double area = Math.pow(s * (s - side1) * (s - side2) * (s - side3), 0.5);

        // 输出
        System.out.println("The area of the triangle is " + area);
    }
}


  • 在这里插入图片描述
import java.util.Scanner;

public class Code_06 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		//输入数据
		System.out.println("请输入您的体重值(单位:千克)为:");
		float weight = sc.nextFloat();
		System.out.println("请输入您的身高值(单位:米)为:");
		float height = sc.nextFloat();
		
		//判断健康状况
		float bmi = weight / (height * height);
		System.out.printf("您的BMI值是:%.2f\n",bmi);
		if (bmi<18.5)
			System.out.println("身体健康状况:偏瘦");
		else if(bmi <25)
			System.out.println("身体健康状况:正常体重");
		else if(bmi<30)
			System.out.println("身体健康状况:偏胖");
		else
			System.out.println("身体健康状况:肥胖");


	}

}
  • 在这里插入图片描述
public class AleapYear {
    public static void main(String[] args) {
        System.out.println("请输入年份:");
        //   键盘动态输入
        Scanner input =new Scanner(System.in);
        // 捕捉异常
        try {
             // 循环读取用户输入的值
             while (true){
                 //  循环读取用户输入的值
                int year=input.nextInt();
                 if (year<1000 || year >9999)
                     System.out.println("请输入大于1000小于9999的年份");
                 else if (year %4==0 && year %100 !=0 || year %400==0){
                     System.out.println(year+"年,是闰年");
                 }else {
                     System.out.println(year+"年,是平年");
                 }
 
             }
        }catch (Exception e){
            System.out.println("请输入正确年份:");
            e.getStackTrace();
        }
    }
}
 
  • 在这里插入图片描述
import java.util.Scanner;
class PlayTicket {
	public static void main(String[] args) {
/*
假设你想开发一个玩彩票的游戏,程序随机地产生一个两位数的彩票,提示用户输入
一个两位数,然后按照下面的规则判定用户是否能赢。
如果用户输入的数匹配彩票的实际顺序,奖金10 000美元。
如果用户输入的所有数字匹配彩票的所有数字,但顺序不一致,奖金 3 000美元。
如果用户输入的一个数字仅满足顺序情况下匹配彩票的一个数字,奖金1 000美元。
如果用户输入的一个数字仅满足非顺序情况下匹配彩票的一个数字,奖金500美元。
如果用户输入的数字没有匹配任何一个数字,则彩票作废。
*/

	//10-99
	String prize=(int)(Math.random()*90+10)+"";
	System.out.println("本期奖金号码为:"+prize);
	char p1=prize.charAt(0);
	char p2=prize.charAt(1);
	Scanner scan=new Scanner(System.in);
	System.out.println("请输入彩票号码:");
	String ticket=scan.next();
	//获取第一和第二个数字
	char t1=ticket.charAt(0);
	char t2=ticket.charAt(1);
		if((t1==p1)&&(t2==p2)){
			System.out.println("奖金10,000美元");
		}else if((t1==p2)&&(t2==p1)){
			System.out.println("奖金3000美元");
		}else if((t1==p1)||(t2==p2)){
			System.out.println("奖金1000美元");
		}else if((t1==p2)||(t2==p1)){
			System.out.println("奖金500美元");
		}else{
			System.out.println("彩票作废");
		}
      
	}
}

  • 在这里插入图片描述
import java.util.Scanner;

public class Test3_1 {
    public static void main(String[] args) {
        // 获取数据
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a, b, c: ");
        double a = input.nextDouble(), b = input.nextDouble(), c = input.nextDouble();

        // 计算判别式
        double judge = Math.pow(b, 2) - 4 * a * c;

        // 根据判别式结果分三种情况计算根值并输出
        if (judge > 0 && a != 0){
            double r1 = (-b + Math.pow(judge, 0.5)) / (2 * a);
            double r2 = (-b - Math.pow(judge, 0.5)) / (2 * a);
            System.out.println("The equation has two roots "+r1+" and "+r2);
        } else if (judge == 0 && a != 0){
            double r1 = (-b) / (2 * a);
            System.out.println("The equation has one root " + r1);
        }else if (a == 0){  // 补充,如果a=0应该也有结果,但不是根
            double r1 = (-c) / b;
            System.out.println("The equation has one root " + r1);
        }else
            System.out.println("The equation has no real roots");
    }
}


  • 在这里插入图片描述
import java.util.Scanner;

public class Test3_3 {
    public static void main(String[] args) {
         // 获取a b c d e f
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a, b, c, d, e, f: ");
        double a = input.nextDouble(), b = input.nextDouble(), c = input.nextDouble();
        double d = input.nextDouble(), e = input.nextDouble(), f = input.nextDouble();

        // 判断a*d-b*c是否为0
        if(a * d - b * c == 0){
            System.out.println("The equation has no solution");
            return; 
        }

        // 求解
        double x = (e*d-b*f) / (a*d-b*c);
        double y = (a*f-e*c) / (a*d-b*c);

        // 输出结果
        System.out.println("x is " + x + " and y is " + y);
    }
}


  • 在这里插入图片描述
package pack2;
 
import java.util.Scanner;
 
public class FindDate {
 /*
 提示用户输入代表今天日期的数字(周日为0 ,周一为1,….,周六为6)。同时,提示用户输入一个今天之后的天数,作为代表将来某天的数字,然后显示这天是星期几。
        将来的日期 = (今天日期 + 将来天数)% 7
 */
	public static void main(String[] args) {
		try(Scanner input = new Scanner(System.in);) {
			System.out.print("Enter today's day: ");
			int day = input.nextInt();
			
			System.out.print("Enter the number of days elapsed since today: ");
			int numberOfDays = input.nextInt();
			
			System.out.println(searchDate(day, numberOfDays));
		}
	}
 
	//找到将来的日期
	public static String searchDate(int day, int numberOfDays) {
		String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", 
                         "Friday", "Saturday"};
		return "Today is "+days[day]+" and the future day is "
                +days[((day + numberOfDays) % 7)];
	}
}

  • 在这里插入图片描述
package Demo2.Test4;

import java.util.Scanner;

public class Test26 {
    public static void main(String[] args) {
        /*
        输入一个字符串,判断该字符串是否是回文字符串(面试题)123454321
         */
            String s = new Scanner(System.in).nextLine();
            if ( print(s)){
                System.out.println("是回文字符串");
            }else{
                System.out.println("不是");
            }

        }

        private static boolean print(String s) {
            for (int i = 0, j = s.length() - 1; i < s.length(); i++, j--) {
                if (s.charAt(i)!= s.charAt(j)) {
                    return false;
                }
            }
            return true;
        }
    }

  • 在这里插入图片描述
package Demo2.Test4;

import java.util.Scanner;

public class Test34 {
    public static void main(String[] args) {
        /*
        猜拳游戏,石头剪刀布。随机数生成石头剪刀布(0:石头  1:剪刀  2:布)
         */
        Scanner sc=new Scanner(System.in);
        while(true) {
            int r=(int)(Math.random()*3);
            System.out.print("请输入你的选择(0:石头  1:剪刀  2:布):");
            int x=sc.nextInt();
            if((r==0&&x==1)||(r==1&&x==2)||(r==2&&x==0)) {
                System.out.println("你输了");
            }else {
                System.out.println("你赢了");
            }
        }

        }
    }

  • 在这里插入图片描述
package pack2;
 
import java.util.Scanner;
 
public class DayIs {
 
	public static void main(String[] args) {
		try(Scanner input = new Scanner(System.in);) {
			System.out.print("Enter year: (e.g., 2012): ");
			int year = input.nextInt();
			
			System.out.print("Enter month: 1-12: ");
			int month = input.nextInt();
			
			System.out.print("Enter the day of the month: 1-31: ");
			int day = input.nextInt();
			
			System.out.println(day(year, month, day));
		}
	}
 
	//某天是星期几
	public static String day(int year, int month, int day) {
		String[] days = {"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday",     
                         "Thursday", "Friday"};	
		int m = month,k, j;
		
		if(month < 1 || month > 12)	//如果月份不合法,抛出异常
			throw new IllegalArgumentException("Error Month: "+month);
		if(day < 1 || day > 31)	    //如果天数不合法,抛出异常
			throw new IllegalArgumentException("Error Day: "+day);
		
		if(month == 1 || month == 2) {	//处理月份为1或2的情况
			m = (month == 1) ? 13 : 14;	//如果月份为1,m = 13;否则,m = 14
			year--;	    //年份减一
		}
		k = year % 100;            	//世纪的第几年
		j = Math.abs(year / 100);	//世纪数
		
		int h = (day + (26 * (m + 1)) / 10 + k + (k / 4) + (j / 4) + 5 * j) % 7;
		return "Day of the week is "+days[h];
	}
}

  • 在这里插入图片描述
import java.util.Scanner;
/*
先用上面公式判断是否在圆内
输出点的坐标
难点在输出语句中的如何控制not的输出:打标(boolean标记)
*/

public class Test3_22 {
    public static void main(String[] args) {
        // 获取点坐标
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a point with two coordinates: ");
        double x2 = input.nextDouble(), y2 = input.nextDouble();

        // 判断是否在圆内
        double x1 = 0.0, y1 = 0.0;
        double distance = Math.pow( (Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2)), 0.5);

        double radius = 10.0;

        final double EPSILON = 0.001;
        boolean bool = false;
        if((radius - distance) > EPSILON){
            // 这里认为点在圆内
            bool = true;
        }

        // 输出结果
        if(bool){
            System.out.println("Point (" + x2 + ", " +  y2 + ") is in the circle");
        }else{
            System.out.println("Point (" + x2 + ", " +  y2 + ") is not in the circle");
        }
    }
}



  • 在这里插入图片描述
import java.util.Scanner;

public class Test3_28 {
/*
三种情况:

一个矩形(中心(x2,y2))在另一个(中心(x1,y1))之内:两个中心距离在x、y上的分量假设为x0、y0,中心(x1,y1)的高为h1、宽为w1,中心(x2,y2)的高为h2、宽为w2,则此时(x0 + w2 / 2) < (w1 / 2),且(y0 + h2 / 2) < (h1 / 2)
重叠(变量用1中的):((w1 - w2) / 2) < x0 < ((w1 + w2) / 2) 且 ((h1 - h2) / 2) < y0 < ((h1 + h2) / 2)
相离:x0 > ((w1 + w2) / 2) 或 y0 > ((h1 + h2) / 2)
*/
    public static void main(String[] args) {
        // 从控制台获取数据
        Scanner input = new Scanner(System.in);
        System.out.println("Enter r1's center x-. y- coordinates, width, and height: ");
        double x1 = input.nextDouble(), y1 = input.nextDouble();
        double w1 = input.nextDouble(), h1 = input.nextDouble();
        System.out.println("Enter r2's center x-, y- coordinates, width, and height: ");
        double x2 = input.nextDouble(), y2 = input.nextDouble();
        double w2 = input.nextDouble(), h2 = input.nextDouble();

        // 计算两个中心之间距离的分量
        double x0 = Math.abs(x2 - x1);
        double y0 = Math.abs(y2 - y1);

        // 判断位置
        if(((x0 + w2 / 2) <= (w1 / 2)) && ((y0 + h2 / 2) <= (h1 / 2))) {
            System.out.println("r2 is inside r1");
        }else if(((w1 - w2) / 2) < x0 && x0 < ((w1 + w2) / 2) && ((h1 - h2) / 2) < y0 && y0 < ((h1 + h2) / 2))
            System.out.println("r2 overlaps r1");
        else
            System.out.println("r2 does not overlap r1");
    }
}


  • 在这里插入图片描述
import java.util.Scanner;

public class Test3_27 {
    public static void main(String[] args) {
    /*
    思路:
    x坐标在0~200内
   y坐标在0~100内
   如果将(200,0)和(0,100)作为一条线,该直线的截距为100,将直线平移到该坐标点上,此时直线的截距应在0~100内
    */
        // 获取该点x坐标、y坐标
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a point's x- and y- coordinates: ");
        double x_judge = input.nextDouble(), y_judge = input.nextDouble();

        // 判断该点是否在三角形内,如果不在则改为false
        boolean bool = true;
        // 判断x、y坐标是否在范围内
        if( (x_judge < 0 || x_judge > 200) || (y_judge < 0 || y_judge > 100) ) {
            bool = false;
        }
        // 求出其它两个点对应的直线斜率(k),并将x_judge y_judge代入判断
        double k = 100.0 / (0 - 200);
        double b_judge = y_judge - k * x_judge;
        if(b_judge < 0 || b_judge > 100)
            bool = false;

        // 输出
        if(bool)
            System.out.println("The point is in the triangle");
        else
            System.out.println("The point is not in the triangle");
    }
}


  • 在这里插入图片描述
import java.util.Scanner;

public class Test3_28 {
    public static void main(String[] args) {
    /*
    
一个矩形(中心(x2,y2))在另一个(中心(x1,y1))之内:两个中心距离在x、y上的分量假设为x0、y0,中心(x1,y1)的高为h1、宽为w1,中心(x2,y2)的高为h2、宽为w2,则此时(x0 + w2 / 2) < (w1 / 2),且(y0 + h2 / 2) < (h1 / 2)

重叠(变量用1中的):((w1 - w2) / 2) < x0 < ((w1 + w2) / 2) 且 ((h1 - h2) / 2) < y0 < ((h1 + h2) / 2)


相离:x0 > ((w1 + w2) / 2) 或 y0 > ((h1 + h2) / 2)
    */
        // 从控制台获取数据
        Scanner input = new Scanner(System.in);
        System.out.println("Enter r1's center x-. y- coordinates, width, and height: ");
        double x1 = input.nextDouble(), y1 = input.nextDouble();
        double w1 = input.nextDouble(), h1 = input.nextDouble();
        System.out.println("Enter r2's center x-, y- coordinates, width, and height: ");
        double x2 = input.nextDouble(), y2 = input.nextDouble();
        double w2 = input.nextDouble(), h2 = input.nextDouble();

        // 计算两个中心之间距离的分量
        double x0 = Math.abs(x2 - x1);
        double y0 = Math.abs(y2 - y1);

        // 判断位置
        if(((x0 + w2 / 2) <= (w1 / 2)) && ((y0 + h2 / 2) <= (h1 / 2))) {
            System.out.println("r2 is inside r1");
        }else if(((w1 - w2) / 2) < x0 && x0 < ((w1 + w2) / 2) && ((h1 - h2) / 2) < y0 && y0 < ((h1 + h2) / 2))
            System.out.println("r2 overlaps r1");
        else
            System.out.println("r2 does not overlap r1");
    }
}


  • 在这里插入图片描述
import java.util.Scanner;

public class Test3_29 {
    public static void main(String[] args) {
    /*
编写程序,提示用户输入两个圆的中心坐标和各自的半径值,然后判断圆是在第一个圆内,还是和第一个圆重叠
原书自带提示:如果两个圆心的距离≤|r1-r2|,可以判断circle2在circle1内;如果两个圆心的距离≤r1+r2,可以判断circle2和circle1重叠
    */
        // 接收用户输入
        Scanner input = new Scanner(System.in);
        System.out.println("Enter circle1's center x-, y-coordinates, and radius: ");
        double x1 = input.nextDouble(), y1 = input.nextDouble(), r1 = input.nextDouble();
        System.out.println("Enter circle2's center x-, y-coordinates, and radius: ");
        double x2 = input.nextDouble(), y2 = input.nextDouble(), r2 = input.nextDouble();

        // 计算两个圆心的距离
        double distance = Math.pow(Math.pow(x1-x2,2) + Math.pow(y1-y2,2), 0.5);

        // 判断距离与圆心之间的关系
        if(distance < Math.abs(r1-r2))
            System.out.println("circle2 is inside circle1");
        else if(distance < r1+r2)
            System.out.println("circle2 overlaps circle1");
        else
            System.out.println("circle2 does not onverlap circle1");
    }
}


  • 在这里插入图片描述
import java.util.Scanner;

public class Test3_26 {
/*
先分别判断能否被5和6整除
并将结果赋予boolean变量
再结合操作符进一步判断
*/
    public static void main(String[] args) {
        // 接收用户输入
        Scanner input = new Scanner(System.in);
        System.out.println("Enter an integer: ");
        int userInt = input.nextInt();

        // 分别判断(三目运算符)能否被5、6整除, bool存是否能被5、6单个整除
        boolean bool_5 = (userInt % 5 == 0) ? true : false;
        boolean bool_6 = (userInt % 6 == 0) ? true : false;
        boolean bool = ((bool_5==true&&bool_6==false) || (bool_5==false&&bool_6==true)) ? true : false;

        // 5和6
        System.out.println("Is "+ userInt + " divisible by 5 and 6? " +
                (bool_5 && bool_6));
        // 5或6
        System.out.println("Is "+ userInt + " divisible by 5 or 6? " +
                (bool_5 || bool_6));
        // 5、6其一
        System.out.println("Is "+ userInt + " divisible by 5 or 6, but not both?  " + bool);
    }
}


  • 在这里插入图片描述
    解:比较用户输入的数字和电脑生成的数字大小
    使用Random类产生随机数
    Math.random(); 产生一个[0,1)的小数
    (int) [0,1) * 101 = [0,101)
import java.util.Scanner;
public class Demo32 {
    public static void main(String[] args) {
        //产生一个随机数
        int com = (int) (Math.random() * 101);
        //用户输入数字 来判断是否猜中
        Scanner input = new Scanner(System.in);
        while (true) {
            System.out.print("Enter a number:");
            int usr = input.nextInt();
            if (usr > com) {
                System.out.println("high");
            } else if(usr < com) {
                System.out.println("low");
            } else {
                System.out.println("niubility!");
            break;
            }
        }
    }
}




  • 在这里插入图片描述
    解:首先比较两个数字,选最小的作为循环的开始;
    从最小的数字开始向1循环递减,
    如果找到一个数字i能够把两个数字同时整除,
    那么最大公约数就是i
import java.util.Scanner;
public class Demo33 {
    public static void main(String[] args) {
        //提示输入两个数字并判断大小
        Scanner input = new Scanner(System.in);
        System.out.print("请输入两个数字:");
        int number1 = input.nextInt();
        int number2 = input.nextInt();
        int min = number1 < number2 ? number1 : number2;

        //从min开始向1循环递减,如果找到一个数字i能够把num1和num2同时整除,那么最大公约数就是i
        int number = 1;
        for (int i = min; i > 0; i--) {
            if (number1 % i == 0 && number2 % i == 0) {
                number = i;
                break;
            }
        }
        System.out.println("最大公约数为:" + number);
    }
}



  • 在这里插入图片描述



在这里插入图片描述
解:从第一个字符和最后一个字符挨个比较
如果一直相同,一直到首尾相遇,那就是回文
否则就不是回文

import java.util.Scanner;
public class Demo35 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("请输入一段话:");
        //接下来输入的一行
        String str = input.nextLine();
        
        int l = 0;
        int r = str.length() - 1;
        
        boolean flag = true;
        //比较字符
        while (l < r) {
            if (str.charAt(l) == str.charAt(r)) {
                l++;
                r--;
            } else {
            	//遇到不一样的字符,则跳出并改变flag
                flag = false;
                break;
            }
        }
        if (flag) {
            System.out.println(str + " 这句文本是回文");
        } else {
            System.out.println(str + " 这句文本不是回文");
        }
    }
}


在这里插入图片描述

解:素数是不能被除1和它本身外其他数整除
先用判断i是否为素数
如果不是就寻找下一个
如果是就跳出循环,并输出i,同时让计数count加一.直到满五十个素数

public class Demo36 {
    public static void main(String[] args) {
        int count = 0;
        int number = 2;
        while (count < 50) {
            boolean flag = true;
            for (int i = 2; i <= number / 2; i++) {
                if (number % i == 0) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                System.out.print(number + "\t");
                count++;
                if (count % 10 == 0) {
                    System.out.println();
                }
            }
            number++;
        }
    }
}



  • 在这里插入图片描述
    解:获取输入,当获取到输入为0时结束获取(while语句)
    在while语句内将所有输入数据加起来、单独变量计数、单独变量计算多少个正数、负数
    计算输入值的总和和平均值,输出
import java.util.Scanner;

public class Test5_1 {
    public static void main(String[] args) {
        // 接收输入
        Scanner input = new Scanner(System.in);
        System.out.println("Enter an integer, the input ends if it is 0: ");
        int i = 0, sum = 0, positive = 0, negative = 0; // 计数、总和、正数个数、负数个数
        int user = 0;
        boolean bool = true;            // 打标
        while(bool){
            user = input.nextInt();        // 接收输入
            if(user != 0){                 // 这个分支主要对非0的输入进行处理
                sum += user;               // 加总
                ++i;                       // 计数(总数)
                if(user > 0){++positive;}  // 计数(正数)
                else{++negative;}          // 计数(负数)
            }else{                         // 这个分支对输入的0进行处理
                if(i == 0){              // 如果只输入了一个0的处理:输出错误信息并退出
                    System.out.println("No numbers are entered except 0");
                    System.exit(1);
                }else{                     // 如果已经输入了多个数字则结束整个循环
                    bool = false;
                }
            }
        }

        // 计算平均数并输出结果
        System.out.println("The number of positives is " + positive);
        System.out.println("The number of negatives is " + negative);
        System.out.println("The total is " + sum);
        System.out.println("The average is " + (sum / i));
    }
}



在这里插入图片描述

public class Test5_10 {
    public static void main(String[] args) {
    /*
    用for循环判断从100到1000之间的所有整数能否被5和6整除
如果能被整除,便直接用if判断语句输出
if语句中再嵌套一个条件判断语句,当输出个数为10时,输出一个换行符(可以是System.out.println()也可以是System.out.print("\n")
    */
        // 用for循环判断从100到1000之间的所有整数能否被5和6整除
        boolean bool = false;   //打标:如果能同时被5和6整除则设置为true
        int n = 0;             //计数变量,每满10换行
        for(int i = 100; i < 1001; ++i){
            // 判断从100到1000之间的所有整数能否被5和6整除
            bool = false;
            if((i % 5 == 0) && (i % 6 == 0)){
                bool = true;
            }
            // 如果能同时被整除:输出
            if (bool){
                System.out.print(i + " ");
                ++n;
            }
            // 输出10个变量换行
            if(n == 10){
                System.out.println();
                n = 0;
            }
        }
    }
}


  • 在这里插入图片描述
    解:
    用for循环判断从100到1000之间的所有整数能否被5和6整除
    如果能被整除,便直接用if判断语句输出
    if语句中再嵌套一个条件判断语句,当输出个数为10时,输出一个换行符(可以是System.out.println()也可以是System.out.print(“\n”))
public class Test5_10 {
    public static void main(String[] args) {
        // 用for循环判断从100到1000之间的所有整数能否被5和6整除
        boolean bool = false;   //打标:如果能同时被5和6整除则设置为true
        int n = 0;             //计数变量,每满10换行
        for(int i = 100; i < 1001; ++i){
            // 判断从100到1000之间的所有整数能否被5和6整除
            bool = false;
            if((i % 5 == 0) && (i % 6 == 0)){
                bool = true;
            }
            // 如果能同时被整除:输出
            if (bool){
                System.out.print(i + " ");
                ++n;
            }
            // 输出10个变量换行
            if(n == 10){
                System.out.println();
                n = 0;
            }
        }
    }
}

  • 在这里插入图片描述
    解:
    从2循环判断到number / 2
    每找到一个数将其打印出来 ,并将number / i
    如果该数没有除数
    就直接将其打印
import java.util.Scanner;
public class Demo40 {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number:");
        int number = input.nextInt();
        while (true) {
            boolean flag = true;
            for (int i = 2; i <= number / 2; i++) {
                if (number % i == 0) {
                    System.out.print(i + " ");
                    number = number / i;
                    flag = false;
                    break;
                }

            }
            if (flag) {
                System.out.println(number);
            break;
            }
        }
    }
}



在这里插入图片描述

public class Demo41{
    public static void main(String[] args){
        //一共循环7次
        for(int i=1; i <= 7; i++) {
            //每次先打印空格,空格规律为7-i
            for(int k=1; k<= 7-i; k++) {
                System.out.print("  ");
            }
            //再打印数字
            for(int j=-(i-1); j<=i-1; j++) {
                System.out.print(Math.abs(j)+1+" ");
            }
            System.out.println();
        }
    }
}




  • 在这里插入图片描述
public class Test5_18 {
    public static void main(String[] args) {
        // 0:打印表头
        System.out.println("图案1           图案2           图案3           图案4");

        int lines = 6;
        for(int n = 1;n <= lines;n++){
            // (图案1数字部分)打印数字从1到n;
            for(int a = 1;a <= n;a++)
                System.out.printf("%d ", a);
            // (图案1空格部分)打印2 * (lines - n)个空格;
            if(lines != n){
                for(int b = lines - n;b > 0;b--)
                    System.out.print("  ");
            }

            // (分隔)打印3个空格来分隔不同图案;
            System.out.print("    ");

            // (图案2数字部分)从1打印到(lines-n+1);
            for(int c = 1;c < (lines - n + 2); c++){
                System.out.printf("%d ", c);
            }
            // (图案2空格部分)打印2 * (n - 1)个空格;
            if(n != 1){
                for(int d = 1;d <= n - 1;d++)
                    System.out.print("  ");
            }
            // (分隔)打印3个空格来分隔不同图案;
            System.out.print("    ");

            // (图案3空格部分)打印2 * (lines - n)个空格;
            if(n != 6){
                for(int e = 1;e < (lines - n + 1);e++)
                    System.out.print("  ");
            }
            // (图案3数字部分)从n打印到1;
            for(int f = n; f > 0;f--)
                System.out.printf("%d ",f);
            // (分隔)打印3个空格来分隔不同图案;
            System.out.print("    ");

            // (图案4空格部分)打印2 * (n - 1)个空格;
            if(n != 1){
                for(int g = 1;g < n;g++)
                    System.out.print("  ");
            }
            // (图案4数字部分)从1打印到(lines - n + 1)
            for(int h = 1;h < lines - n + 2;h++)
                System.out.printf("%d ", h);

            // 换行
            System.out.println();
        }
    }
}



在这里插入图片描述

public class Demo43 {
    public static void main(String[] args) {
        
        for (int i = 1; i <= 8; i++) {
            for (int k = 1; k <= 8 - i; k++) {
                System.out.print("    ");
            }
            for (int j = 1 - i; j <= i - 1; j++) {
                int num = (int) Math.pow(2,i - 1 - Math.abs(j));
                System.out.printf("%4d",num);
            }
            
            System.out.println();
        }
    }
}


在这里插入图片描述

public class Demo44 {
    public static void main(String[] args) {
        int count = 0;
        //循环2到1000 以内的素数
        for (int number = 2; number <= 1000; number++) {
            boolean flag = true; 
            //判断是否为素数
            for (int i = 2; i <= number / 2; i++) {
                if (number % i == 0) {
                    flag = false;
                    break;
                }
            }
            //如果是就输出
            if (flag) {
                System.out.print(number + "\t");
                count++;
                if (count % 8 == 0) {
                    System.out.println();
                }
            }
        }
    }
}




  • 在这里插入图片描述
public class Demo45{
    public static void main(String[] args){
        double sum=0;
        //i的循环累加步长为2
        for(int i=1; i<=97; i+=2) {
            sum += i * 1.0 / (i+2);
        }
        System.out.println(sum);
    }
}



在这里插入图片描述

/*
4*(1-1/3+1/5-1/7+……+Math.pow(-1, i+1)/(2i-1)))
=4(1-1/3+1/5-1/7+1/9-……-Math.pow(-1, i+1)/(2i-3)+Math.pow(-1, i+1)/(2i-1))
=4*((1-1/3)+(1/5-1/7)+(1/9-1/11)+……-Math.pow(-1, i+1)/(2i-3)+Math.pow(-1, i+1)/(2i-1))
因为i均为偶数,所以公式最后一个元素符号为负
原式=4*((1-1/3)+(1/5-1/7)+(1/9-1/11)+……+(Math.pow(-1, i+1)/(2i-3)+Math.pow(-1, i+1)/(2i-1)))
=4*(2.0/(1 * 3)+2.0/(5 * 7)+2.0/(9 * 11)+……+2.0/((2 * i-3) * (2 * i-1)))
=8*(1.0/(1 * 3)+1.0/(5 * 7)+1.0/(9 * 11)+……+1.0/((2 * i-3) * (2 * i-1)))
————————————————
版权声明:本文为CSDN博主「有只程序猿」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_46356698/article/details/119857513
*/
public class Demo46 {
    public static void main(String[] args) {
        double formula = 0;
        for( int i = 10000; i <= 100000 ; i += 10000 ){
            formula = 0;
            for ( int n = 1 ; n <= i / 2; n++ ){
                formula += 1.0 / ( ( 4 * n - 3 ) * ( 4 * n - 1) );
            }
            formula = 8 * formula ;
            System.out.printf("当i=%d时,结果为%f\n", i, formula);
        }
    }
}

  • 在这里插入图片描述

public class Demo47{
    public static void main(String[] args){        
        double sum = 1;
        
        int max = 10;
        //阶乘数从1开始
        int temp = 1;
        for(int i=1; i < max; i++) {
            temp=temp * i;
            sum += 1.0 / temp;
        }
        System.out.println(sum);
    }
}



在这里插入图片描述
解:从外向内循环选择语句:
遍历6到10000(不含)(假设为i)
找出i的所有除数(不含i本身)+验证所有除数之和是否等于i本身

public class Demo48 {
    public static void main(String[] args) {
        int temp = 0;
        for (int i = 6; i <= 10000; i++){
            temp = 0;
            // 找出i的所有除数(n)
            for (int n = 1; n < i;n++){
                // 判断n是否为i的除数
                if (i % n == 0){
                    temp += n;
                }
            }
            // 判断除数之和是否为i
            if (temp == i)
                System.out.println(i+"为完全数");
        }
    }
}


  • 在这里插入图片描述
import java.util.Scanner;
import java.util.Random;
public class Demo49{
    public static void main(String[] args){
        String [] arr = {"剪刀","石头","布"};
        Scanner input = new Scanner(System.in);
        Random Random = new Random();
        //循环游戏,直到一方赢到两次为止
        int comi = 0;
        int useri = 0;
        while(true){
            //提示用户输入
            System.out.print("请输入(石头0)(剪刀1)(布2):");
            int user = input.nextInt();
            //随机生成
            int com = Random.nextInt(3);
            if(user == com){
                System.out.println("平局!!!电脑出了:" + arr[com] +"你出了:"+arr[user]);
            }else if(user - com == -1 || user - com == 2){
                System.out.println("你赢了!!!电脑出了:" + arr[com] +"你出了:"+arr[user]);
                useri++;
            }else {
                System.out.println("电脑赢了!!!电脑出了:" + arr[com] +"你出了:"+arr[user]);
                comi++;
            }
            if(comi == 2 && useri == 2){
                break;
            }
        }
    }
}


在这里插入图片描述
解:接收用户输入的10进制整数
对十进制整数进行转换
输出转换后的二进制整数

import java.util.Scanner;

public class Demo50 {

    public static void main(String[] args) {
        //1. 接收用户输入的10进制整数
        Scanner input = new Scanner(System.in);
        System.out.print("请输入一个十进制整数:");
        int decimal = input.nextInt();

        // 2. 对十进制整数进行转换:除2倒序的余数;以十进制整数形式存储二进制数
        int remainder = 0, binary = 0;
        for (int i = 1;decimal > 0;i *= 10){
            remainder = decimal % 2;
            decimal /= 2;
            binary += remainder * i;
        }

        // 3. 输出
        System.out.println(binary);
    }
}


在这里插入图片描述
解:这道题和5.37十进制转二进制基本一样,不过转换过程数字会变化而已

import java.util.Scanner;

public class Demo51 {
    public static void main(String[] args) {
        //1. 接收用户输入的10进制整数
        Scanner input = new Scanner(System.in);
        System.out.print("请输入一个十进制整数:");
        int decimal = input.nextInt();

        // 2. 对十进制整数进行转换:除8倒序的余数;以十进制整数形式存储八进制数
        int remainder = 0, binary = 0;
        for (int i = 1;decimal > 0;i *= 10){
            remainder = decimal % 8;
            decimal /= 8;
            binary += remainder * i;
        }

        // 3. 输出
        System.out.println(binary);
    }
}


在这里插入图片描述
解:维护maxn和count两个变量,max存储最大值而count存储它出现的次数。初始状态时,将第一个数值赋值给max而将count赋值为1。
接下来的每个数字逐个和max比较。如果这个数大于max,就将它赋值给max,count相应重置为1。如果这个数等于max,则count自增1

import java.util.Scanner;

public class Demo52 {
    public static void main(String[] args) {
        // 接收用户输入:以0结束
        Scanner input = new Scanner(System.in);
        System.out.print("Enter numbers:");

        // temp存储最大值,count_max存储次数,user_input接收输入
        int user_input = 0, temp = 0, count_max = 1;

        for (;;){
            // 判断是不是结尾(0)
            user_input = input.nextInt();
            if ( user_input == 0 )
                break;

            // 比较
            if (temp > user_input){
                //
            }else if (temp == user_input){
                count_max++;
            } else {
                temp = user_input;
                count_max = 1;
            }
        }

        // 输出结果
        System.out.println("The largest number is " + temp);
        System.out.println("The occurrence count of the largest number is " + count_max);
    }
}


在这里插入图片描述

import java.util.Scanner;
public class Demo53 {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("请输入第1个顶点坐标:");
        double x1 = input.nextDouble();
        double y1 = input.nextDouble();
        System.out.print("请输入第2个顶点坐标:");
        double x2 = input.nextDouble();
        double y2 = input.nextDouble();
        System.out.print("请输入第3个顶点坐标:");
        double x3 = input.nextDouble();
        double y3 = input.nextDouble();

        //0,0 0,1 1,0
        double a = Math.hypot(x1 - x2, y1 - y2);
        double b = Math.hypot(x1 - x3, y1 - y3);
        double c = Math.hypot(x2 - x3, y2 - y3);
        double A = Math.acos((a * a - b * b - c * c)/ (-2 * b * c));
        double B = Math.acos((b * b - a * a - c * c)/ (-2 * a * c));
        double C = Math.acos((c * c - b * b - a * a)/ (-2 * a * b));
        
        A = Math.round(Math.toDegrees(A));
        B = Math.round(Math.toDegrees(B));
        C = Math.round(Math.toDegrees(C));
        System.out.println(A);
        System.out.println(B);
        System.out.println(C);
    }
}



在这里插入图片描述

import java.util.Scanner;

public class Test4_10 {
    public static void main(String[] args) {
        String set1 =
                " 1 3 5 7\n" +
                        " 9 11 13 15\n" +
                        "17 19 21 23\n" +
                        "25 27 29 31";

        String set2 =
                " 2 3 6 7\n" +
                        "10 11 14 15\n" +
                        "18 19 22 23\n" +
                        "26 27 30 31";

        String set3 =
                " 4 5 6 7\n" +
                        "12 13 14 15\n" +
                        "20 21 22 23\n" +
                        "28 29 30 31";

        String set4 =
                " 8 9 10 11\n" +
                        "12 13 14 15\n" +
                        "24 25 26 27\n" +
                        "28 29 30 31";

        String set5 =
                "16 17 18 19\n" +
                        "20 21 22 23\n" +
                        "24 25 26 27\n" +
                        "28 29 30 31";

        int day = 0;

        // Create a Scanner
        Scanner input = new Scanner(System.in);;

        // Prompt the user to answer questions
        System.out.println("Is your birthday in Set1?\n");
        System.out.println(set1);
        System.out.println("\nEnter N for No and Y for Yes:");
        String str = input.nextLine();
        char answer = str.charAt(0);

        if(answer == 'Y')
            day += 1;

        // Prompt the user to answer questions
        System.out.println("\nIs your birthday in Set2?\n");
        System.out.println(set2);
        System.out.println("\nEnter 0 for No and 1 for Yes:");
        str = input.nextLine();
        answer = str.charAt(0);

        if(answer == 'Y')
            day += 2;

        // Prompt the user to answer questions
        System.out.println("\nIs your birthday in Set3?\n");
        System.out.println(set3);
        System.out.println("\nEnter 0 for No and 1 for Yes: ");
        str = input.nextLine();
        answer = str.charAt(0);

        if(answer == 'Y')
            day += 4;

        // Prompt the user to answer questions
        System.out.println("\nIs your birthday in Set3?\n");
        System.out.println(set4);
        System.out.println("\nEnter 0 for No and 1 for Yes: ");
        str = input.nextLine();
        answer = str.charAt(0);

        if(answer == 'Y')
            day += 8;

        // Prompt the user to answer questions
        System.out.println("\nIs your birthday in Set3?\n");
        System.out.println(set5);
        System.out.println("\nEnter 0 for No and 1 for Yes: ");
        str = input.nextLine();
        answer = str.charAt(0);

        if(answer == 'Y')
            day += 16;

        System.out.println("\nYour birthday is " + day + "!");
    }
}


在这里插入图片描述
解:在for循环中:生成随机整数+赋值给counts数组(下标为生成的随机整数,counts[i]用来计数)
输出时:下标是这个数字,而对应数组的元素为次数

public class Test7_7 {
    public static void main(String[] args) {
        //1. 生成100个随机整数+赋值给counts数组
        int element = 0;
        int[] counts = new int[10];
        for (int count = 1; count <= 100 ; count++){
            // 生成随机整数
            element = (int) (Math.random() * 10);
            // 数组元素自增1
            counts[element]++;
        }

        //2. 输出时:下标是这个数字,而对应数组的元素为次数
        for (int i = 0 ; i < 10 ; i++){
            System.out.println(i + " 出现了" + counts[i] + "次");
        }
    }
}


在这里插入图片描述
解:已知r(中心到顶点距离),代入边长公式求出边长,边长再代入面积公式
输出时保留2位小数prinf()

import java.util.Scanner;

public class Test4_1 {
    public static void main(String[] args) {
        final double PI = Math.PI;

        // 获取用户输入数据(r)
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the length from the center to a vertex: ");
        double r = input.nextDouble();

        // 代入边长公式求出边长
        double s = 2 * r * Math.sin(PI / 5);

        // 边长再代入面积公式
        double area = (5 * s * s) / (4 * Math.tan(PI / 5));

        //输出
        System.out.printf("The area of the pentagon is %.2f", area);
    }
}



在这里插入图片描述
解:计算正多边形面积公式:
area = (n * s * s) / (4 * Math.tan(Math.PI / n))

import java.util.Scanner;

public class Test4_5 {
    public static void main(String[] args) {
        // 获取数据
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the number of sides: ");
        int n = input.nextInt();
        System.out.println("Enter the side: ");
        double s = input.nextDouble();

        // 代入公式
        double area = (n * s * s) / (4 * Math.tan(Math.PI / n));

        // 输出结果
        System.out.println("The area of the polygon is " + area);
    }
}


在这里插入图片描述
解:强转为char即可

import java.util.Scanner;

public class Test4_8 {
    public static void main(String[] args) {
        // 获取数据
        Scanner input = new Scanner(System.in);
        System.out.println("Enter an ASCII code: ");
        int i = input.nextInt();

        // 转为ASCII码格式
        char ch = (char)i;
        System.out.println(ch);
    }
}


在这里插入图片描述
解:获取数据后进行合法性判断
转化为16进制
输出

import java.util.Scanner;

public class Test4_11 {
    public static void main(String[] args) {
        // 接收输入
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a decimal value (0 to 15)");
        int decimalValue = input.nextInt();

        // 合法性判断
        if(decimalValue < 0 || decimalValue > 15){
            System.out.println(decimalValue + " is an invald input");
            System.exit(1);
        }

        // 转换为16进制数:10A 11B 12C 13D 14E 15F
        String result;
        if( decimalValue < 10){
            System.out.println("The hex value is " + decimalValue);
        }else{
            switch (decimalValue){
                case 10:result="A";break;
                case 11:result="B";break;
                case 12:result="C";break;
                case 13:result="D";break;
                case 14:result="E";break;
                default:result="F";
            }
            System.out.println("The hex value is " + result);
        }
    }
}


在这里插入图片描述
解:接收输入
使用String对象的比较方法:s0.contains(s1)如果s1是s0的子字符串,则返回true
输出结果

import java.util.Scanner;

public class Test4_22 {
    public static void main(String[] args) {
        // 接收输入
        Scanner input = new Scanner(System.in);
        System.out.println("Enter string s1: ");
        String s1 = input.next();
        System.out.println("Enter string s2: ");
        String s2 = input.next();

        // 判断s2是否为s1子串
        boolean bool = s1.contains(s2);

        // 输出结果
        if(bool)
            System.out.println(s2 + " is a substring of " + s1);
        else
            System.out.println(s2 + " is not a substring of " + s1);
    }
}



在这里插入图片描述
解:该问题可以简化为:
判断输入的字符串格式是否为:三个数字-两个数字-四个数字

获取用户输入
判断长度是否符合要求(11位)
将每位分别转为char类型,再强转为int类型(ASCII码)
判断第4个、第7个int类型数值是否为45(’-'在ASCII码对应45)
判断其它int数值是否在’0’~'9’之间(即[45, 54])
如第4步、第5步均为是,则格式合法
代码

import java.util.Scanner;

public class Test4_21 {
    public static void main(String[] args) {
        // 获取用户输入
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a SSN: ");
        String str = input.next();

        // 判断长度是否符合要求(11位)
        int length = str.length();
        if(length != 11){
            System.out.println(str + " is an invalid social security number");
            System.exit(1);
        }

        //将每位分别转为char类型,再强转为int类型(ASCII码)
        char c1 = str.charAt(0);int i1 = (int) c1;
        char c2 = str.charAt(1);int i2 = (int) c2;
        char c3 = str.charAt(2);int i3 = (int) c3;
        char c4 = str.charAt(3);int i4 = (int) c4;
        char c5 = str.charAt(4);int i5 = (int) c5;
        char c6 = str.charAt(5);int i6 = (int) c6;
        char c7 = str.charAt(6);int i7 = (int) c7;
        char c8 = str.charAt(7);int i8 = (int) c8;
        char c9 = str.charAt(8);int i9 = (int) c9;
        char c10 = str.charAt(9);int i10 = (int) c10;
        char c11 = str.charAt(10);int i11 = (int) c11;

        // 判断第4个、第7个int类型数值是否为45('-'在ASCII码对应45)
        boolean bool4 = false, bool7 = false, bool_47 = false;
        if(i4 == 45)
            bool4 = true;
        if(i7 == 45)
            bool7 = true;
        if(bool4 && bool7)
            bool_47 = true;

        // 判断其它int数值是否在'0'~'9'之间(即[45, 54])
        boolean bool1 = false, bool2 = false, bool3 = false, bool5 = false, bool6 = false;
        boolean bool8 = false, bool9 = false, bool10 = false, bool11 = false, bool_13 = false;
        if(i1 > 44 && i1 < 55)
            bool1 = true;
        if(i2 > 44 && i2 < 55)
            bool2 = true;
        if(i3 > 44 && i3 < 55)
            bool3 = true;
        if(i5 > 44 && i5 < 55)
            bool5 = true;
        if(i6 > 44 && i6 < 55)
            bool6 = true;
        if(i8 > 44 && i8 < 55)
            bool8 = true;
        if(i9 > 44 && i9 < 55)
            bool9 = true;
        if(i10 > 44 && i10 < 55)
            bool10 = true;
        if(i11 > 44 && i11 < 55)
            bool11 = true;
        if(bool1 && bool2 && bool3 && bool5 && bool6 && bool8 && bool9 && bool10 && bool11)
            bool_13 = true;

        // 如第4步、第5步均为是,则格式合法
        if(bool_13 && bool_47)
            System.out.println(str + " is a valid social security number");
        else
            System.out.println(str + " is an invalid social security number");
    }
}


在这里插入图片描述
解:获取用户输入的字符串
可以尝试使用charAt()从最后一个元素输出到第一个,下标从(length-1)开始、0结束,中间不空格不空行

import java.util.Scanner;

public class Test5_46 {
    public static void main(String[] args) {
        // 获取字符串
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = input.next();

        // 获取字符串的每个字符
        System.out.print("The reveresd string is ");
        for (int i = str.length() - 1; i >= 0; i--){
            System.out.print(str.charAt(i));
        }
    }
}


在这里插入图片描述

import java.util.Scanner;

public class Test3_9 {
    public static void main(String[] args) {
        // 获取数据
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the first 9 digits of an ISBN as integer: ");
        int i = input.nextInt();
        int temp = i;

        // 处理数据:赋值d1~d9
        int d1 = i / 100000000;
        i %= 100000000;
        int d2 = i / 10000000;
        i %= 10000000;
        int d3 = i / 1000000;
        i %= 1000000;
        int d4 = i / 100000;
        i %= 100000;
        int d5 = i / 10000;
        i %= 10000;
        int d6 = i / 1000;
        i %= 1000;
        int d7 = i / 100;
        i %= 100;
        int d8 = i / 10;
        i %= 10;
        int d9 = i;
        System.out.println(d1+" "+d2+" "+d3+" "+d4+" "+d5+" "+d6+" "+d7+" "+d8+" "+d9);
        // 求d10
        int d10 =(1 * d1 + 2 * d2 + 3 * d3 + 4 * d4 + 5 * d5 + 6 * d6 +7 * d7 + 8 * d8 + 9 * d9) % 11;

        // 输出
        String str;
        if(d10 < 10) {
            str = "" + temp + d10;
        }else{
            str = "" + temp + "X";
        }
        System.out.println("The ISBN-10 number is " + str);
    }
}


  • 在这里插入图片描述
    解:获取字符串
    通过for循环将字符串中的奇数位置字符抽出(charAt())并输出
import java.util.Scanner;

public class Test5_48 {
    public static void main(String[] args) {
        // 1. 获取字符串
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = input.nextLine();

        // 2. 通过for循环将字符串中的奇数位置字符抽出(charAt())并输出
        for (int i = 0; i < str.length() ; i += 2){
            System.out.print(str.charAt(i));
        }
    }
}


在这里插入图片描述
解:获取用户输入
通过循环获取字符串每个字符(charAt()方法),先强转至char,再强转为int型(此时就为ASCII码形式了)
判断int型数字是否在ASCII大写字母[65, 90]范围内,如果在,则对应的计数变量自增1
输出结果

import java.util.Scanner;

public class Test5_50 {
    public static void main(String[] args) {
        //1. 获取用户输入
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = input.nextLine();      // nextLine()读1行,next()读空格后的元素(空格起止)

        // 2. 将字符串每一位单独提取并转为char,进而转为int以获取每个字符的ASCII码形式
        int temp = 0, upper = 0;
        for ( int i = 0 ; i < str.length(); i++){
            char ch = (char) str.charAt(i);
            temp = (int) ch;
            //3. 判断temp是否在大写字母范围内
            if (temp >= 65 && temp <= 90)
                ++upper;
        }

        // 输出结果
        System.out.println("The number of uppercase letters is " + upper);
    }
}


在这里插入图片描述
解:
获取用户输入的两个字符串(假设一个为a,一个为b)
对a和b同时用substring()方法进行切割(从下标0到下标1、从下标0到下标2……),切割后得到的子字符串进行比较,直到不匹配为止
输出不匹配之前(进行比较)的字符串

import java.util.Scanner;

public class Test5_51 {
    public static void main(String[] args) {
        // 1. 获取用户输入的两个字符串(假设一个为a,一个为b)
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the first string: ");
        String str_1 = input.nextLine();
        System.out.print("Enter the second string: ");
        String str_2 = input.nextLine();

        // 获取str_1和str_2的长度
        int length_1 = str_1.length();
        int length_2 = str_2.length();
        int length = Math.max(length_1, length_2);

        // 2. 对a和b同时用substring()方法进行切割,并进行比较,直到不匹配为止
        String cut_str1 = "", cut_str2="", temp="";
        int count = 0;
        for (int i = 1 ; i <= length ; i++){
            cut_str1 = str_1.substring(0,i);
            cut_str2 = str_2.substring(0,i);
            if (cut_str1.equals(cut_str2)){
                temp = cut_str1;
                ++count;
            } else {
                break;
            }
        }

        //3. 输出不匹配之前(进行比较)的字符串
        if (count != 0){
            System.out.print("The common prefix is " + temp);
        }else
            System.out.print(str_1 + " and " + str_2 + " have no common prefix");

    }
}


  • 在这里插入图片描述
    解:提示:使用求余操作符%提取数字,用除号/去掉提取出来的数字。例如,使用234%10提取4,使用234/10去掉4。使用一个循环来返回提取和去掉每位数字,直到所有位数都提取完为止。编写程序提示用户输入一个整数,然后显示这个整数所有数字之和
import java.util.Scanner;

public class Test6_2 {
    public static void main(String[] args) {
        // 接收用户输入
        Scanner input = new Scanner(System.in);
        System.out.print("请输入一个整数:");
        long n = input.nextLong();

        // 传入方法并接收返回
        long result = sumDigits(n);

        // 别写完方法忘主方法这里的输出
        System.out.println("整数" + n + "的各位数字之和为" + result);
    }

    public static long sumDigits(long n){
        // 存储变量(保存和)
        long result = 0;
        // 循环:提取每位数字
        for(; n >= 1 ; n /= 10){
            result += n % 10;
        }
        return result;
    }
}


在这里插入图片描述
解:以上给出的两个方法,第一个是接收一个int型数值再返回一个int型数值,第二个是接收一个int型数值并返回boolean布尔值
一般这本黑皮书上的题对应相应的英文,直接翻译过来就能知道想干什么
主方法调用(判断是不是回文数):isPalindrome()方法
isPalindrome方法()调用(对数值进行逆转):reverse()方法

如果没有任何提示,且题目里也没有说明、无法翻译:
这个时候可以灵活使用,除了上面的方案外,还可以(这种方法略显复杂且冗余):
主方法调用revese()方法:假设revese()方法返回0时为回文数,主方法内需要根据接收到的数值与0是否全等判断
reverse()方法调用isPalindrome()方法:isPalindrome()方法可以返回是否为回文数的boolean值,reverse()方法再将boolean值转化为0或其他值返回给主方法

注意传入的整数可能是正整数、负整数和0

import java.util.Scanner;

public class Test6_3 {
    public static void main(String[] args) {
        // 接收用户输入
        Scanner input = new Scanner(System.in);
        System.out.print("请您输入一个整数:");
        int user_input = Math.abs(input.nextInt());

        // 提前拦截输入为0
        if (user_input == 0){
            System.out.print("输入整数是0,是回文数");
            System.exit(1);
        }

        // 判断是否为回文数,并根据返回值确定输出内容
        boolean bool = isPalindrome(user_input);
        if (bool)
            System.out.print("输入整数是回文数");
        else
            System.out.print("输入整数不是回文数");
    }
    // 判断输入数值是否为回文数
    public static boolean isPalindrome(int number){
        return number == reverse(number);
    }
    // 返回number的回文数
    public static int reverse(int number){
        String str = "";       // 临时保存转换后的数字(以String型存储)
        for (;number > 0;number /= 10){
            str += number % 10;
        }
        return Integer.parseInt(str);
    }
}


在这里插入图片描述
解:主方法将n传入方法printMatrix()中
在方法printMatrix()中打印矩阵

import java.util.Scanner;

public class Test6_17 {
    public static void main(String[] args) {
        // 接收用户输入
        Scanner input = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = input.nextInt();

        // 将值n传递给方法printMatrix()
        printMatrix(n);
    }
    public static void printMatrix(int n){
        for (int x = 1; x <= n;x++){
            int temp = 0;
            for (int y = 1; y <= n;y++){
                temp = (int) (Math.random() * 2);
                System.out.print(temp + "\t");
                if (y == n)
                    System.out.println();
            }
        }
    }
}


在这里插入图片描述
解:至少8位:字符串长度大于等于8
仅能包含字母和数字:字符串每位的ASCII码只能在如下三个区间:[48, 57]、[65, 90]、[97, 112]
必须至少包含两个数字:至少在[48, 57]区间出现两次
编写一个返回字符ASCII码的方法:public static int char_to_ASCII(char ch)
主方法则实现其他功能

import java.util.Scanner;

public class Test6_18 {
    public static void main(String[] args) {
        // 接收用户输入
        Scanner input = new Scanner(System.in);
        System.out.print("请输入一个密码:");
        String str = input.nextLine();

        // 1. 至少8位:字符串长度大于等于8
        int length = str.length();
        if (length < 8){
            System.out.println("Invalid Password");
            System.exit(1);
        }

        // 2. 转ASCII
        boolean bool1 = true, bool2 = false;
        int count = 0;
        for (int i = 0 ;i < length;i++){
            int int_ASCII = char_to_ASCII(str.charAt(i));
            // 仅能包含字母和数字;[48, 57]、[65,  90]、[97, 122]
            if (int_ASCII < 48 || (int_ASCII > 57 && int_ASCII < 65) || (int_ASCII > 90 && int_ASCII < 97) || int_ASCII > 122){
                bool1 = false;
                break;
            }
            // 必须至少包含两个数字
            if (int_ASCII >= 48 && int_ASCII <= 57)
                count++;
        }
        if (count >= 2)
            bool2 = true;

        // 输出判断
        if (bool1 && bool2)
            System.out.println("Valid Password");
        else
            System.out.println("Invalid Password");
    }
    public static int char_to_ASCII(char ch){
        return (int) (ch);
    }
}


  • 在这里插入图片描述
    解:主方法读入三条边的值
    将三条边的值传入isValid方法判断三条边的值是否有效
    isValid方法通过排序取两条最短边相加判断是否大于第三边的长度,并返回boolean值
    如果isValid方法返回true,则将三条边的值传入area方法计算面积
    area方法使用上面三角形面积计算公式求出面积并返回数据
    主方法返回数据
import java.util.Scanner;

public class MyTriangle {
    public static void main(String[] args) {
        // 1. 主方法读入三条边的值
        Scanner input = new Scanner(System.in);
        System.out.print("请输入三条边的值:");
        double side1 = input.nextDouble(), side2 = input.nextDouble(), side3 = input.nextDouble();

        // 3. 将三条边的值传入isValid方法判断三条边的值是否有效
        if (!isValid(side1, side2, side3)){
            System.out.println("输入无效");
            System.exit(1);
        }

        // 5. 将三条边的值传入area方法计算面积并输出
        System.out.println("这三角形的面积为:"+area(side1, side2, side3));
    }
    // 2. 将三条边的值传入isValid方法判断三条边的值是否有效
    public static boolean isValid(double side1, double side2, double side3){
        double temp = 0;
        if (side1 > side2){
            temp = side1;
            side1 = side2;
            side2 = temp;
        }
        if (side1 > side3){
            temp = side1;
            side1 = side3;
            side3 = temp;
        }
        if (side2 > side3){
            temp = side2;
            side2 = side3;
            side3 = temp;
        }
        return (side1 + side2 > side3);
    }
    // 4. area方法使用上面三角形面积计算公式求出面积并返回数据
    public static double area(double side1, double side2, double side3){
        double s = (side1 + side2 + side3) / 2;
        return Math.pow(s*(s-side1)*(s-side2)*(s-side3), 0.5);
    }
}



在这里插入图片描述
解:主方法中:接收字符串、将字符串整体传递给countLetters方法、接收countLetters方法返回值并输出
countLetters方法:接收到之后,将字符串中的每一个字符单独抽出转为ASCII码,判断其数值是否在[65, 90]或[97, 122]中

import java.util.Scanner;

public class Test6_20 {
    public static void main(String[] args) {
        //接收字符串
        Scanner input = new Scanner(System.in);
        System.out.print("请输入一个字符串:");
        String str = input.nextLine();

        //将字符串整体传递给countLetters方法并接收countLetters方法返回值并输出
        System.out.println("输入的字符串字母有:" + countLetters(str) + "个");
    }
    // 计算字符串中的字母数量
    public static int countLetters(String n){
        int length = n.length();
        int str_ASCII = 0, count = 0;
        for (int i = 0;i < length;i++){
            str_ASCII = (int) (n.charAt(i));
            if ((str_ASCII >= 76 && str_ASCII <= 90) || (str_ASCII >= 97 && str_ASCII <= 122))
                count++;
        }
        return count;
    }
}

在这里插入图片描述

import java.util.Scanner;

public class Test6_22 {
    public static void main(String[] args) {
        // 接收需要求平方根的n值(以long接收)
        Scanner input = new Scanner(System.in);
        System.out.print("请输入一个n值:");
        long n = input.nextLong();

        // 传入n值
        double feedback = sqrt(n);

        // 返回sqrt值
        System.out.println(feedback);
    }

    public static double sqrt(long n){
        // 第一轮:lastGuess取整
        double nextGuess = 2, lastGuess = 0;
        for (lastGuess = 1 ; nextGuess - lastGuess >= 0.0001 ; lastGuess++){
            nextGuess = (lastGuess + n / lastGuess ) / 2;
        }
        // 第二轮:获取lastGuess大致范围后精确到小数点后两位
        for (lastGuess = nextGuess; nextGuess - lastGuess >= 0.0001 ; lastGuess += 0.01){
            nextGuess = (lastGuess + n / lastGuess ) / 2;
        }
        return nextGuess;
    }
}


在这里插入图片描述
解:(回文素数)回文素数是指一个数同时为素数和回文数。
例如,131是一个素数也是回文数,数字313和757也是如此。
编程程序,显示前100个回文素数,每行显示10个数,数字中间用一个空格隔开

public class Test6_26 {
    public static void main(String[] args) {
        int count = 0;
        for (int i = 2; count <= 100;i++){
            if (palindromeNumber(i) && primeNumber(i)){
                System.out.print(i + " ");
                count++;
                if (count % 10 == 0)
                    System.out.println();
            }
        }
    }
    public static boolean palindromeNumber(int i){
        // 这是判断是否是回文数
        if (i / 10 == 0)
            return true;
        else if (i / 100 == 0)
            return (i / 10) == (i % 10);
        else if (i / 1000 == 0)
            return (i / 100) == (i % 10);
        else if (i / 10000 == 0)
            return ((i / 1000) == (i % 10)) && ((i % 1000 / 100) == (i % 100 / 10));
        else
            return ((i / 10000) == (i % 10)) && ((i % 10000 / 1000) == (i % 100 / 10));
    }
    public static boolean primeNumber(int i){
        boolean bool = true;
        for (int n = 2; n <= i / 2 ;n++){
            if ( i % n == 0){
                bool = false;
                break;
            }
        }
        return bool;
    }
}



在这里插入图片描述
解:两个反素数条件:①一个素数倒过来还是个素数;②两个素数不相等(非回文素数)

public class Test6_27 {
    public static void main(String[] args) {
        int count = 0;  // 计数变量
        // 循环遍历
        for (int i = 10; count <= 100; i++){
            if (isPrimeNumber(i) && isPrimeNumber(reverse(i)) && (i != reverse(i))){
                System.out.print(i+" ");
                count++;
                if (count % 10 == 0)
                    System.out.println();
            }
        }
    }
    // 倒置
    public static int reverse(int i){
        // 通过将int型数转为String实现倒置
        String str0 = i +"", str1 = "";
        int length = str0.length();
        for (int n = length-1; n >= 0; n--){
            str1 += str0.charAt(n);
        }
        // 再将转换后的String转为int型输出
        return Integer.parseInt(str1);
    }
    // 判断是否是素数
    public static boolean isPrimeNumber(int i){
        boolean bool = true;
        for (int n = 2; n <= i / 2 ;n++){
            if ( i % n == 0){
                bool = false;
                break;
            }
        }
        return bool;
    }
}


在这里插入图片描述
解:从p=1开始遍历到p=31,计算2^p-1的结果
对结果判断是否是素数,如果是素数则将本行输出

public class Test6_28 {
    public static void main(String[] args) {
        // 打印表头和分隔符
        System.out.println("p\t\t2^p-1");
        System.out.println("——————————————");

        // 遍历p
        for (int p = 1; p <= 31; p++){
            if (isPrimeNumber((int) (Math.pow(2, p)-1))){
                System.out.println(p+"\t\t" + (int) (Math.pow(2, p)-1));
            }
        }
    }
    public static boolean isPrimeNumber(int i){
        if (i == 1) {return false;}
        for (int n = 2;n <= i / 2;n++ ){
            if (i % n == 0){
                return false;
            }
        }
        return true;
    }
}


在这里插入图片描述
解:遍历从2到997的所有正整数(这部分作为较小值),较大值则加2即可
对两个值判断是否为素数,当两个值都是素数时按照规定格式输出到控制台

public class Test6_29 {
    public static void main(String[] args) {
        // 遍历
        for (int a = 2; a <= 997;a++){
            if (isPrimeNumber(a) && isPrimeNumber(a+2)){
                System.out.println("(" + a + "," + (a+2) + ")");
            }
        }
    }
    // 判断值是否为素数
    public static boolean isPrimeNumber(int i){
        if (i == 1){return false;}
        for (int n = 2; n <= i / 2;n++){
            if (i % n == 0)
                return false;
        }
        return true;
    }
}


  • 在这里插入图片描述
    解:已知r(中心到顶点距离),代入边长公式求出边长,边长再代入面积公式
    输出时保留2位小数prinf()
import java.util.Scanner;

public class Test4_1 {
    public static void main(String[] args) {
        final double PI = Math.PI;

        // 获取用户输入数据(r)
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the length from the center to a vertex: ");
        double r = input.nextDouble();

        // 代入边长公式求出边长
        double s = 2 * r * Math.sin(PI / 5);

        // 边长再代入面积公式
        double area = (5 * s * s) / (4 * Math.tan(PI / 5));

        //输出
        System.out.printf("The area of the pentagon is %.2f", area);
    }
}


在这里插入图片描述
解:计算正多边形面积公式:
area = (n * s * s) / (4 * Math.tan(Math.PI / n))

import java.util.Scanner;

public class Test4_5 {
    public static void main(String[] args) {
        // 获取数据
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the number of sides: ");
        int n = input.nextInt();
        System.out.println("Enter the side: ");
        double s = input.nextDouble();

        // 代入公式
        double area = (n * s * s) / (4 * Math.tan(Math.PI / n));

        // 输出结果
        System.out.println("The area of the polygon is " + area);
    }
}


递归解决斐波那契数列
解:注意:由于int的取值范围有限,最大值为 (2^32)-1 = 2147483647,当n>46的时候,会发生取值范围溢出的情况,所以这里如果想要验证n>46时的计算耗时情况,请将返回值类型int改为long。 例如第2种方法。就将int改为了long。

public static int fibonacci(int n){

        if (n == 1 || n == 2) {             //特殊情况,分开讨论
            return 1;
        }
        if (n > 2) {
            return fibonacci(n - 1) + fibonacci(n - 2);     //递归调用
        }
        return -1;              //如果输入错误的n,一律返回-1
    }


递归解决汉诺塔问题

package ChapterFive.Part2;
 
/**
 * n阶汉诺塔的移动步骤
 * 
 * @author meng
 *
 */
public class HanoiDemo {
 
	private static int count = 0;
	
	public static void main(String[] args) {
 
		hanio(3,'x','y','z');
		System.out.println(" 总共移动了 " + count + " 次" );
	}
/**
 * 移动
 * @param n 共需要移动的盘子
 * @param x  从起始位置
 * @param y  借助辅助塔 
 * @param z  移动到终止位置
 */
	public static void hanio(int n, char x, char y, char z) {
		count++;
		if(n==1) {
			move(x,n,z);
		}else {
			hanio(n-1,x,z,y);
			move(x,n,z);
			hanio(n-1,y,x,z);
		}
		
	}
/**
 * 打印移动
 * @param x  从起使位置
 * @param n  移动第几个盘子
 * @param y  要移动到的最终位置
 */
	private static void move(char x, int n, char y) {
		// TODO Auto-generated method stub
		System.out.println(" Move " + n + " from " + x + " to " + y);
	}
}

在这里插入图片描述
解:维护maxn和count两个变量,max存储最大值而count存储它出现的次数。初始状态时,将第一个数值赋值给max而将count赋值为1。
接下来的每个数字逐个和max比较。如果这个数大于max,就将它赋值给max,count相应重置为1。如果这个数等于max,则count自增1

import java.util.Scanner;

public class Test5_41 {
    public static void main(String[] args) {
        // 接收用户输入:以0结束
        Scanner input = new Scanner(System.in);
        System.out.print("Enter numbers:");

        // temp存储最大值,count_max存储次数,user_input接收输入
        int user_input = 0, temp = 0, count_max = 1;

        for (;;){
            // 判断是不是结尾(0)
            user_input = input.nextInt();
            if ( user_input == 0 )
                break;

            // 比较
            if (temp > user_input){
                //
            }else if (temp == user_input){
                count_max++;
            } else {
                temp = user_input;
                count_max = 1;
            }
        }

        // 输出结果
        System.out.println("The largest number is " + temp);
        System.out.println("The occurrence count of the largest number is " + count_max);
    }
}


在这里插入图片描述
解:读入一个数,如果它是一个新数,则将它存储在数组中。如果该数已经在数组中,则忽略它输入之后,数组包含的都是不同的数

import java.util.Scanner;

public class Test7_5 {
    public static void main(String[] args) {
        // 声明一个数组
        int[] lst0 = new int[10];

        // 读取数据并传入数组
        Scanner input = new Scanner(System.in);
        System.out.print("Enter 10 numbers: ");
        int input_number = 0, count = 0;
        for (int x = 0 ; x < 10 ; x++){
            boolean bool = false;
            input_number = input.nextInt();
            for (int y = 0 ; y < x ; y++){
                if (lst0[y] == input_number){
                    bool = true;
                }
            }
            if ( !bool ){
                count++;
                lst0[count-1] = input_number;
            }
        }

        // 输出结果
        System.out.println("The number of distinct numbers is " + count);
        System.out.print("The distinct numbers are: ");
        for (int i = 0 ; i < count ; i++){
            System.out.print(lst0[i] + " ");
        }
    }
}



在这里插入图片描述
解:主方法step1:接收用户输入的10个double型值,使用double型数组接收
补全两个方法头的方法体
主方法step2:调用并接收返回值,输出这个返回值

import java.util.Scanner;

public class Test7_8 {
    public static void main(String[] args) {
        // 1. 主方法中:接收用户输入的10个double型值,使用double型数组接收
        Scanner input = new Scanner(System.in);
        System.out.print("请输入10个double型值:");
        double[] input_list = new double[10];
        for (int i = 0 ; i < 9 ; i++){
            input_list[i] = input.nextDouble();
        }

        // 3. 主方法step2:调用并接收返回值,输出这个返回值
        double average_d = average(input_list);
        System.out.println(average_d);
    }
    //2. 补全两个方法头的方法体
    public static int average(int[] array){
        int length = array.length;
        int sum = 0;
        for (int i = 0 ; i < length ; i++){
            sum += array[i];
        }
        return sum / length;
    }
    public static double average(double[] array){
        int length = array.length;
        double sum = 0;
        for (int i = 0 ; i < length ; i++){
            sum += array[i];
        }
        return sum / length;
    }
}


在这里插入图片描述
解:主方法:接收用户输入的5个数字(从控制台以数组形式接收),调用gcd方法、接收到的返回值进行输出
gcd方法:对接收到的数组一个一个找最大公约数,5个公约数中取最大的数并返回

import java.util.Scanner;

public class Test7_14 {
    public static void main(String[] args) {
        //接收用户输入的5个数字(从控制台以数组形式接收)
        Scanner input = new Scanner(System.in);
        System.out.print("请输入5个数字:");
        int length = 5;
        int[] lst = new int[length];
        for (int i = 0; i < length; i++){
            lst[i] = input.nextInt();
        }

        //调用gcd方法、接收到的返回值进行输出
        System.out.println(gcd(lst));
    }
    public static int gcd(int n1, int n2){
        int res = Math.min(n1,n2);
        while(res >= 0){
            if( (n1 % res == 0) && (n2 % res == 0))
                break;
            else
                --res;
        }
        return res;
    }
    public static int gcd(int...numbers){
        int len = numbers.length;
        int num = numbers[0];
        for (int i = 0; i < len; i++) {
            num = gcd(num, numbers[i]);
        }
        return num;
    }
}


在这里插入图片描述
解:主方法从控制台获取数据,赋值给数组
调用eliminateDuplicates方法,传入刚刚赋值完的数组
eliminateDuplicates方法:去掉重复值,返回新数组
主方法按照格式要求输出

import java.util.Scanner;

public class Test7_15 {         //1 2 3 2 1 6 3 4 5 2
    public static void main(String[] args) {
        // 1. 主方法从控制台获取数据,赋值给数组
        Scanner input = new Scanner(System.in);
        System.out.print("Enter 10 numbers: ");
        int length0 = 10;
        int[] lst_input = new int[length0];
        for (int i = 0; i < length0; i++){
            lst_input[i] = input.nextInt();
        }

        // 2. 调用eliminateDuplicates方法,传入刚刚赋值完的数组
        int[] lst_feedback = eliminateDuplicates(lst_input);

        // 4. 主方法按照格式要求输出
        System.out.print("The distinct numbers are: ");
        int temp = 0;
        for (int i = 0; i < 10; i++){
            temp = lst_feedback[i];
            if (temp != 0 || (i == 0 && temp == 0)){
                System.out.print(temp + " ");
            }
        }
    }
    public static int[] eliminateDuplicates(int[] list){
        int length = 10;
        // 计算list最大值: max
        int max = 0;
        for (int i = 0; i < length; i++){
            if (max < list[i])
                max = list[i];
        }
        // 声明创建一个以list最大值+1为长度的数组
        int[] lst_temp = new int[max + 1];
        // 原数组元素作为下标代入新数组,并将元素置为1
        for (int i = 0; i < length; i++) {
            lst_temp[list[i]] = 1;
        }
        // 把接收的数组list进行遍历,list的元素代入lst_temp的下标中
        // 将保留的list[i]用返回数组接收
        int[] feedback = new int[10];
        int count = 0;
        for (int i = 0 ; i <= max ; i++){
            if (lst_temp[i] == 1){
                feedback[count] = i;
                count++;
            }
        }
        return feedback;
    }
}


在这里插入图片描述
解:主方法:获取用户输入(定义list长度)
主方法:声明一个数组+获取用户输入(给list赋值)
主方法:调用方法isSorted,传入刚刚赋值好的数组,接收boolean返回值
主方法:根据返回值输出结果
isSorted方法:获取传入的数组长度为length
isSorted方法:声明一个数组,长度等于length
isSorted方法:将输入的数组复制给刚刚声明的数组
isSorted方法:对list进行排序(直接调用Arrays类的sort方法)
isSorted方法:对两个数组进行深度比较(equals(lis1, list2)),并直接输出返回值

import java.util.Arrays;
import java.util.Scanner;

public class Test7_19 {
    public static void main(String[] args) {
        //1. 主方法:获取用户输入(定义list长度)
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the size of the list: ");
        int length = input.nextInt();
        //2. 主方法:声明一个数组+获取用户输入(给list赋值)
        int[] list = new int[length];
        System.out.print("Enter the contents of the list: ");
        for (int i = 0 ; i < length ; i++){
            list[i] = input.nextInt();
        }
        //2+ 输出数组长度和元素
        System.out.print("The list has " + length + " integers ");
        for (int i = 0 ; i < length ; i++){
            System.out.print(list[i] + " ");
        }
        //3. 主方法:调用方法isSorted,传入刚刚赋值好的数组,接收boolean返回值
        boolean bool = isSorted(list);
        //4. 主方法:根据返回值输出结果
        if (bool)
            System.out.print("\nThe list is already sorted");
        else
            System.out.print("\nThe list is not sorted");
    }
    // isSorted方法:判断传入的数组是否已经排好序
    public static boolean isSorted(int[] list){
        //5. isSorted方法:获取传入的数组长度为length
        int length = list.length;
        //6. isSorted方法:声明2个数组,长度等于length
        int[] list_copy = new int[length];
        int[] list_copy_reverse = new int[length];
        //7. isSorted方法:将输入的数组复制给刚刚声明的两个数组(顺序不同)
        for (int i = 0 ; i < length ; i ++){
            list_copy[i] = list[i];
            list_copy_reverse[i] = list[length - i - 1];
        }
        //8. isSorted方法:对list进行排序(直接调用Arrays类的sort方法)
        Arrays.sort(list);
        //9. isSorted方法:对两个数组进行深度比较(equals(lis1, list2)),并直接输出返回值
        return Arrays.equals(list, list_copy) || Arrays.equals(list, list_copy_reverse);
    }
}


在这里插入图片描述
解:主方法:从控制台获取用户输入,先获取list1 size并赋值给length
主方法:声明一个数组,长度为length
主方法:通过循环接收list1 contents部分
主方法:以上步骤重复,接收list2
主方法:调用自定义方法equals,传入list1、list2,使用boolean接收方法结果
主方法:根据接收结果不同输出不同内容
equals方法:获取list1、list2长度并比较,如果长度不等则直接返回false
equals方法:遍历list1、list2数组,如果元素有不相等的情况则直接返回false
equals方法:如果遍历完后没有返回,则返回true

import java.util.Scanner;

public class Test7_26 {
    public static void main(String[] args) {
        //1. 主方法:从控制台获取用户输入,先获取list1 size并赋值给length
        Scanner input = new Scanner(System.in);
        System.out.print("Enter list1 size and contents: ");
        int length1 = input.nextInt();
        //2. 主方法:声明一个数组,长度为length
        int[] list1 = new int[length1];
        //3. 主方法:通过循环接收list1 contents部分
        for (int i = 0 ; i < length1 ; i++){
            list1[i] = input.nextInt();
        }
        //4. 主方法:以上步骤重复,接收list2
        System.out.print("Enter list2 size and contents: ");
        int length2 = input.nextInt();
        int[] list2 = new int[length2];
        for (int i = 0 ; i < length2 ; i++){
            list2[i] = input.nextInt();
        }
        //5. 主方法:调用自定义方法equals,传入list1、list2,使用boolean接收方法结果
        boolean bool = equals(list1, list2);
        //6. 主方法:根据接收结果不同输出不同内容
        if (bool){
            System.out.print("Two lists are strictly identical");
        }else
            System.out.print("Twu lists are not strictly identical");
    }
    public static boolean equals(int[] list1, int[] list2){
        //7. equals方法:获取list1、list2长度并比较,如果长度不等则直接返回false
        int length1 = list1.length, length2 = list2.length;
        if (length1 != length2)
            return false;
        //8. equals方法:遍历list1、list2数组,如果元素有不相等的情况则直接返回false
        for (int i = 0 ; i < length1 ; i++){
            if (list1[i] != list2[i])
                return false;
        }
        //9. equals方法:如果遍历完后没有返回,则返回true
        return true;
    }
}


  • 在这里插入图片描述
    解:主方法:从控制台获取整数列表长度,并赋值给int型变量length
    主方法:声明一个数组,长度为length
    主方法:使用循环从控制台获取数组元素
    主方法:调用方法isConsecutiveFour,传入获取的数组,根据返回值决定输出
    isConsecutiveFour方法:获取传入的数组长度,赋值给int型变量length
    isConsecutiveFour方法:使用for循环i作为下标从0开始length-4结束(含)
    判断values[i]==values[i+1]==values[i+2]==values[i+3],如果为真则返回true
    isConsecutiveFour方法:循环结束后返回false
import java.util.Scanner;

public class Test7_30 {
    public static void main(String[] args) {
        //1. 主方法:从控制台获取整数列表长度,并赋值给int型变量length
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of values: ");
        int length = input.nextInt();
        //2. 主方法:声明一个数组,长度为length
        int[] list = new int[length];
        //3. 主方法:使用循环从控制台获取数组元素
        System.out.print("Enter the values: ");
        for (int i = 0 ; i < length ; i++){
            list[i] = input.nextInt();
        }
        //4. 主方法:调用方法isConsecutiveFour,传入获取的数组,根据返回值决定输出
        if (isConsecutiveFour(list)){
            System.out.print("The list has consecutive fours");
        }else
            System.out.print("The list has no consecutive fours");
    }
    public static boolean isConsecutiveFour(int[] values){
        //5. isConsecutiveFour方法:获取传入的数组长度,赋值给int型变量length
        int length = values.length;
        //6. isConsecutiveFour方法:使用for循环i作为下标从0开始length-4结束(含)
        for (int i = 0 ; i <= length - 4 ;i++) {
            //7. 判断values[i]==values[i+1]==values[i+2]==values[i+3],如果为真则返回true
            if (values[i] == values[i + 1] && values[i + 1] == values[i + 2] &&
                    values[i + 2] == values[i + 3])
                return true;
        }
        //8. isConsecutiveFour方法:循环结束后返回false
        return false;
    }
}


在这里插入图片描述
解:输入的第一个数字表示列表中元素的个数,该数字不是列表的一部分。

package pack2;
 
import java.util.Arrays;
import java.util.Scanner;
 
public class MergeList {
 
	public static void main(String[] args) {
		try(Scanner input = new Scanner(System.in);) {
			System.out.print("Enter list1: ");
			int[] list1 = new int[input.nextInt()];
			for (int i = 0; i < list1.length; i++) 
				list1[i] = input.nextInt();
			
			System.out.print("Enter list2: ");
			int[] list2 = new int[input.nextInt()];
			for (int i = 0; i < list2.length; i++) 
				list2[i] = input.nextInt();
			
			System.out.print("The merged list is");
			for (int i : merge(list1, list2)) {
				System.out.print(" "+i);
			}
		}
	}
 
	/**合并两个有序列表(方法一)*/
	public static int[] merge(int[] list1, int[] list2) {
		int[] list3 = new int[list1.length + list2.length];
		
		System.arraycopy(list1, 0, list3, 0, list1.length);
		System.arraycopy(list2, 0, list3, list1.length, list2.length);
		Arrays.parallelSort(list3);
		
		return list3;
	}
 
	/**合并两个有序列表(方法二)*/
	public static int[] merge1(int[] list1, int[] list2) {
		int[] list3 = new int[list1.length + list2.length];
		int currentList1 = 0;
		int currentList2 = 0;
		int currentList3 = 0;
		
		while(true) {
			list3[currentList3++] = (list1[currentList1] < list2[currentList2]) ?         
                                     list1[currentList1++] : list2[currentList2++];
			if(currentList1 >= list1.length || currentList2 >= list2.length) break;
		}
		
		while(currentList3 < list3.length)
			list3[currentList3++] = (currentList1 < list1.length) ? list1[currentList1++] 
                                     : list2[currentList2++];
		
		return list3;
	}
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发热的嘤嘤怪(2003计科胜胜同学)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值