2、编程求解100以内的全部素数存储在int pn[ ]中,然后从屏幕打印输出。素数是指除去1以外,只能被1和它本身整除的数。public class prime { public static void main(String[] args) { // TODO Auto-generated method stub int i,j; int a=0; for(i=1;i<=100;i++) { for(j=2;j<=i/2;j++) if(i%j== 0) break; if(j>i/2) {int[] pn=new int[100]; pn[a]=i;
System.out.println(pn[a]); } } } }
1、编写一个方法,方法的返回值为一个数组,数组里存放Student类的对象,数组的大小由参数传入。在程序中调用此方法,输出数组中个元素的值。
package test1; /** * 主类 */
public class StudentDemo {
public static void main(String[] a) {
2
Student[] ss = new Student[] { new Student(\"张飞\", 88), new Student( \"张峰\", ), new Student( \"翁少\", 77), new Student( \"李莉\", 78), new Student( \"赵菲\", 90),
new Student( \"宏伟\", 95),new Student( \"王莉\", 67),new Student( \"吴天\",79), new Student( \"赵鸥\", 85),new Student( \"陈玲玲\", 93),};
//初始状态
System.out.println(\"初始状态:\"); //输出数组
for (Student s : ss) { System.out.println(s); } } } /**
* 学生类 */
class Student {
private int score;// 学号 private String name;// 姓名
public Student( String name, int score) {
this.name = name; this.score = score; }
public int getScore() { return score; }
public void setName(String name) { this.name = name; }
public void setScore(int score) { this.score = score; }
//重载toString()
public String toString() {
return \"姓名:\" + this.name +\" \" +\"成绩:\" + this.score; } }
2、在一个数组中存放10个学生信息(姓名,成绩),然后按成绩从大到小排列输出。
import java.util.Arrays;
import java.util.Comparator;
3
/** * 主类 */
public class StudentDemo {
public static void main(String[] a) {
Student[] ss = new Student[] { new Student(\"张飞\ new Student( \"张峰\翁少\ new Student( \"李莉\赵菲\
new Student( \"宏伟\王莉\吴天\ new Student( \"赵鸥\陈玲玲\ myComparable mycomp=new myComparable(); //数组排序
Arrays.sort(ss,mycomp); //排序之后
System.out.println(\"排序之后:\"); //输出数组
for (Student s : ss) { System.out.println(s); } } } /**
* 学生类 */
class Student {
private int score;// 学号 private String name;// 姓名
public Student( String name, int score) {
this.name = name; this.score = score; }
public int getScore() { return score; }
public void setName(String name) { this.name = name; }
public void setScore(int score) { this.score = score; }
//重载toString()
public String toString() {
return \"姓名:\" + this.name +\" \" +\"成绩:\" + this.score;
4
} }
//自定义的排序类。实现Comparator接口
class myComparable implements Comparator { public int compare(Object a, Object b) { Student s1 = (Student) a; Student s2 = (Student) b;
int i=s1.getScore() - s2.getScore(); if(i>0) return -1;
else if(i<0) return 1; else return 0; } }
5