This post was updated 682 days ago and some of the ideas may be out of date.
输出1-100之间所有素数
public class T03 {
public static boolean isPrime(int x){
for (int i = 2; i < x; i++) {
if(x%i==0)
return false;
}
return true;
}
public static void main(String[] args) {
for (int i = 2; i <=100 ; i++) {
if(isPrime(i))
System.out.print(i+",");
}
}
}
求其最大公约数和最小公倍数
辗转相除法
import java.util.Scanner;
public class T02 {
public static void main(String[] args) {
int a,b,m,n,r;
Scanner sc = new Scanner(System.in);
a=sc.nextInt();
b=sc.nextInt();
m=a>b?a:b;
n=a<b?a:b;
while(n!=0){
r=m%n;
m=n;
n=r;
}
System.out.println(m+","+a*b/m);
}
}
求所有四位数中,各位数字之和等于5,并且不含数字1的数。要求输出所有满足以上条件的四位数
public class T01 {
public static void main(String[] args) {
int i,a,b,c,d;
for(i=1000;i<10000;i++){ //1234
a=i%10;
b=i/10%10;
c=i/100%10;
d=i/1000;
if(5==a+b+c+d&&a!=1&&b!=1&&c!=1&&d!=1)
System.out.print(i+",");
}
}
}
编程定义汽车类和公交车类,思考两个类的继承关系,实现如下要求:
(1) 汽车类定义如下成员:
① 两个私有成员变量:车牌号和汽车颜色;
② 一个无参构造方法;
③ 一个有参构造方法;
(2) 公交车类定义如下成员:
① 一个成员变量:准载人数;
② 一个无参构造方法;
③ 一个有参构造方法。
public class Car {
private String no;
private String color;
public Car(){}
public Car(String no,String color){
this.no=no;
this.color=color;
}
}
class Bus extends Car{
int num;
public Bus(){}
public Bus(String no,String color,int num){
super(no,color);
this.num=num;
}
}
编程实现如下要求:
(1) 定义一个抽象类表示形状类,在类中定义抽象方法求形状的周长;
(2) 定义形状类的子类圆形类,实现求其周长的方法。
public abstract class Shape {
public abstract double prime();
}
class Circle extends Shape{
double r;
@Override
public double prime() {
return 2*Math.PI*r;
}
}
参与讨论