Java基础语法和面向对象代码汇总

 基础语法

package com.ly.java1030Summary;

import java.util.Scanner;

public class Function {
	/*
	 * 需求
	 * 抽奖规则:用户输入的四位数会员号百位数字等于产生的随机数即为幸运会员
	 * 产生随机数的方法:int random = (int)(Math.random()*10);
	 * 
	 */
	public void zhongJiang(){
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入你的会员号:");
		int VipNum = sc.nextInt();
		int baiwei = (VipNum/100)%10;
		//生成0-9随机数
		int random = (int)(Math.random()*10);
		System.out.println(random);
		if(baiwei == random){
			System.out.println(VipNum+"号客户,恭喜你中奖");
		}else{
			System.out.println(VipNum+"号客户,谢谢惠顾");
		}
	}
	
	/*
	 * 打印菱形
	 */
	public void printLingxing(){
		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < 6-i; j++) {
				System.out.print(" ");
			}
			for (int j = 0; j < 2*i-1; j++) {
				System.out.print("*");
			}
			System.out.println();
		}
		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < i; j++) {
				System.out.print(" ");
			}
			for (int j = 0; j < 11-2*i; j++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}
	
	/*
	 * 打印99乘法表
	 */
	public void printChenfabiao(){
		for (int i = 1; i < 10; i++) {
			for (int j = 1; j <= i; j++) {
				System.out.print(i+"*"+j+"="+i*j+"\t");
			}
			System.out.println();
		}
	}
	
	/*
	 * 根据用户输入数字,打印数字三角形
	 * 将输入代码添加捕获异常
	 */
	public void printNumTriangle(){
		System.out.print("请输入大于1的整数");
		Scanner sc = new Scanner(System.in);
		int num = 0;
		try{
			num = sc.nextInt();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			System.out.println("请输入数字");
		}
		for (int i = 0; i < num+1; i++) {
			for (int j = 0; j < num-i; j++) {
				System.out.print(" ");
			}
			for (int j = 0; j < 2*i-1; j++) {
				System.out.print(i);
			}
			System.out.println();
		}
	}
}

 数组操作

package com.ly.java1030Summary;

import java.util.Arrays;

public class ArrayOperator {
	
	/*
	 * 打印数组
	 */
	public void printArrFor(int[] arr){
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i]+" ");
		}
	}
	public void printArrForeach(int[] arr){
		for (int i : arr) {
			System.out.print(i);
			System.out.print(" ");
		}
	}
	
	/*
	 * 判断数组中是否存在用户输入的数字
	 */
	public boolean searchNumInArr(int[] arr,int num){
		/*
		 * 遍历数组,一一比较是否与num相等
		 * 若相等返回真
		 */
		for (int i : arr) {
			if(i == num){
				return true;
			}
		}
		return false;
	}
	
	/*
	 * 求数组最大值
	 */
	public int maxNumInArr(int[] arr){
		//假定最大值是数组第一位,注意:假定的值一定存在于数组
		int maxNum = arr[0];
		for (int i = 0; i < arr.length; i++) {
			if(arr[i] > maxNum){
				//假如有数比设定的大,交换两个值
				int temp = arr[i];
				arr[i] = maxNum;
				maxNum = temp;
			}
		}
		return maxNum;
	}
	/*
	 * 数组排序
	 */
	
	public int[] sortArr(int[] arr){
		/*
		 * 冒泡排序
		 * 相邻比大小
		 * 外层n-1
		 * 内层n-i-1
		 */
		for (int i = 0; i < arr.length-1; i++) {
			for (int j = 0; j < arr.length-i-1; j++) {
				if(arr[j] < arr[j+1]){
					//降序
					int temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}	
			}
		}
		return arr;
	}
	
	/*
	 * 向一个数组插入一个数,并降序排列
	 * 
	 */
	public int[] insertAndSortArr(int[] arr,int num){
		/*
		 * 思路:
		 * 1.判断数组中是否存在该数字,若存在,则排序返回即可
		 * 2.不存在,判断数组最后一位是否为空,若为空则插入最后一位,然后排序返回数组
		 * 3.若数组最后一位不为空,需要数组容量+1,并将数组插入数组最后一位,排序后返回数组
		 */
		//声明变量记录下标
		for (int i = 0; i < arr.length; i++) {
			if(arr[i] == num){
				//数组存在该数字
				return sortArr(arr);
			}
		}
		//不存在该数字,需要判断是否需要扩容
		int index;
		if(arr[arr.length-1] == 0){
			//不需要扩容
		}else{
			//需要扩容
			arr = Arrays.copyOf(arr, arr.length+1);
		}
		index = arr.length-1;
		arr[index] = num;
		return sortArr(arr);
	}
	
	
	
	
}

学生数组

package com.ly.java1030Summary;

import java.util.Arrays;

public class Student {

	private String name;
	private int age;
	
	
	/*
	 * 将学生对象插入学生数组
	 */
	public Student[] addStudent(Student[] stus,Student stu){
		int index = -1;
		//判断数组最后一位是否为空
			if(stus[stus.length-1].equals(null)){
				for (int i = 0; i < stus.length; i++) {
					if(stus[i].equals(null)){
						//记录数组第一个空位下标
						index = i;
					}
				}
			}else{
				//需要扩容
				stus = Arrays.copyOf(stus, stus.length+1);
				index = stus.length-1;
			}
		stus[index] = stu;
		return stus;
	}
	
	/*
	 * 在数组中按名字查找某个学生,返回布尔值
	 */
	public boolean searchInStuArr(Student[] stus,String name){
		for (Student student : stus) {
			if(student.name.equals(name))
				return true;
		}
		return false;
	}
	
	/*
	 * 给定范围在数组中查询是否存在某个学生
	 */
	public boolean searchInStuArr(Student[] stus,String name,int a,int b){
		for (int i= a; i <= b; i++) {
			if(stus[i].name.equals(name))
				return true;
		}
		return false;
	}
	
	//打印学生数组所有信息
	public void printStus(Student[] stus){
		for (Student student : stus) {
			System.out.print(student+"\t");
		}
	}
	//打印学生信息
	public void printStu(Student stu){
		System.out.println(stu);
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "[name=" + name + ", age=" + age + "]";
	}
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}
	/**
	 * @param age the age to set
	 */
	public void setAge(int age) {
		if(age <0 || age >100){
			System.out.println("超出范围,默认为20");
			this.age = 20;
		}else{
			this.age = age;
		}
	}
	
	
	
}

多态 

//多态

package com.ly.java1030Summary;

public class Master {

	public void fill(Pet p){
		p.eat();
	}
}

package com.ly.java1030Summary;

public abstract class Pet {

	private String name;
	private int age;
	
	
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}


	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}


	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}


	/**
	 * @param age the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}


	public Pet() {
		super();
		// TODO Auto-generated constructor stub
	}


	public Pet(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}


	public abstract void eat();
	
}
package com.ly.java1030Summary;

public class Dog extends Pet{

	private String brand;
	
	public void pickDisc(){
		System.out.println("狗子扔飞盘");
	}
	/**
	 * @param brand
	 */
	public Dog(String brand,String name, int age) {
		super(name,age);
		this.brand = brand;
	}
	/**
	 * 
	 */
	public Dog() {
		super();
		// TODO Auto-generated constructor stub
	}
	/**
	 * @param name
	 * @param age
	 */
	public Dog(String name, int age) {
		super(name, age);
		// TODO Auto-generated constructor stub
	}


	/**
	 * @return the brand
	 */
	public String getBrand() {
		return brand;
	}


	/**
	 * @param brand the brand to set
	 */
	public void setBrand(String brand) {
		this.brand = brand;
	}


	@Override
	public void eat() {
		// TODO Auto-generated method stub
		System.out.println("小狗吃骨头");
	}

	
}

package com.ly.java1030Summary;

public class Cat extends Pet{

	private String sex;
	
	public void swimmingOnBed(){
		System.out.println("小猫可以床上游泳");
	}
	public Cat() {
		super();
		// TODO Auto-generated constructor stub
	}


	public Cat(String name, int age) {
		super(name, age);
		// TODO Auto-generated constructor stub
	}


	public Cat(String name, int age, String sex) {
		super(name,age);
		this.sex = sex;
	}


	/**
	 * @return the sex
	 */
	public String getSex() {
		return sex;
	}


	/**
	 * @param sex the sex to set
	 */
	public void setSex(String sex) {
		this.sex = sex;
	}


	@Override
	public void eat() {
		// TODO Auto-generated method stub
		System.out.println("小猫吃鱼");
	}

}

接口 

//接口
package com.ly.java1030Summary;

public interface CPU {
	String getBrand();
	double getBasicRate();
}
package com.ly.java1030Summary;

public class IntelCPU implements CPU {

	@Override
	public String getBrand() {
		// TODO Auto-generated method stub
		return "i9 13900k";
	}

	@Override
	public double getBasicRate() {
		// TODO Auto-generated method stub
		return 5.8;
	}



}
package com.ly.java1030Summary;

public interface EMS {
	String getBrand();
	int getCapacity();
}
package com.ly.java1030Summary;

public class Sumsung implements EMS {

	@Override
	public String getBrand() {
		// TODO Auto-generated method stub
		return "三星B-die颗粒内存条";
	}

	@Override
	public int getCapacity() {
		// TODO Auto-generated method stub
		return 32;
	}

}
package com.ly.java1030Summary;

public interface HardDisk {
	int getCapacity();
}
package com.ly.java1030Summary;

public class XPG implements HardDisk {

	@Override
	public int getCapacity() {
		// TODO Auto-generated method stub
		return 2048;
	}

}
package com.ly.java1030Summary;

public class MyPC {

	CPU cpu = new IntelCPU();
	EMS ems = new Sumsung();
	HardDisk hd = new XPG();
	
	public void showPcInfo(){
		System.out.println("计算机组成如下:");
		System.out.println("CPU品牌:"+cpu.getBrand()+",\tCPU主频:"+cpu.getBasicRate()+"GHz");
		System.out.println("内存品牌:"+ems.getBrand()+",\t内存容量:"+ems.getCapacity()+"G");
		System.out.println("硬盘容量:"+hd.getCapacity()+"G");
	}
	
}

测试类

//以上代码测试类
package com.ly.java1030Summary;

public class Call {
	/*
	 * 这个方法是Function类中的方法调用测试总和
	 */
	public void callFunction(){
		Function cf = new Function();
		cf.printLingxing();
		cf.printChenfabiao();
		cf.zhongJiang();
		cf.printNumTriangle();
	}
	/*
	 * 这个方法是ArrayOperator类中方法调用测试总和
	 */
	public void callArrayOperator(){
		int[] arr = {11,12,3,44,25};
		ArrayOperator ap = new ArrayOperator();
		ap.printArrForeach(arr);
		System.out.println(ap.searchNumInArr(arr, 12));
		System.out.println(ap.maxNumInArr(arr));
		ap.printArrForeach(ap.insertAndSortArr(arr, 69));
	}
	
	public void callStudent(){
		Student stu1 = new Student("zhangsan1",11);
		Student stu2 = new Student("zhangsan2",12);
		Student stu3 = new Student("zhangsan3",13);
		Student stu4 = new Student("zhangsan4",14);
		Student stu5 = new Student("zhangsan5",15);
		Student stu = new Student();
		Student[] stus = new Student[1];
		stus[0] = stu1;
		stus = stu.addStudent(stus, stu2);
		stus = stu.addStudent(stus, stu3);
		stus = stu.addStudent(stus, stu4);
		stus = stu.addStudent(stus, stu5);
		stu.printStus(stus);
		System.out.println();
		boolean flag = stu.searchInStuArr(stus, "zhangsan5", 0, 4);
		System.out.println(flag);
		
	}
	
	public void callMaster(){
		Master m = new Master();
		//向上转型
		Pet p1 = new Dog("程程","拉布拉多",2);
		Pet p2 = new Cat("丹丹",2,"狸花");
		m.fill(p1);
		m.fill(p2);
		
		//向下转型,此时需要判断类型是否匹配
		if(p1 instanceof Dog)
			((Dog)p1).pickDisc();
		if(p2 instanceof Cat)
			((Cat)p2).swimmingOnBed();
	}
	
	public void callInterface(){
		MyPC mpc = new MyPC();
		mpc.showPcInfo();
	}
	
}

异常 

//异常
package com.sky.yichang.homework;

//加入不继承RuntimeException而是直接继承Exception,在
public class AgeException extends RuntimeException {

	public AgeException() {
		super();
		// TODO Auto-generated constructor stub
	}

	public AgeException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

}
package com.sky.yichang.homework;

public class ScoreException extends RuntimeException{

	public ScoreException() {
		super();
		// TODO Auto-generated constructor stub
	}

	public ScoreException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

}
package com.sky.yichang.homework;

public class User {

	private String name;
	private int age;
	private int score;
	
	public static void print1(){
		User user = new User();
		user.getAge();//静态方法可以访问非静态资源
		//getName();//静态方法不能直接访问非静态资源,但是可以通过对象调用		
		
	}
	public void print(){
		System.out.println(this);
		getName();
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "User [name=" + name + ", age=" + age + ", score=" + score + "]";
	}
	
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}

	public User(String name, int age) {
		super();
		this.name = name;
		if(age<1 || age>100)
			throw new AgeException("年龄输入错误,必须在0到100之间");
		else
			this.age = age;
	}
	
	public User(String name, int age, int score) throws ScoreException {
		super();
		this.name = name;
		if(age<1 || age>100)
			throw new AgeException("年龄输入错误,必须在0到100之间");
		else
			this.age = age;
		if(score<0 || score>100)
			throw new ScoreException("分数输入有误,必须在0到100");
		else
			this.score = score;
	}
	/**
	 * @return the score
	 */
	public int getScore() {
		return score;
	}
	/**
	 * @param score the score to set
	 * @throws ScoreException 
	 */
	public void setScore(int score) {
		if(score<0 || score>100)
			throw new ScoreException("分数输入有误,必须在0到100");
		else
			this.score = score;
	}
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}
	/**
	 * @param age the age to set
	 * @throws AgeException 
	 */
	public void setAge(int age) {
		if(age<1 || age>100)
			throw new AgeException("年龄输入错误,必须在0到100之间");
		else
			this.age = age;
			
	}
}
package com.sky.yichang.homework;

public class Operator {

	public void callUser(){
		User user1  = new User();
		user1.setName("甘雨");
		try {
			user1.setAge(3500);
			
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("年龄输入有误,已经改为默认值18");
			user1.setAge(18);
		}finally{
			user1.print();
		}
	}
	
	public void callUser2(){
		User user2 = new User();
		try {
			user2.setName("胡桃");
			user2.setAge(15);
			user2.setScore(150);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("分数输入有误,已经给了默认值80");
			user2.setScore(80);
		}
		finally{
			user2.print();
		}
	}
}
package com.sky.yichang.homework;

public class Demo {

	public static void main(String[] args) {
		Operator op = new Operator();
		op.callUser();
		op.callUser2();
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值