1.写一个求素数的算法。
import java.util.Scanner; public class fourteenYear { public static void main(String[] args) { // 1. 写一个求素数的算法。 Scanner sc = new Scanner(System.in); int n = sc.nextInt(); boolean flag = true; if(n == 2) flag = false; for(int i = 2; i<n/2;i++){ if(n%i != 0){ flag = false; } } if(!flag) { System.out.println("是素数"); }else { System.out.println("不是素数"); } } }
2.在一个有序数列中插入一个数,使得数列依然有序,并且把最大的那个数剔除出队列
没有读懂题目什么意思,于是就全部都用队列写了。
public static void main(String[] args) { LinkedList<Integer> queue = new LinkedList<>(); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for(int i = 0;i < 10;i++){ queue.add(i); } int j = 0; for (int i = 0; i < queue.size(); i++) { int num = queue.peek(); if(num<n){ queue.offer(queue.poll()); j = i; } } queue.addFirst(n); for (int i = 0; i <= queue.size()-j-1; i++) { System.out.println(queue.toString()); if(i == queue.size()-j-2 ){ if(j != 0) { int x = queue.poll(); System.out.println(x + " " + i); break; } } if(j == 0 && i == queue.size()-j-1){ int x = queue.poll(); System.out.println(x + " " + i); break; } queue.offer(queue.poll()); } for (Integer i : queue) { System.out.print(i + " "); } }
3.写一个类,类里面包含了私有成员变量和方法,并且用该类里面的方法给私有成员变量赋值和输出
class Student{ private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }