最近预习到抽象类,我把第三天的内容用抽象类进行了功能整合,发上来大家交流一下
import java.util.*;
//输入一个范围,然后根据数字类型选择,计算该范围内该类型数字之和
class preview9_17 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入两个数以确定范围");
int start = sc.nextInt();
int end = sc.nextInt();
//1.偶数 2.奇数 3.水仙花数 4.整数
System.out.println("choose method! 1:even 2:odd 3:narcissus 4.int");
int type = sc.nextI
nt();
Num num = null;
switch(type) {
case 1:num = new Even(start,end);
break;
case 2:num = new Odd(start,end);
break;
case 3:num = new Fl(start,end);
break;
case 4:num = new Int(start,end);
break;
}
int rs = num.getSum(start,end);
Tool.printNum(rs);
}
}
abstract class Num {
public int COUNT = 0;
private int start;
private int end;
Num(int start,int end){
this.start = start;
this.end = end;
}
public int getSum(int start,int end){
if (end < start){
end = start ^ end;
start = start ^ end;
end = start ^ end;
}
for(int i = start;i <= end;i++){
getTypeSum(i);
}
return COUNT;
}
abstract void getTypeSum(int i);
}
class Int extends Num{
Int(int start,int end){
super(start,end);
}
void getTypeSum(int i){
COUNT = COUNT + i;
}
}
class Fl extends Num{
Fl(int start,int end){
super(start,end);
}
void getTypeSum(int i){
int a = 0,b = 0,c = 0;
a = i/100;
b = i/10%10;
c = i%10;
if (i==(Math.pow(a,3)+Math.pow(b,3)+Math.pow(c,3))){
System.out.println(i);
COUNT++;
}
}
}
class Even extends Num{
Even(int start,int end){
super(start,end);
}
void getTypeSum(int i){
if (i%2 == 0){
COUNT = COUNT + i;
}
}
}
class Odd extends Num{
Odd(int start,int end){
super(start,end);
}
void getTypeSum(int i){
if (i%2 != 0){
COUNT = COUNT + i;
}
}
}
class Tool {
public static int turnNum(int a,int b){
a = a ^ b;
b = a ^ b;
a = a ^ b;
return a;
}
public static void printNum(int...params){
for (int i = 0; i < params.length; i++) {
System.out.println(params[i]);
}
}
}
|
|