您的位置:首页 > 编程语言 > Java开发

JAVA 基础知识学习3

2017-03-27 14:19 507 查看

目录

目录
JAVA 面向对象 包装类 数字处理类 接口继承多态异常处理类
方法的参数传递

方法重载

integer类进制转换

实现星座查询类

通过类的实例访问成员变量和方法

统计字符串的实际长度的类

获取汉字拼音简码的类

编写验证E-mail地址的类

编写用选择法对数组排序的类

计算某年某月的天数

包装类 Integer Long Short Boolean Byte Chaeacter Double Float Number

十进制 二进制 十六进制互相转换

使用character 把String 转换为大写

使用character 把String 转换为小写

使用compareTo 方法比较int型数的大小

JAVA 面向对象 包装类 数字处理类 接口继承多态异常处理类

方法的参数传递

(1)编写ObjectArg类,在该类中定义几个成员变量,这个类的对象将用于演示方法传参。实例代码如下:

public class ObjectArg {
public String name=""; // 姓名
public int age=0;  // 年龄
public String sex="";  // 性别
}


(2)编写ArgDemo类,分别定义测试基本数据类型传参和对象类型传参的方法,并输出它们修改参数的结果。实例代码如下:

public class ArgDemo {
static int intArg = 10;                                                // int基础类型的测试变量
static ObjectArg objectArg = new ObjectArg();           // 对
4000
象类型的测试变量
public static void main(String[] args) {
changeIntArg(intArg);                                  // 测试int基本类型传参
System.out.println("传递给方法的int类型参数:"+intArg);
System.out.println("intArg=" + intArg);                 // 输出传递给方法的变量值
objectArg.age = 29;                                     // 初始化对象数据
objectArg.name = "李经理";
objectArg.sex = "男";
changeOjbectArg(objectArg);                              // 测试对象传参
System.out.println("传递给方法的对象:");
printObjInfo(objectArg);                              // 输出传递给方法的对象信息
}
/**
* 测试基本数据类型传参的方法
* @param arg int类型参数
*/
public static void changeIntArg(int arg) {
System.out.println("=========实参未改变============= ");
System.out.println("changeIntArg()方法开始执行");
System.out.println("int类型参数arg=" + arg);
System.out.println("将参数值除以2");
arg = arg / 2;                                              // 改变参数值
System.out.println("arg=" + arg);
}
/**
* 测试对象类型传参的方法
* @param arg 对象参数
*/
public static void changeOjbectArg(ObjectArg arg){
System.out.println("========实参被改变============== ");
System.out.println("changeOjbectArg()方法开始执行");
System.out.println("输出对象参数:");
printObjInfo(arg);                                        // 输出对象参数信息
arg.name="王经理";                                    // 修改对象参数信息
arg.sex="女";
arg.age=20;
System.out.println("修改后的对象参数:");
printObjInfo(arg);                                        // 输出修改后的对象参数信息
}
/**
* 输出对象信息的方法
* @param arg 对象参数
*/
private static void printObjInfo(ObjectArg arg) {
System.out.println("\t名字:"+arg.name);
System.out.println("\t性别:"+arg.sex);
System.out.println("\t年龄:"+arg.age);
}
}


方法重载

方法的重载就是在同一个类里定义了多个名称相同,但是参数类型和数量以及顺序不同的方法。为了更好地理解重载,这里将编写一个方法重载的实例。

实现过程如下:

public class OverLoadTest {
static int sum = 0; // 成员变量sum 用于累加计数

/**
* 把两个int类型整数相加方法
*
* @param numA
*            第一个int整数
* @param numB
*            第二个int整数
* @return 两数之和,类型为int
*/
public static int add(int numA, int numB) {
return numA + numB;
}

/**
* 把两个double 类型实数相加的方法
*
* @param numA
*            第一个double 实数
* @param numB
*            第二个double 实数
* @return 两数值和,类型为double
*/
public static double add(double numA, double numB) {
return numA + numB;
}

/**
* 累加int 类型整数的方法,该方法将参数值累加到sum成员变量
*
* @param numA
*            int 整形参数
* @return
*/
public static int add(int numA) {
sum += numA;
return sum;
}

/**
* 把int整数和double类型实数相加的方法
*
* @param numA
*            int整数
* @param numB
*            double实数
* @return 整数和实数的和,类型为double
*/

public static double add(int numA, double numB) {

return numA + numB;

}

/**
*
* 把double实数和int类型整数相加的方法
*
* @param numA
*            double实数
*
* @param numB
*            int整数
*
* @return 整数和实数的和,类型为double
*
*/

public static double add(double numA, int numB) {

return numA + numB;

}

public static void main(String args[]) {

System.out.println("调用add(int, int)方法:" + add(1, 2));

System.out.println("调用add(double, double)方法:" + add(2.1, 3.3));

System.out.println("调用add(int)方法:" + add(1));

System.out.println("调用add(int, double)方法:" + add(4, 5.89));

System.out.println("调用add(double, int)方法:" + add(5.89, 4));

}

}


integer类进制转换

import java.util.Scanner;

public class RadixConversion {
private static Scanner scan = new Scanner(System.in);

public static void main(String[] args) {

System.out.println("请输入一个十进制数字:");

int num = scan.nextInt(); // 读取用户输入整数

String value = Integer.toBinaryString(num); // 把整数转换为二进制格式的字符串

System.out.println("该数字的二进制格式为:" + value);

value = Integer.toHexString(num); // 把整数转换为十六进制格式的字符串

System.out.println("该数字的十六进制格式为:" + value);

value = Integer.toOctalString(num); // 把整数转换为八进制格式的字符串

System.out.println("该数字的八进制格式为:" + value);

}

}




实现星座查询类

public class QueryConstellation {
/**
* 功能:根据生日查询星座
*
* @param month
* @param day
* @return
*/
public String query(int month, int day) {
String name = "";   //提示信息
if (month > 0 && month < 13 && day > 0 && day < 32) { // 判断输入的月和日是否有效
if ((month == 3 && day > 20) || (month == 4 && day < 21)) { // 3月21~4月20
name = "您是白羊座!";
} else if ((month == 4 && day > 20) || (month == 5 && day < 21)) { // 4月21~5月20
name = "您是金牛座!";
} else if ((month == 5 && day > 20) || (month == 6 && day < 22)) { // 5月21~6月21
name = "您是双子座!";
} else if ((month == 6 && day > 21) || (month == 7 && day < 23)) { // 6月22~7月22
name = "您是巨蟹座!";
} else if ((month == 7 && day > 22) || (month == 8 && day < 23)) { // 7月23~8月22
name = "您是狮子座!";
} else if ((month == 8 && day > 22) || (month == 9 && day < 23)) { // 8月23~9月22
name = "您是处女座!";
} else if ((month == 9 && day > 22) || (month == 10 && day < 23)) { // 9月23~10月22
name = "您是天平座!";
} else if ((month == 10 && day > 22) || (month == 11 && day < 22)) { // 10月23~11月21
name = "您是天蝎座!";
} else if ((month == 11 && day > 21) || (month ==
14ab2
12 && day < 22)) { // 11月22~12月21
name = "您是射手座!";
} else if ((month == 12 && day > 21) || (month == 1 && day < 20)) { // 12月22~1月19
name = "您是摩羯座!";
} else if ((month == 1 && day > 19) || (month == 2 && day < 19)) { // 1月20~2月18
name = "您是水牛座!";
} else if ((month == 2 && day > 18) || (month == 3 && day < 21)) { // 2月19~3月20
name = "您是双鱼座!";
}
name = month + "月" + day + "日  " + name; // 组合提示信息
} else {
name = "请输入您的真实的生日!"; // 设置错误提示信息
}
return name;
}
}


通过类的实例访问成员变量和方法

public class Circ {
final float PI = 3.14159f; // 定义一个用于表示圆周率的常量PI
public float r = 0.0f;

// 定义计算圆面积的方法
public float getArea() {
float area = PI * r * r; // 计算圆面积并赋值给变量area
return area; // 返回计算后的圆面积
}

// 定义计算圆周长的方法
public float getCircumference(float r) {
float circumference = 2 * PI * r; // 计算圆周长并赋值给变量circumference
return circumference; // 返回计算后的圆周长
}

// 定义主方法测试程序
public static void main(String[] args) {
Circ circ = new Circ();
circ.r = 20; // 改变成员变量的值
float r = 20;
float area = circ.getArea(); // 调用成员方法
System.out.println("圆的面积为:" + area);// 输出面的面积
float circumference = circ.getCircumference(r); // 调用带参数的成员方法
System.out.println("圆的周长为:" + circumference); // 输出圆的周长
}
}


统计字符串的实际长度的类

public class TotalWordcount {
/**
* 功能:统计字符串的实际长度
* @param str
* @return
*/
public int total(String str) {
byte temp[];    //临时的字节数组
int strlength=0;    //字符串的实际长度
for(int i=0;i<str.length();i++){    //循环语句
temp=(str.substring(i,i+1)).getBytes(); //获取一个字符并存储到字节数组中
strlength+=temp.length; //累加字符串的长度
}
return strlength;   //返回字符串的实际长度
}
}


获取汉字拼音简码的类

public class GetCharSpell {

public String getCharSpell(String character){
String spell="";    //汉字拼音简码
String str[]=character.split("");   //将汉字分隔为数组
int length=str.length;//获取汉字的个数
byte[] a=null;  //空的字节数组
String getchar="";  //单个汉字的拼音简码
for(int i=1;i<length;i++){
a=str[i].getBytes();
if(a.length>1){
int asc=256*(a[0]+256)+(a[1]+256);
if(asc>=45217 && asc<=45252){
getchar= "A";
}else if(asc>=45253 && asc<=45760){
getchar= "B";
}else if(asc>=45761 && asc<=46317){
getchar= "C";
}else if(asc>=46318 && asc<=46825){
getchar= "D";
}else if(asc>=46826 && asc<=47009){
getchar= "E";
}else if(asc>=47010 && asc<=47296){
getchar= "F";
}else if(asc>=47297 && asc<=47613) {
getchar= "G";
}else if(asc>=47614 && asc<=48118) {
getchar= "H";
}else if(asc>=48119 && asc<=49061) {
getchar= "J";
}else if(asc>=49062 && asc<=49323) {
getchar= "K";
}else if(asc>=49324 && asc<=49895) {
getchar= "L";
}else if(asc>=49896 && asc<=50370) {
getchar= "M";
}else if(asc>=50371 && asc<=50613) {
getchar= "N";
}else if(asc>=50614 && asc<=50621) {
getchar= "O";
}else if(asc>=50622 && asc<=50905) {
getchar= "P";
}else if(asc>=50906 && asc<=51386) {
getchar= "Q";
}else if(asc>=51387 && asc<=51445) {
getchar= "R";
}else if(asc>=51446 && asc<=52217) {
getchar= "S";
}else if(asc>=52218 && asc<=52697) {
getchar= "T";
}else if(asc>=52698 && asc<=52979) {
getchar= "W";
}else if(asc>=52980 && asc<=53640) {
getchar= "X";
}else if(asc>=53689 && asc<=54480) {
getchar= "Y";
}else if(asc>=54481 && asc<=62289) {
getchar= "Z";
}
}
else{   //不是汉字时
getchar=str[i]; //简码等于本身
}
spell+=getchar; //连接生成的拼音简码
}
return spell;
}
}


编写验证E-mail地址的类

public class CheckEmail {
public boolean checkEmail(String email){
boolean result=false;
String regex = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"; //正则表达式,定义邮箱格式
if(email.matches(regex)){                            //matches()方法可判断字符串是否与正则表达式匹配
result=true;
}
return result;
}
}


编写用选择法对数组排序的类

public class ArraySort {
/**
* 升序排列
* @param arr
* @return
*/
public int[] ascSort(int[] arr){
int min=0;  //当前比较的两个数组元素中小的下标
for(int i=0;i<arr.length;i++){
min=i;
for(int j=i+1;j<arr.length;j++){
if(arr[j]<arr[min]){
min=j;  //将max设置为两个数中较小的一个的下标
}
}
//将arr[min]与arr[i]中的值互换
int t=arr[min];
arr[min]=arr[i];
arr[i]=t;
}
return arr;
}
/**
* 降序排列
* @param arr
* @return
*/
public int[] descSort(int[] arr){
int max=0;  //当前比较的两个数组元素中小的下标
for(int i=0;i<arr.length;i++){
max=i;
for(int j=i+1;j<arr.length;j++){
if(arr[j]>arr[max]){
max=j;  //将max设置为两个数中较大的一个的下标
}
}
//将arr[max]与arr[i]中的值互换
int t=arr[max];
arr[max]=arr[i];
arr[i]=t;
}
return arr;
}
}


计算某年某月的天数

/**
* 字符串工具类
* @author WuYang
*
*/
public class StringUtil {
/**
* 判断一个字符串是否为数字
* @param strNum
* @return 为数字时返回true
*/
public static boolean isNumber(String strNum){
// 判断字符串是否有效
if(strNum == null || strNum.isEmpty()){
return false;
}
// 将字符串转换为char型数组
char[] arr = strNum.toCharArray();
// 遍历字符数组
for (char c : arr) {
// 判断字符数组中的每一个数是否为数字
if(!Character.isDigit(c)){
return false;
}
}
// 字符串为数字返回true
return true;
}
/**
* 计算某年某月的天数
* @param year 年份
* @param month 月份
* @return 天数
*/
public static int account(int year, int month){
// 定义天数
int day = 0;
// 判断月份为几月
switch (month) {
// 如果月份为1、3、5、7、8、10、12天数为31天
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
// 如果月份为4、6、9、11天数为30
case 4:
case 6:
case 9:
case 11:
day = 30;
break;
}
// 判断是否为2月
if(month == 2){
// 判断年份是否闰年
if((year % 4 == 0 && year % 100 != 0) ||  (year % 4 == 0 && year % 400 == 0)){
// 闰年为29天
day = 29;
}else{
// 不是闰年为28天
day = 28;
}
}
// 返回天数
return day;
}
}


包装类 Integer Long Short Boolean Byte Chaeacter Double Float Number

/**
* @author wuyang 包装类 integer 类型
*/
public class Getint {
public static void main(String args[]) {
String str = Integer.toString(456);                // 获取数字的十进制表示
String str2 = Integer.toBinaryString(456);     // 获取数字二进制表示
String str3 = Integer.toHexString(456);        // 获取数字的十六进制表示
String str4 = Integer.toOctalString(456);       // 获取数字的八进制表示
System.out.println("'456'的十进制表示为:" + str);
System.out.println("'456'的二进制表示为:" + str2);
System.out.println("'456'的十六进制表示为:" + str3);
System.out.println("'456'的八进制表示为:" + str4);
int maxint = Integer.MAX_VALUE;         // 获取Integer类的常量值

int minint = Integer.MIN_VALUE;

int intsize = Integer.SIZE;

System.out.println("int类型可取的最大值是:" + maxint); // 将常量值输出

System.out.println("int类型可取的最小值是:" + minint);

System.out.println("int类型的二进制位数是:" + intsize);

}

}


十进制 二进制 十六进制互相转换

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import com.lyq.RadioPanel;
import com.lzw.BackgroundPanel;
import com.swtdesigner.SwingResourceManager;

public class MainFrame extends JFrame {
private static final long serialVersionUID = 1074908476800267585L;
private JTextField textField_2;
private JTextField textField;
/**
* Launch the application
* @param args
*/
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame
*/
public MainFrame() {
super();
setResizable(false);
setTitle("进制转换");
setBounds(100, 100, 490, 209);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final BackgroundPanel backgroundPanel = new BackgroundPanel();
backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class, "/res/bg.jpg"));
getContentPane().add(backgroundPanel, BorderLayout.CENTER);

textField = new JTextField();
textField.setBounds(120, 25, 297, 22);
backgroundPanel.add(textField);

final RadioPanel radioPanel = new RadioPanel();
radioPanel.setBounds(67, 53, 350, 43);
backgroundPanel.add(radioPanel);

final JLabel label = new JLabel();
label.setText("转换前:");
label.setBounds(67, 27, 52, 18);
backgroundPanel.add(label);

final JLabel label_1 = new JLabel();
label_1.setText("转换后:");
label_1.setBounds(67, 104, 52, 18);
backgroundPanel.add(label_1);

textField_2 = new JTextField();
textField_2.setBounds(120, 102, 297, 22);
backgroundPanel.add(textField_2);

final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
// 获取文本框中的字符串
String strNum = textField.getText();
// 如果文本框中的字符串不是一个数
if(!StringUtil.isNumber(strNum)){
// 错误提示
JOptionPane.showMessageDialog(null, "请输入正确的数据!");
return;
}
// 返回字符数组
char[] arr = strNum.toCharArray();
// 遍历字符数组
for (char c : arr) {
// 如果字符为"abcdef"
if("abcdef".indexOf(c) != -1){
// 转换为16进制
strNum = Long.parseLong(strNum, 16) + "";
break;
}
}
// 获取所选择的进制
int select = radioPanel.getSelect();
// 提示信息
String value = "错误!";
// 判断所选择的进制
switch (select) {
case 16:
// 转换为16进制
value = Long.toHexString(Long.valueOf(strNum));
break;
case 10:
// 转换为10进制
value = Long.toString(Long.valueOf(strNum), 10);
break;
case 8:
// 转换为8进制
value = Long.toOctalString(Long.valueOf(strNum));
break;
case 2:
// 转换为2进制
value = Long.toBinaryString(Long.valueOf(strNum));
break;
}
textField_2.setText(value);
}
});
button.setText("转换");
button.setBounds(330, 136, 88, 28);
backgroundPanel.add(button);
//
}

}


/**
* 字符串工具类
* @author YongQiang Lee
*
*/
public class StringUtil {
/**
* 判断一个字符串是否为数字
* @param strNum
* @return 为数字时返回true
*/
public static boolean isNumber(String strNum){
// 判断字符串是否有效
if(strNum == null || strNum.isEmpty()){
// 返回false
return false;
}
// 将字符串转换为字符数组
char[] arr = strNum.toCharArray();
// 遍历数组
for (char c : arr) {
// 如字符不是一个数字
if(!Character.isDigit(c)){
// 判断字符是否为"abcdef"中的字符
if("abcdef".indexOf(c) == -1){
// 返回false
return false;
}
}
}
// 返回true
return true;
}
}


public class Example {
public static void main(String[] args) {
// 创建int型变量a
int a = 128;
// 将a转换为二进制
String str1 = Integer.toBinaryString(a);
// 将a转换为八进制
String str2 = Integer.toOctalString(a);
// 将a转换为十六进制
String str3 = Integer.toHexString(a);
// 输出转换结果
System.out.println("十进制128的二进制表示是:" + str1);
System.out.println("十进制128的八进制表示是:" + str2);
System.out.println("十进制128的十六进制表示是:" + str3);
}
}


使用character 把String 转换为大写

public class Example {
public static void main(String[] args) {
// 实例化一个字符串
String oldStr = "I Love ShangHai";
// 将字符串转换为字符数组
char[] arr = oldStr.toCharArray();
// 遍历数组中的元素
for (int i = 0; i < arr.length; i++) {
// 如字符为小写将其转换为大写
if (Character.isLowerCase(arr[i])) {
arr[i] = Character.toUpperCase(arr[i]);
}
}
// 转换后的字符串
String newStr = new String(arr);
// 输出信息
System.out.println("转换前字符串的内容是:" + oldStr);
System.out.print("转换后字符串的内容是:" + newStr);
}
}


使用character 把String 转换为小写

public class Example {
public static void main(String[] args) {
// 实例化一个字符串
String oldStr = "I Love Beijing";
// 将字符串转换为字符数组
char[] arr = oldStr.toCharArray();
// 遍历数组中的元素
for (int i = 0; i < arr.length; i++) {
// 如字符为大写将其转换为小写
if (Character.isUpperCase(arr[i])) {
arr[i] = Character.toLowerCase(arr[i]);
}
}
// 转换后的字符串
String newStr = new String(arr);
// 输出信息
System.out.println("转换前字符串的内容是:" + oldStr);
System.out.print("转换后字符串的内容是:" + newStr);
}
}


使用compareTo 方法比较int型数的大小

public class Example {
public static void main(String[] args) {
// int型变量a
int a = 100;
// int型变量a
int b = 1000;
// Integer对象num1
Integer num1 = new Integer(a);
// Integer对象num2
Integer num2 = new Integer(b);
// 比较num1与num2的大小
int flag = num1.compareTo(num2);
if (flag < 0) {
System.out.println(a + "小于" + b);
} else if (flag == 0) {
System.out.println(a + "等于" + b);
} else {
System.out.println(a + "大于" + b);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: