zoukankan      html  css  js  c++  java
  • java-7311练习(上)

    java练习,仅供参考!
    欢迎同学们交流讨论。

    JDK 1.8 API帮助文档
    JDK 1.6 API中文文档

    Java GUI

    -------------------------2016-10-23更新

    HappyFace

    package gui.test;
    import javax.swing.JApplet;
    import java.awt.Graphics;
    
    public class HappyFace extends JApplet
    {
        public void paint(Graphics canvas)
        {
            super.paint(canvas);
        	setSize(400,300);
            canvas.drawOval(100, 50, 200, 200);
            canvas.fillOval(155, 100, 10, 20);
            canvas.fillOval(230, 100, 10, 20);
            canvas.drawArc(150, 160, 100, 50, 180, 180);
        }
    }
    
    

    HappyFaceJFrame

    package gui.test;
    
    import java.awt.Graphics;
    
    import javax.swing.JFrame;
    
    public class HappyFaceJFrame extends JFrame
    {
    	public HappyFaceJFrame()
    	{
    		setSize(400,300);
    		setDefaultCloseOperation(EXIT_ON_CLOSE);
    	}
    	
        public void paint(Graphics canvas)
        {
            canvas.drawOval(100, 50, 200, 200);
            canvas.fillOval(155, 100, 10, 20);
            canvas.fillOval(230, 100, 10, 20);
            canvas.drawArc(150, 160, 100, 50, 180, 180);
        }
        
        public static void main(String[] args)
    	{
        	HappyFaceJFrame guiwindow = new HappyFaceJFrame();
    		guiwindow.setVisible(true);
    	}
        
    }
    
    

    MultipleFaces

    package gui.test;
    
    import javax.swing.JApplet;
    import java.awt.Graphics;
    import java.awt.Color;
    
    
    public class MultipleFaces extends JApplet
    {
    	public static final int FACE_DIAMETER = 50;
    	public static final int X_FACE0 = 10;
    	public static final int Y_FACE0 = 5;
    	
    	public static final int EYE_WIDTH = 5;
    	public static final int EYE_HEIGHT = 10;
    	public static final int X_RIGHT_EYE0 = 20;
    	public static final int Y_RIGHT_EYE0 = 15;
    	public static final int X_LEFT_EYE0 = 45;
    	public static final int Y_LEFT_EYE0 = Y_RIGHT_EYE0;
    	
    	public static final int NOSE_DIAMETER = 5;
    	public static final int X_NOSE0 = 32;
    	public static final int Y_NOSE0 = 25;
    	
    	public static final int MOUTH_WIDTH = 30;
    	public static final int MOUTH_HEIGHT0 = 0;
    	public static final int X_MOUTH0 = 20;
    	public static final int Y_MOUTH0 = 35;
    	public static final int MOUTH_START_ANGLE = 180;
    	public static final int MOUTH_EXTENT_ANGLE = 180;
    
    	
    	public void paint(Graphics canvas)
    	{
    		setSize(500, 300);
    		
    		int i, xOffset, yOffset; // Want i to exist after the loop ends
    		
    		for (i = 0; i <= 4; i++)
    		{ 
    			// Draw one face:
    			xOffset = 50 * i;
    			yOffset = 30 * i;
    			
    			// Draw face circle:
    			if (i % 2 == 0) // if i is even
    			{ 
    				// Make face light gray
    				//canvas.setColor(Color.LIGHT_GRAY);
    				canvas.setColor(Color.YELLOW);
    				canvas.fillOval(X_FACE0 + xOffset, Y_FACE0 + 30 * i, FACE_DIAMETER, FACE_DIAMETER);
    			}
    			canvas.setColor(Color.BLACK);
    			canvas.drawOval(X_FACE0 + xOffset, Y_FACE0 + yOffset, FACE_DIAMETER, FACE_DIAMETER);
    
    			// Draw eyes:
    			canvas.setColor(Color.BLUE);
    			canvas.fillOval(X_RIGHT_EYE0 + xOffset, Y_RIGHT_EYE0 + yOffset, EYE_WIDTH, EYE_HEIGHT);
    			canvas.fillOval(X_LEFT_EYE0 + xOffset, Y_LEFT_EYE0 + yOffset, EYE_WIDTH, EYE_HEIGHT);
    			// Draw nose:
    			canvas.setColor(Color.BLACK);
    			canvas.fillOval(X_NOSE0 + xOffset, Y_NOSE0 + yOffset, NOSE_DIAMETER, NOSE_DIAMETER);
    			// Draw mouth:
    			canvas.setColor(Color.RED);
    			canvas.drawArc(X_MOUTH0 + xOffset, Y_MOUTH0 + yOffset, MOUTH_WIDTH, MOUTH_HEIGHT0 + 3 * i,
    					MOUTH_START_ANGLE, MOUTH_EXTENT_ANGLE);
    		}
    		// i is 5 when the previous loop ends
    		xOffset = 50 * i;
    		yOffset = 30 * i;
    		
    		// Draw kissing face:
    		// Draw face outline:
    		canvas.setColor(Color.BLACK);
    		canvas.drawOval(X_FACE0 + xOffset, Y_FACE0 + yOffset, FACE_DIAMETER, FACE_DIAMETER);
    		// Draw eyes:
    		canvas.setColor(Color.BLUE);
    		canvas.fillOval(X_RIGHT_EYE0 + xOffset, Y_RIGHT_EYE0 + yOffset, EYE_WIDTH, EYE_HEIGHT);
    		canvas.fillOval(X_LEFT_EYE0 + xOffset, Y_LEFT_EYE0 + yOffset, EYE_WIDTH, EYE_HEIGHT);
    		// Draw nose:
    		canvas.setColor(Color.BLACK);
    		canvas.fillOval(X_NOSE0 + xOffset, Y_NOSE0 + yOffset, NOSE_DIAMETER, NOSE_DIAMETER);
    		// Draw mouth in shape of a kiss:
    		canvas.setColor(Color.RED);
    		canvas.fillOval(X_MOUTH0 + xOffset + 10, Y_MOUTH0 + yOffset, MOUTH_WIDTH - 20, MOUTH_WIDTH - 20);
    
    		// Add text:
    		canvas.drawString("Kiss, Kiss.", X_FACE0 + xOffset + FACE_DIAMETER, Y_FACE0 + yOffset);
    		
    		// Draw blushing face:
    		i++;
    		xOffset = 50 * i;
    		yOffset = 30 * i;
    		
    		// Draw face circle:
    		canvas.setColor(Color.LIGHT_GRAY);
    		canvas.fillOval(X_FACE0 + xOffset, Y_FACE0 + yOffset, FACE_DIAMETER, FACE_DIAMETER);
    		canvas.setColor(Color.BLACK);
    		canvas.drawOval(X_FACE0 + xOffset, Y_FACE0 + yOffset, FACE_DIAMETER, FACE_DIAMETER);
    		// Draw eyes:
    		canvas.setColor(Color.BLACK);
    		canvas.fillOval(X_RIGHT_EYE0 + xOffset, Y_RIGHT_EYE0 + yOffset, EYE_WIDTH, EYE_HEIGHT);
    		canvas.fillOval(X_LEFT_EYE0 + xOffset, Y_LEFT_EYE0 + yOffset, EYE_WIDTH, EYE_HEIGHT);
    		// Draw nose:
    		canvas.setColor(Color.BLACK);
    		canvas.fillOval(X_NOSE0 + xOffset, Y_NOSE0 + yOffset, NOSE_DIAMETER, NOSE_DIAMETER);
    		// Draw mouth:
    		canvas.setColor(Color.BLACK);
    		canvas.drawArc(X_MOUTH0 + xOffset, Y_MOUTH0 + yOffset, MOUTH_WIDTH, MOUTH_HEIGHT0 + 3 * (i - 2),
    				MOUTH_START_ANGLE, MOUTH_EXTENT_ANGLE);
    		
    		// Add text:
    		canvas.drawString("Tee Hee.", X_FACE0 + xOffset + FACE_DIAMETER, Y_FACE0 + yOffset);
    	}
    }
    

    week1

    1.1 编写第一个程序,输出“Hello world!”

    package week1;
    
    /*任务1
     *程序描述:编写第一个程序,输出“Hello world!”。 
     */
    public class Hello 
    {
    	public static void main(String[] args)
    	{
    		System.out.println("hello world!");
    	}
    
    }
    
    
    hello world!
    

    1.2 输出你的 短期/长期 目标

    package week1;
    
    /*任务2
     *程序描述:
     *编写程序,第一行输出你的姓名;之后空第一行;
     *第 三及五行 输出你的 短期/长期 目标。
     *输出如下:  
     *My name: *** 
     * 
     *My short-term objective:*****         
     *My long-term objective:***********  
     */
    public class MyLifeGoals 
    {
    
    	public static void main(String[] args) 
    	{
    		System.out.println("My name:***
    ");
    		System.out.println("My short-term objective:*****");
    		System.out.println("My long-term objective:***********");
    	}
    
    }
    
    My name:***
    
    My short-term objective:*****
    My long-term objective:***********
    

    1.3 多行输出 一个宽 12 个字符、高 10行 的字符“J”

    package week1;
    
    /*
     * 任务3
     * 程序描述:通过在多行输出 J 来组成一个
     * 宽 12 个字符、高 10行  的字符“J”。 
     */
    public class JLetter 
    {
    	public static void main(String[] args)
    	{
    		String str = "JAVA";
    		//输出 1-2 行
    		for (int i = 0; i < 2; i++)
    		{
    			for (int j = 0; j < 3; j++)
    			{
    				System.out.printf("%s", str);
    			}
    			System.out.println();
    		}
    		//输出 3-6 行
    		for (int i = 0; i < 4; i++)
    		{
    			//占位符长度包含字符本身的长度;即 10 = 4+6
    			System.out.printf("%10s
    ",str);
    		}
    		//输出 7-8  行
    		System.out.printf("%s%9s
    ","J",str);
    		System.out.printf("%s%8s
    ","JA",str);
    		//输出 9-10 行
    		System.out.printf("%5s%s
    ",str,str);
    		System.out.printf("%6s%s
    ",str,"JA");
    	}
    } 
    
    JAVAJAVAJAVA
    JAVAJAVAJAVA
          JAVA
          JAVA
          JAVA
          JAVA
    J     JAVA
    JA    JAVA
     JAVAJAVA
      JAVAJA
    

    1.4 用户信息:姓名、年龄、期望工资及婚否

    package week1;
    
    import java.util.Scanner;
    
    /*
     * 任务4
     * 程序描述: 
     * (1) 首先定义四个变量,用来存放用户的姓名、年龄、期望工资及婚否 
     * (2) 分别接收用户输入的姓名、年龄、工资及婚否 
     * (3) 将这些信息分四行输出。 
     * 输出: 
     * 请输入你的姓名:周星星
     * 请输入你的年龄:18
     * 请输入你期望的工资:25000.9
     * 你是否已婚(true代表已婚,false代表未婚):false
     * 你的信息如下:
     * 姓名:周星星
     * 年龄:18
     * 期望的工资:25000.9
     * 婚姻状态:false
     */
    public class UserInfo
    {
    
    	public static void main(String[] args)
    	{
    		String name;   //设置变量
    		int age;
    		float expected_salary;
    		boolean matital_status;
    		
    		//从键盘接收数据  
    		Scanner scan = new Scanner(System.in);
    		
    		System.out.print("请输入你的姓名:");
    		name = scan.nextLine();
    		System.out.print("请输入你的年龄:");
    		age = scan.nextInt();
    		System.out.print("请输入你期望的工资:");
    		expected_salary = scan.nextFloat();
    		System.out.print("你是否已婚(true代表已婚,false代表未婚):");
    		matital_status = scan.nextBoolean();
    		scan.close();   // 关闭 Scanner 对象
    
    		System.out.println("你的信息如下:");
    		System.out.println("姓名:" + name);
    		System.out.println("年龄:" + age);
    		System.out.println("期望的工资:" + expected_salary);
    		System.out.println("婚姻状态:" + matital_status);
    	}
    
    }
    
    请输入你的姓名:周星星
    请输入你的年龄:18
    请输入你期望的工资:25000.9
    你是否已婚(true代表已婚,false代表未婚):false
    你的信息如下:
    姓名:周星星
    年龄:18
    期望的工资:25000.9
    婚姻状态:false
    

    1.5 User 类: get()、set()

    package week1;
    
    /*
     * 任务5
     * 程序描述: 该实验的目标是生成 User 类。 
     * - 三个成员变量
     * 	姓名(name):字符串类型
     * 	年龄(age):整形
     * 	性别(gender):整形
     * - 六个成员方法
     * getName(): String 
     * setName(): void 
     * getAge(): int 
     * setAge(): void 
     * getGender():int 
     * setGender():void 
     */
    public class User
    {
    	private String name;
    	private int age;
    	private int gender;
    
    	public String getName()
    	{
    		return name;
    	}
    
    	public void setName(String name)
    	{
    		this.name = name;
    	}
    
    	public int getAge()
    	{
    		return age;
    	}
    
    	public void setAge(int age)
    	{
    		this.age = age;
    	}
    
    	public int getGender()
    	{
    		return gender;
    	}
    
    	public void setGender(int gender)
    	{
    		this.gender = gender;
    	}
    
    }
    
    

    week2

    -------------------------2016-10-14更新

    2.1 我的Java成绩

    package week2;
    
    import java.util.Scanner;
    
    /*
     * 任务 1 
     *程序描述:
     *接收用户从键盘上输入的 3 项 Java 成绩:课堂活跃度(activity)、作业(homework)、 考试(exam);
     *之后从键盘上接收用户输入的这三项在最终成绩中的比例,分别为 activityPercent 占 30%、
     *homeworkPercent 占 30%和 examPercent 占 40%。最终按比例计算最 终成绩并输出。  
     */
    public class Score
    {
    
    	public static void main(String[] args)
    	{
    		int score_activity;
    		int score_homework;
    		int score_exam;
    		float score_total;
    
    		Scanner scan = new Scanner(System.in);
    		System.out.println("以下是3项Java成绩,请按提示输入");
    		System.out.print("请输入 课堂活跃度 成绩:");
    		score_activity = scan.nextInt();
    		System.out.print("请输入 作业 成绩:");
    		score_homework = scan.nextInt();
    		System.out.print("请输入 考试 成绩:");
    		score_exam = scan.nextInt();
    		scan.close();
    		
    		score_total = (float) 
    				( score_activity * 0.3
    				+ score_homework * 0.3
    				+ score_exam * 0.4
    				);
    		System.out.println("你的总成绩为:" + score_total);
    	}
    
    }
    
    以下是3项Java成绩,请按提示输入
    请输入 课堂活跃度 成绩:86
    请输入 作业 成绩:91
    请输入 考试 成绩:77
    你的总成绩为:83.9
    

    2.2 颠倒输出一个三位整数

    package week2;
    
    import java.util.Scanner;
    
    /*
     * 任务 2 
     * 程序描述:
     * 接收用户输入的一个三位整数(假设用户一定会输入一个三位整数),将其如 123 的数位颠倒,输出 321。 
     */
    public class ReverseNumber
    {
    
    	public static void main(String[] args)
    	{
    		//定义一个三位整数(number)的个位(unit)、十位(ten)、百位(hundred)
    		int number, unit, ten, hundred;
    		Scanner scan = new Scanner(System.in);
    		System.out.print("请输入一个三位整数:");
    		number = scan.nextInt();
    		scan.close();
    		unit = number%10;  //取个位
    		ten = number%100/10;  //取十位
    		hundred = number/100;  //取百位
    
    		System.out.println("这个数逆向输出为:" + unit + ten + hundred);
    	}
    
    }
    
    请输入一个三位整数:198
    这个数逆向输出为:891
    
    

    2.3 一元二次方程--根的判别式

    程序描述:接收用户从键盘输入的 a、b、c 值,然后利用公式计算两个根的值。
    输出如下
    Let $ ax^2 + bx + c = 0 (a eq 0), ( ) Large x_1=frac{-b + sqrt{b^2-4ac}}{2a}, ( ) Large x_2=frac{-b - sqrt{b^2-4ac}}{2a}, $
    when $ Delta=b^2-4ac $ only one repeated root
    when $ Delta>0 $ two real roots
    when $ Delta<0 $ two real roots

    package week2;
    
    import java.util.Scanner;
    
    /*
     * 任务3
     * 程序描述:
     * 接收用户从键盘输入的 a、b、c 值,然后利用公式计算两个根的值。 
     */
    public class Quadratic
    {
    	/*
    	 * 关于类Math(java.lang.Math)的2个函数:
    	 * 1.sqrt(double a) 返回正确舍入的 double 值的正平方根
    	 * 2.pow(double a, double b) 返回第一个参数的第二个参数次幂的值
    	 * 更多可访问:http://docs.oracle.com/javase/8/docs/api/
    	 */
    	public static void main(String[] args)
    	{
    		double a,b,c;  //一元二次方程各项系数
    		Scanner scan = new Scanner(System.in);
            System.out.print("Insert value for a: ");
            a = scan.nextDouble();
            System.out.print("Insert value for b: ");
            b = scan.nextDouble();
            System.out.print("Insert value for c: ");
            c = scan.nextDouble();
            scan.close();
    
            System.out.println("Let " + a + "x^2 + " +b+ "x + " + c + " = 0");
            double delta; //根与系数的判别式  delta = b^2 - 4ac
            delta = Math.pow(b, 2) - (4 * a * c);
            if (delta > 0 || delta == 0)
    		{
    			double answer1 = (-b + Math.sqrt(delta)) / (2 * a);
    			double answer2 = (-b - Math.sqrt(delta)) / (2 * a);
    			System.out.println("The values are: "  + answer1 + ", " + answer2);
    		}else 
    		{
    			System.out.println("Answer contains imaginary numbers");
    		}
    
    	}
    }
    
    Insert value for a: 1
    Insert value for b: 2
    Insert value for c: 1
    Let 1.0x^2 + 2.0x + 1.0 = 0
    The values are: -1.0, -1.0
    
    
    Insert value for a: 1
    Insert value for b: 1
    Insert value for c: -6
    Let 1.0x^2 + 1.0x + -6.0 = 0
    The values are: 2.0, -3.0
    
    
    Insert value for a: 3
    Insert value for b: 2
    Insert value for c: 1
    Let 3.0x^2 + 2.0x + 1.0 = 0
    Answer contains imaginary numbers
    
    

    2.4 猜随机整数

    package week2;
    
    import java.util.Scanner;
    
    /*
     * 任务 4
     * 程序描述:
     * 编写程序,实现产生一个从 1-N(N 由用户从键盘输入)的随机数。
     * 用户猜测一 个数,判断该猜测是否正确,如果正确,则输出“你太有才啦!”,否则输出“抱歉啦”及该随机数。
     */
    public class RandomNumber
    {
    	/*
    	 * 随机数可以用java.util.Random。
    	 * 本程序使用的java.lang.Math;
    	 * Math.random() 返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。
    	 * 更多可访问:http://docs.oracle.com/javase/8/docs/api/
    	 */
    	public static void main(String[] args)
    	{
    		int random_number,num;
    		Scanner scan = new Scanner(System.in);
    		System.out.print("请输入范围为 1-N 的整数 的最大值(N):");
    		num = scan.nextInt();
    		
    		//随机一个 1-N 的整数
    		random_number = (int) (Math.random()*num + 1);
    		//System.out.println(random_number);
    		
    		System.out.print("请(猜测)输入这个随机整数:");
    		num = scan.nextInt();
    		scan.close();
    		if (num == random_number)
    		{
    			System.out.println("你太有才啦!");
    		} else
    		{
    			System.out.println("抱歉啦,该随机数为:" + random_number);
    		}
    	}
    
    }
    
    请输入范围为 1-N 的整数 的最大值(N):1
    请(猜测)输入这个随机整数:1
    你太有才啦!
    
    
    请输入范围为 1-N 的整数 的最大值(N):20
    请(猜测)输入这个随机整数:11
    抱歉啦,该随机数为:5
    
    

    2.5 UserApp

    package week2;
    
    import week1.User;
    import java.util.Scanner;
    
    /*
     * 任务5
     * 程序描述:使用week1中生成的 User.java 类。
     * (一)获得用户输入的姓名、年龄及性别 
     * (1)声明三个变量:姓名(name:字符串类型)、年龄(age:整型)及性别(gender: 整型) 
     * (2) 接收用户输入的 name、age、gender 的值 
     * (3) 分三行输出这三个变量  
     * (二)转换年龄 
     * (1) 计算并将用户已经存在于世的分钟数(分钟=年龄×525600) 
     * (2) 计算用户年龄对应的世纪值(年龄/100) 
     * (三) 输出最大心率值
     *  增加 if-else 语句来计算输出男、女对应的不同的最大心率:
     *  男性的最大心率为 214-(0.8* 年龄);女性的最大心率为 209-(0.7*年龄)。
     */
    public class UserApp
    {
    
    	public static void main(String[] args)
    	{
    		//5.1.1 声明三个变量
    		String name;
    		int age;
    		int gender;
    		
    		User user = new User();  //实例化一个对象
    		
    		Scanner scan = new Scanner(System.in);
    		
    		//5.1.2 输入;初始化变量
    		System.out.print("Enter your name:");
    		name = scan.nextLine();
    		System.out.print("Enter your age in years:");
    		age = scan.nextInt();
    		System.out.print("Enter your gender(1 for female,0 for male):");
    		gender = scan.nextInt();
    		scan.close();
    		
    		user.setName(name);
    		user.setAge(age);
    		user.setGender(gender);
    		
    		//5.1.3 输出结果
    		System.out.println("Your name:" + user.getName());
    		System.out.println("Your age in years:" + user.getAge());
    		System.out.println("Your gender:" + gender);
    		
    		//5.2 转换年龄 
    		long minutes = age * 525600;
    		float centuries = (float) (age / 100.0); 
    		//5.2.1 输出用户已经存在于世的分钟数(分钟=年龄×525600) 
    		System.out.println("	Your age in minutes is " + minutes + " minutes.");
    		//5.2.2 输出用户年龄对应的世纪值(年龄/100) 
    		System.out.println("	Your age in centuries is " + centuries + " centuries.");
    
    		//5.3  输出最大心率值 ;男性的最大心率为 214-(0.8* 年龄);女性的最大心率为 209-(0.7*年龄)。
    		// 条件运算符(三元运算符) 判断 计算心率
    		double heart_rate = 0==user.getGender() ? 214-(0.8*age):209-(0.7*age);
    		System.out.println("Your max heart rate is " + heart_rate + " beats per minutes.");
    	}
    
    }
    
    Enter your name:Lucie
    Enter your age in years:25
    Enter your gender(1 for female,0 for male):1
    Your name:Lucie
    Your age in years:25
    Your gender:1
    	Your age in minutes is 13140000 minutes.
    	Your age in centuries is 0.25 centuries.
    Your max heart rate is 191.5 beats per minutes.
    
    
    Enter your name:Kao
    Enter your age in years:19
    Enter your gender(1 for female,0 for male):0
    Your name:Kao
    Your age in years:19
    Your gender:0
    	Your age in minutes is 9986400 minutes.
    	Your age in centuries is 0.19 centuries.
    Your max heart rate is 198.8 beats per minutes.
    
    

    week3

    -------------------------2016-10-25更新

    3.1 计算 1~15 所有不能被 2或者3 整除的和

    package week3;
    
    /*
     * 任务 1
     * 程序描述 :计算从1-15中所有不能被 2或者3 整除的数值 和
     */
    public class Sum 
    {
    	public static void main(String []args)
    	{
    		int digit;
    		int sum=0;
    		
    		for (digit = 1; digit <= 15; ++digit)
    		{
    			//既不能被3整除,也不能被2整除
    			if(digit%3!=0 && digit%2!=0)
    			{
    				sum+=digit;
    				//System.out.println(digit);
    			}
    		}
    		System.out.println("sum = " + sum);
    	}
    }
    
    
    sum = 37
    

    3.2 “你要继续玩吗(输入yes 或 not ): ”

    package week3;
    
    import java.util.Scanner;
    
    /*
     * 任务 2
     * 程序描述 :首先 输出提示信息“你要继续玩吗(输入yes 或  not ): ”
     * 接收用户输入的一行内容, 判断其首字符是否为 yes 或 not;
     * 如果用户输入的是  yes 或  not ,则退出循环输用户的选择,
     * 如果用户输入的不是 yes 或  not ,则输出提示并等待用户的输入。
     */
    public class YesOrNo 
    {
    	public static void main(String[] args)
    	{
    		Scanner scan = new Scanner(System.in);
    		String answer;
    		
    		while (true)
    		{
    			System.out.print("Continue? (enter yes or not): ");
    			answer = scan.nextLine();
    			if (answer.equals("yes"))
    			{
    				System.out.println("
    The selection was y for Yes.");
    				break;
    			}
    			if (answer.equals("not"))
    			{
    				System.out.println("
    The selection was n for No.");
    				break;
    			}
    		}
    		scan.close();
    	}
    	
    }
    
    
    Continue? (enter yes or not): hello
    Continue? (enter yes or not): how are you?
    Continue? (enter yes or not): hi
    Continue? (enter yes or not): hehe
    Continue? (enter yes or not): not
    
    The selection was n for No.
    
    Continue? (enter yes or not): what should I input?
    Continue? (enter yes or not): yes
    
    The selection was y for Yes.
    

    3.3 猜数字

    package week3;
    
    import java.util.Random;
    import java.util.Scanner;
    
    /*
     * 任务 3:猜数
     * 程序描述 :程序随机产生一个从 1-10 的整型随机数。用户多次输入猜测值:
     * 如果小于 5次 即猜中 ,输出“你聪明绝顶啦!”(或其他个性提示)加上猜中所用次数;
     * 如果猜测次数 >=5 且没有猜中,输出“呵你 outout 啦”(或其他个性提示)并附上随机数 ,退出循环;
     * 如果用户输入的整数小于1或大于10,则提示“ 无效输入,请重新输入:”,等待用户 输入有效的数值。
     */
    public class Guess
    {
    	public static void main(String[] args)
    	{
    		Random rnd = new Random();        //创建一个新的随机数生成器
    		
    		/*rnd.nextInt(10):生成[0,10)区间的整数*/
    		int randomNumber = rnd.nextInt(10)+1;  //1-10
    		int guessCount = 0;    //猜数的次数
    		int guessDigit;        //猜数的数字
    		
    		Scanner scan = new Scanner(System.in);
    		
    		do
    		{
    			System.out.print("请输入1-10内的整数: ");
    			guessDigit = scan.nextInt();
    			
    			//输入的整数小于1或大于10,等待用户 输入有效的数值。
    			while (guessDigit < 1 || guessDigit > 10)
    			{
    				System.out.println(guessDigit + " 为无效输入!");
    				System.out.print("请输入1-10内的整数: ");
    				guessDigit = scan.nextInt();
    			}
    			
    			++guessCount;   //此时已经有效输入
    			
    			if (guessDigit == randomNumber)
    			{
    				System.out.println("恭喜你,猜对啦!你猜了"
    						+ guessCount
    						+ "次。");
    				break;
    			}
    		} while (guessCount < 5);
    		scan.close();
    		
    		if (guessCount == 5)
    		{
    			System.out.println("抱歉,猜错啦!你猜了5次。"
    						+ "随机数为:"
    						+ randomNumber);
    		}
    	}
    }
    
    
    请输入1-10内的整数: 0
    0 为无效输入!
    请输入1-10内的整数: 11
    11 为无效输入!
    请输入1-10内的整数: 5
    恭喜你,猜对啦!你猜了1次。
    
    请输入1-10内的整数: 6
    请输入1-10内的整数: 5
    请输入1-10内的整数: 4
    请输入1-10内的整数: 3
    请输入1-10内的整数: 1
    抱歉,猜错啦!你猜了5次。随机数为:8
    
    

    3.4 整数的小运算

    3.4.1 NumberOperations
    package week3;
    
    /*
     * 任务 4
     * 整数的运算
     */
    public class NumberOperations
    {
    	private int number;
    	
    	//构造方法 :对成员变量 number 赋值
    	public NumberOperations(int numberIn) 
    	{
    		number = numberIn;
    	}
    
    	public int getNumber()
    	{
    		return number;
    	}
    	
    	//返回所有 (0,number) 的奇数(以tab间隔)
    	public String oddsUnder()
    	{
    		String oddNumbers = "	";
    		for (int i = 1; i < number; i++)
    		{
    			if (i%2 != 0)
    			{
    				oddNumbers += (i + "	");
    			}
    		}
    		return oddNumbers;
    	}
    
    	//返回 从 (1,number) 的    2的幂(平方)
    	public String powersTwoUnder()
    	{
    		int powerNumber = 0; //2的幂(平方)
    		String powerNumbers = "	";
    		
    		for (int i = 0; i < number; i++)
    		{
    			powerNumber = (int)Math.pow(2, i);
    			if (powerNumber >= number) break;
    			
    			powerNumbers += ( powerNumber + "	");
    		}
    		return powerNumbers;
    	}
    
    	//与初始值比较大小,number 大,小,等-> 1,-1,0
    	public int isGrater(int compareNumber)
    	{
    		if(number > compareNumber) return 1;
    		else if(number < compareNumber) return -1;
    		else return 0;
    	}
    }
    
    
    3.4.2 NumberOpsDriver
    package week3;
    
    import java.util.Scanner;
    
    /*
     * 任务 4
     * 测试整数的运算
     */
    public class NumberOpsDriver 
    {
    
    	public static void main(String[] args)
    	{
    		int number;   //用户输入的整数
    		Scanner scan = new Scanner(System.in); //准备接收键盘输入
    		
    		//(1)输入三个的正整数(以空格间隔,并以0结束)
    		System.out.println("Enter a list of positive integers separated with a space followed by 0:");
    		while (true)
    		{
    			number = scan.nextInt();  //从键盘读取一个int值
    			if(number == 0) break;
    			
    			//(2)创建 NumberOperations对象,并分别调用函数
    			NumberOperations numOps = new NumberOperations(number);
    			System.out.println("For:  " + number);
    			System.out.println("  Odds under:" + numOps.oddsUnder());
    			System.out.println("  Powers of 2 under:" + numOps.powersTwoUnder());
    			
    			//有选择的输出  2个数值的大小比较
    			if (numOps.isGrater(12) == 1)
    				System.out.println("  Compare " + number + " > 12  :	1");
    			else if (numOps.isGrater(12) == -1)
    				System.out.println("  Compare " + number + " < 12   :	-1");
    			else
    				System.out.println("  Compare " + number + " = 12  :	0");
    		}
    		scan.close();
    	}
    }
    
    
    Enter a list of positive integers separated with a space followed by 0:
    12 9 17 0
    For:  12
      Odds under:	1	3	5	7	9	11	
      Powers of 2 under:	1	2	4	8	
      Compare 12 = 12  :	0
    For:  9
      Odds under:	1	3	5	7	
      Powers of 2 under:	1	2	4	8	
      Compare 9 < 12   :	-1
    For:  17
      Odds under:	1	3	5	7	9	11	13	15	
      Powers of 2 under:	1	2	4	8	16	
      Compare 17 > 12  :	1
    

    week4

    -------------------------2016-10-31更新

    4.1 求三个整数的最小值(多种方法)

    package week4;
    
    import java.util.Scanner;
    
    /*
     * 任务 4.1
     * 程序描述 :求3个整数最小值
     */
    public class Minor
    {
    	//0. 三个整数一定存在一个数 小于等于 另外两个数
        public int minFun0(int a, int b, int c)
        {
            int minNum;  //最小数的临时变量
            
            if (a <= b && a <= c )minNum = a;
            else if (b <= a && b <= c)minNum = b;
            else minNum = c;
            
            return minNum;
        }
        //1. if-else
        public int minFun1(int a, int b, int c)
        {
            int minNum;  //最小数的临时变量
            if (a < b)
            {
                if (a < c) minNum = a;
                else minNum = c;
            }
            else
            {
                if (b < c) minNum = b;
                else minNum = c;
            }
            return minNum;
        }
        
        //2. if-else
        public int minFun2(int a, int b, int c)
        {
            int minNum;  //最小数的临时变量
            if (a < b) minNum = a;
            else minNum = b;
    
            if (c < minNum) minNum = c;
            
            return minNum;
        }
    
        //3. 条件运算符 + 临时变量
        public int minFun3(int a, int b, int c)
        {
            int minNum;  //最小数的临时变量
            minNum = a<b ? a:b;
            minNum = minNum<c ? minNum:c;
            return minNum;
        }
        
        //4. 条件运算符 (同理,不同顺序即可)
        public int minFun4(int a, int b, int c)
        {
            return (a<b ? a:b)<c ? (a<b ? a:b):c;
        }
        
        //5. 条件运算符 (同理,不同顺序即可)
        public int minFun5(int a, int b, int c)
        {
            return a<b ? (a<c?a: c) : (b<c?b: c);
        }
        
        //6. 3个整数由小至大排序
        public int minFun6(int a, int b, int c)
        {
        	//如果为真,则(异或运算)交换位置
            if(a > b){ a ^= b;  b ^= a;  a ^= b; }
            if(a > c){ a ^= c;  c ^= a;  a ^= c; }
            if(b > c){ b ^= c;  c ^= b;  b ^= c; }
            return a;
        }
    
        //7. 两点坐标参数比较  + 条件运算符
        public int minFun7(int a, int b, int c)
        {
        	return ((a+b) - Math.abs(a-b))/2 < c 
        			? (a+b - Math.abs(a-b))/2 :c;
        }
        
        //8. 三点坐标参数比较
        public int minFun8(int a, int b, int c)
        {
        	return ((a+b - Math.abs(a-b))/2 + c 
        			- Math.abs(c-(a+b - Math.abs(a-b))/2))/2;
        }
    
        public static void main(String[] args)
        {
            int resNumber[] = new int[9];  //存放结果
            int num1, num2, num3;
            
            Scanner scan = new Scanner(System.in);
    
            System.out.println("Please input three integers:");
            num1 = scan.nextInt();
            num2 = scan.nextInt();
            num3 = scan.nextInt();
            scan.close();
            
            Minor minFuns = new Minor();
            resNumber[0] = minFuns.minFun0(num1, num2, num3);
            resNumber[1] = minFuns.minFun1(num1, num2, num3);
            resNumber[2] = minFuns.minFun2(num1, num2, num3);
            resNumber[3] = minFuns.minFun3(num1, num2, num3);
            resNumber[4] = minFuns.minFun4(num1, num2, num3);
            resNumber[5] = minFuns.minFun5(num1, num2, num3);
            resNumber[6] = minFuns.minFun6(num1, num2, num3);
            resNumber[7] = minFuns.minFun7(num1, num2, num3);
            resNumber[8] = minFuns.minFun8(num1, num2, num3);
    
            // 循环遍历输出结果
            for (int i = 0; i < resNumber.length; i++)
    		{
    			System.out.println("minFun" + (i+1) + ": " + resNumber[i]);
    		}
        }
    }
    
    
    Please input three integers:
    8 1 7
    minFun1: 1
    minFun2: 1
    minFun3: 1
    minFun4: 1
    minFun5: 1
    minFun6: 1
    minFun7: 1
    minFun8: 1
    minFun9: 1
    

    4.2 回文(字符串)测试

    package week4;
    
    import java.util.Scanner;
    
    /*
     * 任务 4.2
     * 程序描述 :进行回文测试,如字符串“abdba”为回文palindrome
     * (1)提示用户输入一个字符串
     * (2)如果字符串为回文,则输出“这是回文”,否则输出“不是回文哦”
     * (3)输出提示“要测试另一个字符串吗? 如果用户输入了y或Y,则执行(2),否则退出程序
     */
    public class PalindromeTester
    {
    
    	public static void main(String[] args)
    	{
    		String string = null;
    		char index;   //输入的第一个字符
            Scanner scan = new Scanner(System.in);
    
            System.out.print("请输入一个字符串:");
            string = scan.nextLine();
            
            do
    		{
    			if (palindrome(string))
    				System.out.println(string + " 是回文!");
    			else
    				System.out.println(string + " 不是回文哦。");
    			
    			System.out.println("
    要测试另一个字符串吗?");
    			System.out.print("继续测试输入 y/Y,否则输入其他:");
    			index = scan.nextLine().charAt(0);
    			
    			switch (index)
    			{
    			case 'y':
    			case 'Y':
    				System.out.print("请输入一个字符串:");
    				string = scan.nextLine();
    				break;
    			case 'n':
    			case 'N':
    			default:
    				System.out.print("程序结束!");
    				break;
    			}
    		} while (index == 'y'|| index=='Y');
            scan.close();
    	}
    
    	private static boolean palindrome(String string)
    	{
    		boolean flag = true;  //默认返回真
    		int len = string.length(); //字符串的长度
    
    		for (int i = 0; i < len/2; i++)
    		{
    			if (string.charAt(i) != string.charAt(len-1-i))
    			{
    				flag = false;
    				break;
    			}
    		}
    		return flag;
    	}
    }
    
    请输入一个字符串:test
    test 不是回文哦。
    
    要测试另一个字符串吗?
    继续测试输入 y/Y,否则输入其他:y
    请输入一个字符串:aba
    aba 是回文!
    
    要测试另一个字符串吗?
    继续测试输入 y/Y,否则输入其他:n
    程序结束!
    

    4.3 判断小数点的两边有多少位

    package week4;
    
    import java.math.BigDecimal;
    import java.util.Scanner;
    
    /*
     ** 任务 4.3
     ** 程序描述 :
     * (1)接收用户输入的一个double类型的数值
     * (2)判断该数值小数点左侧及右侧各有多少位
     * 
     ** 解题思路与方法局限:
     * 本程序 用户的输入是以Double类型为接收的,故也是基于double类型处理的;
     * a)digitalBitsFun1
     * 原理:Double.toString(doubleInput)将小数转化为字符串进行处理,查找'.'的位置进行判断。
     * 局限:问题就是小数转字符串时候会出现科学计数法,这样结果就错误,如“1.32456783E7 小数点左边有1位,右边有10位。”。
     * 改进:使用nextLine()接收用户输入,直接传字符串参数。
     * b)digitalBitsFun2
     * 原理:将一个浮点数进行数值运算,分离开整数部分和小数部分;整数部分通过"乘10取余"计算位数,小数部分通过"乘10舍整"计算位数。
     * 局限:计算机对于浮点数的存储(二进制)位数是有限制的,当精度过高时候会产生溢出导致结果不准确(错误)。
     * 改进:精度问题,统一使用高精度的存储方式。
     * 
     ** 给出一个测试结果,可以对比发现方法的局限性:
     * 请输入一个小数:123465789.123456789123
     * digitalBitsFun1:
     * 1.2346578912345679E8 小数点左边有1位,右边有18位。
     * digitalBitsFun2:
     * 1.2346578912345679E8 小数点左边有9位,右边有8位。
     * 
     ** 程序说明:
     * 本程序对于整数部分或小数部分长度为7以内的输入结果是正确的。至于局限性了解即可。
     * digitalBitsFun2中很可能出现精度问题导致结果的异常,而精度也决定了误差;
     * 经过很多次的调试发现还是要统一BigDecimal类型,比如BigDecimal构造函数参数为字符串(double+"");
     * 在进行BigDecimal运算过程中 如果出现低精度的浮点数,就会影响结果,如new BigDecimal(doubleInput*10+"");
     * 
     */
    public class DigitalTest
    {
    
    	public static void main(String[] args)
    	{
    		double doubleInput;
    		Scanner scan = new Scanner(System.in);
    		
    		System.out.print("请输入一个小数: ");
            doubleInput = scan.nextDouble();
            scan.close();
            
            System.out.println("digitalBitsFun1:");
            digitalBitsFun1(doubleInput);
            System.out.println("digitalBitsFun2:");
            digitalBitsFun2(doubleInput);
            
    	}
    
    	private static void digitalBitsFun1(double doubleInput)
    	{
    		String doubleStr = Double.toString(doubleInput);
    		int pointIndex = doubleStr.indexOf('.');
    		System.out.println(doubleStr + " 小数点左边有"
    				+ pointIndex + "位,右边有"
    				+ (doubleStr.length() - pointIndex - 1 ) 
    				+ "位。");
    	}
    	
    	private static void digitalBitsFun2(double doubleInput)
    	{
    		double integer = Math.floor(doubleInput);  //取整数部分
    		BigDecimal decimals ;  //小数部分
    		int integerCount = 0;  //整数长度
    		int decimalCount = 0;  //小数长度
    		
    		//取小数部分
    		BigDecimal doubleIn = new BigDecimal(doubleInput+"");
    		BigDecimal integerIn = new BigDecimal(integer + "");
    		decimals = doubleIn.subtract(integerIn);
    		//System.out.println("小数部分:" + decimals);
    		
    		//计算整数长度
    		int i = 1; //临时步长
    		if (integer == 0) integerCount++;
    		else
    		{
    			while (integer != integer% i)
    			{
    				integerCount++;
    				i *= 10;
    			}
    		}
    		//计算小数长度
    		BigDecimal j = new BigDecimal(10); //临时步长
    		while (decimals.doubleValue() > 0)
    		{
    			decimalCount++;
    			BigDecimal multiply10 = decimals.multiply(j);
    			BigDecimal integerDeci = new BigDecimal(Math.floor(multiply10.doubleValue()));
    			decimals = multiply10.subtract(integerDeci);
    			//测试/调试输出
    			/*System.out.println("1---" + multiply10);
    			System.out.println("2---" + integerDeci);
    			System.out.println("1-2 = " + decimals);*/
    		}
    		
    		System.out.println(doubleInput 
    				+ " 小数点左边有" + integerCount 
    				+ "位,右边有" + decimalCount + "位。");
    	}
    }
    
    请输入一个小数: 1234567.1234567
    digitalBitsFun1:
    1234567.1234567 小数点左边有7位,右边有7位。
    digitalBitsFun2:
    1234567.1234567 小数点左边有7位,右边有7位。
    

    4.4 Dog项目

    package week4;
    
    /*
     * 任务 4.4.1
     * GoodDog类
     */
    public class GoodDog
    {
    	private int size;
    	
    	GoodDog(int sizeIn)
    	{
    		size = sizeIn;
    	}
    
    	void bark()
    	{
    		if (size <= 14) System.out.println("Yip!Yip!");
    		else if(size > 14 & size < 60) System.out.println("Ruff!Ruff!");
    		else System.out.println("Wooof!Wooof!");
    	}
    	public int getSize()
    	{
    		return size;
    	}
    
    	public void setSize(int size)
    	{
    		this.size = size;
    	}
    }
    
    package week4;
    
    /*
     * 任务 4.4.2
     * 测试狗叫
     */
    public class GoodDogTestDrive
    {
    	public static void main(String[] args)
    	{
    		GoodDog dog1 = new GoodDog(0);
    		GoodDog dog2 = new GoodDog(0);
    		GoodDog dog3 = new GoodDog(0);
    		
    		dog1.setSize(10);
    		dog1.bark();
    		dog2.setSize(50);
    		dog2.bark();
    		dog3.setSize(70);
    		dog3.bark();
    	}
    }
    
    Yip!Yip!
    Ruff!Ruff!
    Wooof!Wooof!
    

    4.5 模拟掷骰子

    package week4;
    
    /*
     * 任务 4.5.1
     * Die类,模拟掷骰子。
     * 
     */
    public class Die
    {
    	private int faceValue;
    	
    	public Die()
    	{
    		faceValue = 1;
    	}
    	
    	public int roll()
    	{
    		return faceValue = (int)(Math.random()*6 + 1);
    	}
    	
    	public String toString()
    	{
    		return Integer.toString(faceValue);
    	}
    	
    	public int getFaceValue()
    	{
    		return faceValue;
    	}
    
    	public void setFaceValue(int faceValue)
    	{
    		this.faceValue = faceValue;
    	}
    
    }
    
    package week4;
    
    /*
     * 任务 4.5.2
     * RollingDice类,模拟掷骰子。
     * 
     */
    public class RollingDice
    {
    	public static void main(String[] args)
    	{
    		int sum;  //
    		Die die1;  //Die类引用变量die1
    		Die die2;  //Die类引用变量die2
    		
    		//创建两个Die类的对象并赋值给die1,die2
    		die1 = new Die();
    		die2 = new Die();
    		
    		//调用两个对象的roll方法来模拟掷骰子
    		die1.roll();
    		die2.roll();
    		//输出两个骰子的点数
    		System.out.println("die1:" + die1.toString());
    		System.out.println("die2:" + die2.toString());
    		System.out.println();
    		
    		int i = die1.roll();  //调用die1的roll()并将返回值赋给int类型的变量i
    		die2.setFaceValue(4);  //以4为实参调用die2的setFaceValue()
    		//输出两个骰子的点数
    		System.out.println("die1:" + i);
    		System.out.println("die2:" + die2.toString());
    		
    		//调用die1、die2的getFaceValue()获得两个骰子的点数并求和,输出和
    		sum = die1.getFaceValue() + die2.getFaceValue();
    		System.out.println("sum= " + sum);
    		System.out.println();
    		
    		//调用die1、die2的roll()并将和赋值给sum
    		sum = die1.roll() + die2.roll();
    		//输出两个骰子的点数以及点数和
    		System.out.println("die1:" + die1.toString());
    		System.out.println("die2:" + die2.toString());
    		System.out.println("sum= " + sum);
    	}
    }
    
    die1:3
    die2:1
    
    die1:1
    die2:4
    sum= 5
    
    die1:6
    die2:4
    sum= 10
    

    week5

    -------------------------2016-11-07更新

    5.1 UserInfo 、UserInfoDrive

    5.1.1 UserInfo
    package week5;
    
    public class UserInfo
    {
    	private String firstName;
    	private String lastName;
    	private String location;
    	private int age;
    	private int status;
    	private static final int OFFLINE = 0;  //用户离线
    	private static final int ONLINE = 1;   //用户在线
    	
    	public UserInfo(String firstNameIn, String lastNameIn)
    	{
    		firstName = firstNameIn;
    		lastName = lastNameIn;
    		setLocation("Not specified");
    		setAge(0);
    		status = OFFLINE;
    	}
    	
    	public String toString()
    	{
    		String output = "";
    		String statusStr = null; //状态字符串
    		if (status == 0) statusStr = "Offline";
    		if (status == 1) statusStr = "Online";
    
    		output = "Name: " + lastName
    				+ " " + firstName
    				+ "
    Location: " + location
    				+ "
    Age: " + age
    				+ "
    Status: " + statusStr ;
    		return output;
    	}
    	
    	public String getLocation()
    	{
    		return location;
    	}
    
    	public void setLocation(String locationIn)
    	{
    		this.location = locationIn;
    	}
    
    	public int getAge()
    	{
    		return age;
    	}
    
    	public boolean setAge(int ageIn)
    	{
    		age = ageIn;
    		
    		boolean flag;
    		if (age > 0) flag = true;
    		else flag = false;
    		
    		return flag;
    	}
    	
    	public void logOff()
    	{
    		status = OFFLINE;
    	}
    	
    	public void logOn()
    	{
    		status = ONLINE;
    	}
    	
    	public static void main(String[] args)
    	{
    		UserInfo userInfo = new UserInfo("Jane", "Lane");
    		System.out.println(userInfo.toString());
    		System.out.println("-----------------------");
    		
    		userInfo.setAge(23);
    		userInfo.setLocation("Auburn");
    		userInfo.logOn();
    		System.out.println(userInfo.toString());
    	}
    }
    
    Name: Lane Jane
    Location: Not specified
    Age: 0
    Status: Offline
    -----------------------
    Name: Lane Jane
    Location: Auburn
    Age: 23
    Status: Online
    
    
    5.1.2 UserInfoDrive
    package week5;
    
    public class UserInfoDrive
    {
    	public static void main(String[] args)
    	{
    		UserInfo user1 = new UserInfo("Linda", "Jiang");
    		System.out.println(user1.toString());
    		System.out.println("-----------------------");
    		user1.setLocation("Virginia");
    		user1.setAge(20);
    		user1.logOn();
    		System.out.println(user1.toString());
    		System.out.println("-----------------------");
    		
    		UserInfo user2 = new UserInfo("yi", "Jiang");
    		System.out.println(user2.toString());
    		System.out.println("-----------------------");
    		user2.setLocation("Qingdao City");
    		user2.setAge(22);
    		user2.logOn();
    		System.out.println(user2.toString());
    		
    	}
    }
    
    Name: Jiang Linda
    Location: Not specified
    Age: 0
    Status: Offline
    -----------------------
    Name: Jiang Linda
    Location: Virginia
    Age: 20
    Status: Online
    -----------------------
    Name: Jiang yi
    Location: Not specified
    Age: 0
    Status: Offline
    -----------------------
    Name: Jiang yi
    Location: Qingdao City
    Age: 22
    Status: Online
    
    

    5.2 模拟账户存取

    5.2.1 Account
    package week5;
    
    public class Account
    {
    	private String acctNumber;  //银行帐号
    	private String name;        //姓名
    	private double balance;    //余额
    	private static final double RATE = 0.035; //利息
    	
    	public Account(String acctNumber, String name, double balance)
    	{
    		this.acctNumber = acctNumber;
    		this.name = name;
    		this.balance = balance;
    	}
    	
    	//存款
    	public double deposit(double amount)
    	{
    		return balance += amount;
    	}
    	
    	//取款
    	public double withdraw(double amount)
    	{
    		return balance -= amount;
    	}
    	
    	//加息
    	public double addInterest()
    	{
    		return balance *= (1 + RATE);
    	}
    	
    	public String toString()
    	{
    		//打印输入余额(四舍五入)保留2位小数
    		double balanceT = (double)Math.round(balance*100)/100;
    		String output = 
    				  "AcctNumber: " + acctNumber
    				+ "
          Name: " + name
    				+ "
       Balance: " + balanceT + "
    ";
    		return output;
    	}
    }
    
    5.2.2 AccountDrive
    package week5;
    
    public class AccountDrive
    {
    
    	public static void main(String[] args)
    	{
    		Account acct1 = new Account("60000001", "Alice", 222);
    		Account acct2 = new Account("60000002", "Eric", 2222);
    		Account acct3 = new Account("60000003", "Lia", 22222);
    		
    		acct1.deposit(300.00);   //acct1存款300
    		acct2.deposit(500.00);   //acct2存款500
    		acct2.withdraw(400.00);  //acct2取款400
    		System.out.print(acct1.toString());
    		System.out.print(acct2.toString());
    		System.out.println(acct3.toString());
    		
    		//分别对三个账号加息
    		acct1.addInterest();
    		acct2.addInterest();
    		acct3.addInterest();
    		System.out.print(acct1.toString());
    		System.out.print(acct2.toString());
    		System.out.print(acct3.toString());
    	}
    }
    
    AcctNumber: 60000001
          Name: Alice
       Balance: 522.0
    AcctNumber: 60000002
          Name: Eric
       Balance: 2322.0
    AcctNumber: 60000003
          Name: Lia
       Balance: 22222.0
    
    AcctNumber: 60000001
          Name: Alice
       Balance: 540.27
    AcctNumber: 60000002
          Name: Eric
       Balance: 2403.27
    AcctNumber: 60000003
          Name: Lia
       Balance: 22999.77
    
    

    期中测试

    Test 1. 求15以内的正奇数之和

    -------------------------2016-11-11更新

    /*
     * 1. 求15以内的正奇数之和;即求1+3+5+7+9+11+13+15的和。
     */
    public class OddNumberSum
    {
    	public static void main(String[] args)
    	{
    		int sum = 0;
    		for (int i = 0; i <= 15; i++)
    		{
    			if (i % 2 == 1) sum += i;
    		}
    		System.out.println("15以内的正奇数之和为" + sum);
    	}
    }
    
    15以内的正奇数之和为64
    

    Test 2. 新版猜数字

    import java.util.Scanner;
    
    /*
     * 6. 猜数字新版。
     * 规定:生成一个100以内的整数,
     * 只给提示猜大了或猜小了,直到猜对为止;
     * 并统计次数
     */
    public class GussNumberNew
    {
    	public static void main(String[] args)
    	{
    		//生成一个 1-100 的随机数
    		int randomDigit = (int) (Math.random()*100 + 1);
    		int gussNumber; //猜的数字
    		int count = 0;  //猜的次数
    		
    		Scanner scan = new Scanner(System.in);
    		//System.out.println(randomDigit);
    		do
    		{
    			count++;
    			System.out.print("请输入一个100以内的整数:");
    			gussNumber = scan.nextInt();
    			
    			if (gussNumber < randomDigit)
    				System.out.println("抱歉,猜小了。");
    			if (gussNumber > randomDigit)
    				System.out.println("抱歉,猜大了。");
    
    		} while (gussNumber != randomDigit);
    		
    		System.out.println("您猜了" + count + "次。");
    		System.out.println("恭喜您,猜对啦!");
    		
    		scan.close();
    	}
    }
    
    请输入一个100以内的整数:50
    抱歉,猜大了。
    请输入一个100以内的整数:25
    抱歉,猜大了。
    请输入一个100以内的整数:12
    抱歉,猜大了。
    请输入一个100以内的整数:6
    抱歉,猜小了。
    请输入一个100以内的整数:9
    抱歉,猜小了。
    请输入一个100以内的整数:10
    抱歉,猜小了。
    请输入一个100以内的整数:11
    您猜了7次。
    恭喜您,猜对啦!
    
    

    Test 3 读取urls.inp文件,并以“/”为分隔符将前后的内容按行输出

    www.google.com
    www.linux.org/info/gnu.html
    thelyric.com/canlender/
    www.cs.vt.edu/undergraduate/about
    youtube.com/watch?v=EHCRimwRGLs
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    /*
     * 3. 读取urls.inp文件,并以“/”为分隔符将前后的内容按行输出。
     */
    public class TextFileInputTest
    {
    
    	public static void main(String[] args)
    	{
    		//文件放在项目路径下(相对路径)
    		String fileName = "urls.inp";
    		Scanner inputStream = null;
    		Scanner scan = null;
    
    		try
    		{
    			inputStream = new Scanner(new File( fileName));
    		} catch (FileNotFoundException e)
    		{
    			System.out.println("Error opening the file " + fileName);
    			System.exit(0);
    		}
    
    		while (inputStream.hasNextLine())
    		{
    			String line = inputStream.nextLine();
    			System.out.println("URL: " + line);
    			
    			scan = new Scanner(line);
    			scan.useDelimiter("/");
    			while (scan.hasNext())
    				System.out.println("   "+scan.next());
    			
    			System.out.println();
    		}
    		scan.close();
    		inputStream.close();
    	}
    }
    
    URL: www.google.com
       www.google.com
    
    URL: www.linux.org/info/gnu.html
       www.linux.org
       info
       gnu.html
    
    URL: thelyric.com/canlender/
       thelyric.com
       canlender
    
    URL: www.cs.vt.edu/undergraduate/about
       www.cs.vt.edu
       undergraduate
       about
    
    URL: youtube.com/watch?v=EHCRimwRGLs
       youtube.com
       watch?v=EHCRimwRGLs
    
    

    Test 4 将用户输入的一行字符串分解到单词

    import java.util.ArrayList;
    import java.util.Scanner;
    
    /*
     * 4.将用户输入的一行字符串分解到单词,加入ArrayList<String>类型
     * 的变量 inputList中,输出inputList的各元素分正序和逆序输出。
     */
    public class InputStringTest
    {
    	public static void main(String[] args)
    	{
    		ArrayList<String> inputList = new ArrayList<>();
    		Scanner scan = new Scanner(System.in);
    		
    		System.out.print("请输入一行单词以空格分隔:");
    		String line = scan.nextLine();
    		//I like you
    
    		//字符串分割
    		String arrayStr[] = line.split(" ");
    		for (String string : arrayStr)
    		{
    			inputList.add(string);
    		}
    		//正序输出
    		for (String word : inputList)
    		{
    			System.out.print(word + " ");
    		}
    		System.out.println();
    		//逆序输出
    		for (int i = inputList.size()-1; i >= 0 ; i--)
    		{
    			System.out.print(inputList.get(i) + " ");
    		}
    		scan.close();
    	}
    }
    
    请输入一行单词以空格分隔:I like you
    I like you 
    you like I 
    

    Test 5 生成Temperatures.java和TemperatureInfo.java两个类

    
    import java.util.ArrayList;
    
    /* 5.1 Temperatures类:
     * 定义ArrayList<Integer>类型的动态数组temperature,用以存储用户输入的温度数据。
     * getLowestTemp()和getHighestTemp()方法分别 返回输入的最大温度值和最小温度值;
     * toString()方法输出所有输入的温度 及  最大值、最小值。
     * 然后加入两个方法:lowerMinimun(int lowIn)和higherMaximum(int highIn)
     * 用来比较与之前输入的多个温度的最小值和最大值,从而输出两者之间的较小值和较大值。
     */
    public class Temperatures
    {
    	ArrayList<Integer> temperature;// 存储用户输入的温度数据
    
    	Temperatures(ArrayList<Integer> temperaturesIn)
    	{
    		if (temperaturesIn == null) //空对象则new
    		{
    			temperaturesIn = new ArrayList<Integer>();
    		}
    		temperature = temperaturesIn;
    		//temperature.add(0); //默认添加一个元素
    	}
    
    	// 输入一个温度,返回此时的最小值
    	public int lowerMinimun(int lowIn)
    	{
    		temperature.add(lowIn);
    		return (getLowestTemp());
    	}
    
    	// 输入一个温度,返回此时的最大值
    	public int higherMaximum(int highIn)
    	{
    		temperature.add(highIn);
    		return getHighestTemp();
    	}
    
    	// 返回此最小温度值
    	public int getLowestTemp()
    	{
    		int min = temperature.get(0);//至少有一个元素,否则报错
    		for (int i = 1; i < temperature.size(); i++)
    		{
    			if (temperature.get(i) < min)
    				min = temperature.get(i);
    		}
    		return min;
    	}
    
    	// 返回此最大温度值
    	public int getHighestTemp()
    	{
    		int max = temperature.get(0);//至少有一个元素,否则报错
    		for (int i = 1; i < temperature.size(); i++)
    		{
    			if (max < temperature.get(i))
    				max = temperature.get(i);
    		}
    		return max;
    	}
    
    	//输出所有输入的温度 及  最大值、最小值。
    	@Override
    	public String toString()
    	{
    		String output;
    		output = "	Temperatures:"
    				+ temperature.toString()
    				+ "
    	Low is :" + getLowestTemp()
    				+ "
    	High is:" + getHighestTemp();
    		return output;
    	}
    
    	public static void main(String[] args)
    	{
    		ArrayList<Integer> tList = new ArrayList<Integer>();
    		tList.add(3);
    		tList.add(2);
    		tList.add(5);
    		tList.add(6);
    		Temperatures temps = new Temperatures(tList);
    		System.out.println(temps.toString());
    
    		temps.lowerMinimun(1);
    		temps.higherMaximum(66);
    		System.out.println(temps.toString());
    	}
    }
    
    	Temperatures:[3, 2, 5, 6]
    	Low is :2
    	High is:6
    	Temperatures:[3, 2, 5, 6, 1, 66]
    	Low is :1
    	High is:66
    
    
    import java.util.ArrayList;
    import java.util.Scanner;
    
    /*
     * 5.2 TemperatureInfo类:
     * 接收用户输入的多个温度值(以” ”为结束标识)。
     * 创建Temperatures 类型的temps对象引用变量,
     * 根据用户输入的字符来决定调用相应的方法。
     */
    public class TemperaturesInfo
    {
    
    	public static void main(String[] args)
    	{
    		//Temperatures temps = new Temperatures(null);
    		ArrayList<Integer> tList = new ArrayList<Integer>();
    		
    		Scanner scan = new Scanner(System.in);
    		do
    		{
    			System.out.print("Please input the temperates:");
    			String temp = scan.nextLine();
    			
    			//输入的第一个字符为空格则结束接收
    			if (temp.toCharArray()[0] == ' ') break;
    			tList.add( Integer.parseInt(temp) );
    			
    		} while (true);
    		
    		Temperatures temps = new Temperatures(tList);
    		
    		//[L]ow temp, [H]eigh temp, [P]rint, [E]nd: "
    		String menu = "Enter choice - [L]ow temp, [H]eigh temp, [P]rint, [E]nd: ";
    		while (true) 
    		{
    			char choice;
    		    System.out.println(menu);
    	        choice = scan.nextLine().charAt(0);
    
    			if (choice != 'L' && choice != 'l' && choice != 'H' && choice != 'h' 
    					&& choice != 'p' && choice != 'P' && choice != 'e' && choice != 'E' )
    			{
    					System.out.println
    					("Your selection is incorrect, please re-enter!
    ");
    					continue;
    			}
    			switch (choice)
    			{
    			case 'L':
    			case 'l':
    				System.out.println("	Low is :" + temps.getLowestTemp());
    				System.out.println();
    				break;
    			case 'H':
    			case 'h':
    				System.out.println("	High is:" + temps.getHighestTemp());
    				System.out.println();
    				break;
    			case 'P':
    			case 'p':
    				System.out.println(temps.toString());
    				System.out.println();
    				break;
    			case 'E':
    			case 'e':
    				scan.close();   //关闭输入
    				System.out.println("Exiting the program...");
    				System.exit(0); //终止当前正在运行的 Java 虚拟机。
    			}
    		}
    	}
    }
    
    Please input the temperates:12
    Please input the temperates:-20
    Please input the temperates:100
    Please input the temperates:56
    Please input the temperates:-35
    Please input the temperates: 
    Enter choice - [L]ow temp, [H]eigh temp, [P]rint, [E]nd: 
    l
    	Low is :-35
    
    Enter choice - [L]ow temp, [H]eigh temp, [P]rint, [E]nd: 
    h
    	High is:100
    
    Enter choice - [L]ow temp, [H]eigh temp, [P]rint, [E]nd: 
    p
    	Temperatures:[12, -20, 100, 56, -35]
    	Low is :-35
    	High is:100
    
    Enter choice - [L]ow temp, [H]eigh temp, [P]rint, [E]nd: 
    e
    Exiting the program...
    
    

    week6

    6 Cylinder(一)

    -------------------------2016-11-12更新

    package week6;
    
    import java.text.DecimalFormat;
    
    /*
     * 6.1 创建 Cylinder类,以存储标签、半度;
     * 方法包括获得及设置这些成员变量,计算直径、周长面积及体积。 
     */
    public class Cylinder
    {
    	private String lable; //存储标签
    	private double radius; //圆柱半径
    	private double height; //圆柱的高
    	Cylinder(String lable, double radius, double height)
    	{
    		this.lable = lable;
    		this.radius = radius;
    		this.height = height;
    	}
    	
    	public String getLable()
    	{
    		return lable;
    	}
    
    	public boolean setLable(String lable)
    	{
    		boolean flag = true;
    		
    		if (lable.isEmpty()) flag = false;
    		else this.lable = lable.trim();
    		//String.trim()截去字符串开头和末尾的空白
    		return flag;
    	}
    
    	public double getRadius()
    	{
    		return radius;
    	}
    
    	public void setRadius(double radius)
    	{
    		this.radius = radius;
    	}
    
    	public double getHeight()
    	{
    		return height;
    	}
    
    	public void setHeight(double height)
    	{
    		this.height = height;
    	}
    
    	//返回圆柱底面直径
    	public double diameter()
    	{
    		return radius * 2;
    	}
    	
    	//返回圆柱底面周长
    	public double circumference()
    	{
    		return diameter() * Math.PI;
    	}
    	
    	//返回 表面积 = 圆柱底面积×2 + 底面周长×高
    	public double area()
    	{
    		return Math.PI * radius * radius * 2
    				+ circumference() * height;
    	}
    	
    	//返回 圆柱底体积
    	public double volumn()
    	{
    		return Math.PI * radius * radius * height;
    	}
    	
    	@Override
    	public String toString()
    	{
    		String output = null;
    		DecimalFormat df = new DecimalFormat("#,##0.0##");
    		output = lable
    				+ " is a cylinder with radius = " + df.format(radius)
    				+ " units and height = " + df.format(height)
    				+ " units, "
    				+ "
    which has diameter = " + df.format(diameter())
    				+ " units, circumference = " + df.format(circumference())
    				+ " units, "
    				+ "
    area = " + df.format(area())
    				+ " square units, and volume = " + df.format(volumn())
    				+ " cubic units.
    ";
    		return output;
    	}
    	
    	public static void main(String[] args)
    	{
    		Cylinder c1 = new Cylinder("Small Example", 4.0, 10.0);
    		Cylinder c2 = new Cylinder("Medium Example", 22.1, 30.6);
    		Cylinder c3 = new Cylinder("Large Example", 100.0, 200.0);
    		c1.setLable("");
    		System.out.println(c1);
    		System.out.println(c2);
    		System.out.println(c3);
    	}
    }
    
    Small Example is a cylinder with radius = 4.0 units and height = 10.0 units, 
    which has diameter = 8.0 units, circumference = 25.133 units, 
    area = 351.858 square units, and volume = 502.655 cubic units.
    
    Medium Example is a cylinder with radius = 22.1 units and height = 30.6 units, 
    which has diameter = 44.2 units, circumference = 138.858 units, 
    area = 7,317.837 square units, and volume = 46,952.189 cubic units.
    
    Large Example is a cylinder with radius = 100.0 units and height = 200.0 units, 
    which has diameter = 200.0 units, circumference = 628.319 units, 
    area = 188,495.559 square units, and volume = 6,283,185.307 cubic units.
    
    package week6;
    
    import java.util.Scanner;
    
    /*
     * 6.2  CylinderApp 测试类
     * 输入 标签、半径及高度,并初始化对象
     */
    public class CyliderApp
    {
    	public static void main(String[] args)
    	{
    		Scanner scan = new Scanner(System.in);
    		String lable;
    		double radius;
    		double height;
    		
    		System.out.println("Enter label, radius and height for a cylinder.");
    		System.out.print("	lable: ");
    		lable = scan.nextLine();
    		System.out.print("	radius: ");
    		radius = Double.parseDouble(scan.nextLine());
    		System.out.print("	height: ");
    		height = Double.parseDouble(scan.nextLine());
    		scan.close();
    		
    		Cylinder cylinder = new Cylinder(lable, radius, height);
    		System.out.println(cylinder);
    	}
    }
    
    
    Enter label, radius and height for a cylinder.
    	lable: Small Example
    	radius: 4.0
    	height: 10.0
    Small Example is a cylinder with radius = 4.0 units and height = 10.0 units, 
    which has diameter = 8.0 units, circumference = 25.133 units, 
    area = 351.858 square units, and volume = 502.655 cubic units.
    
    
  • 相关阅读:
    MVC 自定义异常过滤特性
    写一个左中右布局占满屏幕,其中左右两块是固定宽度200,中间自适应宽度, 要求先加载中间块,请写出结构及样式。
    请写出jQuery绑定事件的方法,不少于两种
    用js写个原生的ajax过程
    link和@import的区别
    attribute和property的区别是什么?
    请简要描述margin重复问题,及解决方式
    display:none;与visibility:hidden;的区别
    web标准以及w3c标准
    css优先级
  • 原文地址:https://www.cnblogs.com/oucbl/p/5927315.html
Copyright © 2011-2022 走看看