//分數類
private int num; //分子
private int den; //分母
/**
* 構造器
* @param num
* @param den
*/
public Rational(int num, int den) {
this.num = num;
this.den = den;
}
/**
* 構造器(修剪空白)
* 例如 :傳入字符串"2/3" 將其中的"2"取出作爲分子 "3"作爲分母
* @param s 傳入字符串s
*/
public Rational(String s){
String[] tt = s.split("/");//把一個字符串撕裂,"/"爲中介點
num = Integer.parseInt(tt[0].trim());//把字符串轉爲整數
den = Integer.parseInt(tt[1].trim());//把字符串轉爲整數
}
/**
* 計算分數乘法
* @param other
* @return
*/
public Rational mul(Rational other){
return new Rational(this.num * other.num ,this.den * other.den);
}
/**
* 分數化簡(約分)的方法(分子和分母同時除以最大公約數)
*/
public Rational simplify(){
//取分子分母的絕對值,保存最大公約數在divisor
int divisor = gcd(Math.abs(num), Math.abs(den));
num /= divisor;//分子除以最大公約數,
den /= divisor;//分母除以最大公約數
return this;//返回當前分數Rational(除後的分數)
}
/**
* 分數的正規化(分母或分子出現負數時)
* @return 化簡後的分數
*/
public Rational normalize(){
if(den < 0){
den = -den;
num = -num;
}
return this;
}
/**
* 最大公約數計算
* @param x 傳入分子x
* @param y 傳入分母y
* @return 返回約數i 或返回1
*/
private int gcd(int x , int y){
if(x > y){
int temp = x;
x = y;
y = temp;
}
for(int i = x; i > 1; i--){
if(x % i == 0 && y % i == 0){
return i;
}
}
return 1;
}
public String toString(){
return num + "/" + den;
}
}
//測試
package com.shen;
public class Test {
public static void main(String[] args){
System.out.println(StringUtil.revers("My girl!"));
String str = " you are my girl!";
char ch = 'r';
System.out.println(str + "裏" + ch + "有" + StringUtil.count(str, ch) + "個");
}
}