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

请问这两道题有办法解决吗?
//打印菱形
public   class   lingxing   {
public   static   void   main(String[]   args){
for(int   i=1;i <=11;i++){
for(int   j=1;j <=9-i   &&   j <=11-2*i;j++)
System.out.print( "   ");
for(int   j=1;j <=i   &&   j <=12-i;j++)
System.out.print( '* ');
System.out.println();
}
}
}

中间要求有9个星星,并且只能用一个for循环.

/*5、 声明一个数组50个元素,利用随机数填充数组1-10之间的数字。  
定义一个类,将填充好的数组作为参数构造这个类的对象,
然后调用对象的方法来计算该数组中各个数字出现的机率,
方法返回字符串数组并显示出来,提示是否继续填充。。。。。*/
public   class   shuzu   {
public   static   void   main(String[]   args){
int   r   =   0;
int[]   random   =   new   int[10];
for(int   i=0;i <random.length;i++){
random[r]   =   (int)(Math.random()*100)+1;
System.out.print(random[r]+ "   ");
random[i]++;
}
for(int   i=0;i <10;i++){
System.out.println(r+ "数出现了 "+random[i]+ "次 ");
}
}
}

这道题我实在想不出,希望大家指点一二.

------解决方案--------------------
第一题..
把一个for拆两半算一个for吧...
public class lingxing {
public static void main(String[] args) {
int n = 5;
int width = 2 * n - 1;
char[] c = new char[width];
for (int i = 0; i < width; i++)
c[i] = ' ';
int big = n - 1;
int small = n - 1;
for (int i = 0; i < n; i++) {
c[big] = '* ';
c[small] = '* ';
System.out.println(c);
big++;
small--;
}
for (int i = n; i < 2 * n - 1; i++) {
big--;
small++;
c[big] = ' ';
c[small] = ' ';
System.out.println(c);
}
}

}

------解决方案--------------------
第二个...不知道是不是这个意思
import java.util.*;
public class shuzu {
public static void main(String[] args) {
Random r = new Random();
int[] ai = new int[50];
for(int i=0; i <ai.length; i++)
ai[i] = r.nextInt(10) + 1;
Probability p = new Probability(ai);
System.out.println(p.calculate());
}
}

class Probability {
int[] ai;
Probability(int[] ai) {
this.ai = ai;
}
public String calculate() {
Map <Integer, Integer> m = new TreeMap <Integer, Integer> ();
for(int i=0; i <ai.length; i++) {
if(m.containsKey(ai[i]))
m.put(ai[i], m.get(ai[i])+1);
else
m.put(ai[i], 1);
}
StringBuilder sb = new StringBuilder( "{ ");
Iterator it = m.entrySet().iterator();
while(it.hasNext()) {
Map.Entry me = (Map.Entry)it.next();
sb.append( "( ");
sb.append(me.getKey());
sb.append( ", ");
double i = (Integer)me.getValue();
sb.append(i / ai.length);
sb.append( ") ");
}
sb.append( "} ");
return sb.toString();
}
}
------解决方案--------------------
/**
* project_name: Test
* package_name: netsource
* package_declaration: package netsource;
* filename: Many_Question.java
* author: yuhaiming
* date: 2007-9-17
*/
package netsource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;