1、 計算整數X和整數Y的最大公約數
請用類和方法實現(定義一個類,在類中定義一個求最大公約數的方法),命名時請按照規范命名。在main方法中獲取用戶輸入的兩個整數,調用之前寫的方法,輸出它們的最大公約數。利用FindBugs查找程序中是否存在bug。
import java.util.Scanner;
public class Demo {
public void compare(int a,int b){
int i = a>b?a:b;
for(;i>0;i--){
if(a%i==0&&b%i==0){
System.out.println("a、b的最大公約數為"+i);
break;
}
}
return;
}
public static void main(String[] arg){
Demo demo = new Demo();
System.out.println("請輸入a:");
Scanner num1 = new Scanner(System.in);
int a=num1.nextInt();
System.out.println("請輸入b:");
Scanner num2 = new Scanner(System.in);
int b=num2.nextInt();
demo.compare(a, b);
}
}
2、 邏輯覆蓋的應用
按照所給的程序流程圖,分別寫出語句覆蓋、分支覆蓋的測試用例,以及它所覆蓋的路徑。
語句覆蓋:
X | Y | 路徑 |
3 | 2 | abc |
5 | 0 | aef |
4 | 0 | aeg |
分支覆蓋:
X | Y | 路徑 |
3 | 2 | abc |
3 | 1 | abd |
5 | 0 | aef |
4 | 0 | aeg |
附加題:根據程序流程圖,寫出代碼(定義一個類和方法來實現),用JUnit生成單元測試,並利用前面設計的測試用例進行測試。
public class Demo {
public void demo(int x,int y){
if(x<4||y>0){
if(y>1){
y=y+1;
System.out.println("X="+x+",Y="+y);
}
else{
System.out.println("X="+x+",Y="+y);
}
}
else{
if(x>=5){
x=x-y;
System.out.println("X="+x+",Y="+y);
}
x=x+y;
System.out.println("X="+x+",Y="+y);
}
}
}
測試用例:
import static org.junit.Assert.*;
import org.junit.Test;
public class DemoTest {
public static void main(String[] args){
Demo demo =new Demo();
demo.demo(3,2);
demo.demo(3,1);
demo.demo(5,0);
demo.demo(4,0);
}
}