日期:2014-05-20  浏览次数:20972 次

求教几个简单的java小程序
1,求n以内的素数;
2,输入一个正整数,倒序输出,要求递归。
3,对四个数进行排序;
4,输出如下图形
  *
  ***
 *****
  ***
  *
要求用2维矩阵.

求大侠写出完整程序,谢谢了!

------解决方案--------------------
/*
* 第一题的方法,一个迭代一个递归
*/

public static void qiushusu(int n) {
ww: for (int i = 1; i <= n; i++) {
for (int j = 2; j < i; j++) {
if (i % j == 0) {
continue ww;
}

}
System.out.println(i);

}
}

public static int qiususu(int n) {
if (n == 1) {
System.out.println(1);
return 1;
} else {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return qiususu(n - 1);
}
System.out.println(n);
return qiususu(n - 1);
}
}

/*
* 第二题的方法,一个迭代一个递归
*/
public static int num(int n) {
String s = Integer.toString(n);
String str = "";
char[] c = s.toCharArray();
for (int i = s.length() - 1; i >= 0; i--) {
str += String.valueOf(c[i]);
}
return Integer.parseInt(str);
}

public static int num1(int n, String str) {// str="";自己在方法里写
String s = Integer.toString(n);
if (s.length() == 1) {
str += s;
return Integer.parseInt(str);
} else {
str += s.charAt(s.length() - 1);
n = n / 10;
return num1(n, str);
}
}

/*
* 第三题的方法,
*/
public static void sort(int a, int b, int c, int d) {
int w[] = { a, b, c, d };
for (int i = 0; i < w.length - 1; i++) {
for (int j = 0; j < w.length - i - 1; j++) {
if (w[j] > w[j + 1]) {
int temp = w[j];
w[j] = w[j + 1];
w[j + 1] = temp;
}
}
}
for (int i : w) {
System.out.print(i + "\t");
}
}

/*
* 第四题
*/
public static void draw() {
int[][] a = new int[5][5];
int b = 2;
int length = 1;
int temp1;
int temp2;
for (int i = 0; i < 5; i++) {
temp1 = length;
temp2 =b;
for (int j = 0; j < 5; j++) {
if (j == b){
a[i][j] = '*';
if(--length>0){
b++;
}
}else {
a[i][j] = ' ';
}

}
length = temp1;
b=temp2;
if (i < 2) {
b--;
length += 2;
} else {
b++;
length -= 2;
}
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print((char)a[i][j]);
}
System.out.println();
}
}

------解决方案--------------------
第一题:
import java.util.Scanner;

public class Demo01 {
/**
*求n以内的素数
*n可以通过控制台输入
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("输入n的值:");
int n = in.nextInt();
System.out.print(n+"以内的素数有:");
for(int i=1;i<n;i++){
if(isSuShu(i)){
System.out.print(i+",");
}
}
}
public static boolean isSuShu(int x){//如果x是素数则返回true,否则返回false
boolean flag = true;
for(int i=2;i<=Math.sqrt(x);i++){
if(x%i==0)
flag = false;
}
return flag;
}
}

第二题:
import java.util.Scanner;

public class Demo02 {
/**
* 输入一个正整数,倒序输出,要求递归
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("输入一个正整数");
String str = in.next();
char[] a = str.toCharArray();
System.out.println("倒序输出:"+fun(a));