首页 技术 正文
技术 2022年11月12日
0 收藏 771 点赞 3,169 浏览 1458 个字

java随机数与数组的使用。   

一:题目

java随机数与数组的使用。

二 代码:

 public class Students {
    int number;  // 学号
    int State ;   // 年级
    int Score ;    // 成绩
    
    
 public Students(int number, int state, int score) {
        super();
        this.number = number;
        State = state;
        Score = score;
    }

public static void main(String[] args)
 {
     Students sds[]=new Students[20];
      
     for(int i=0;i<sds.length;i++)
     {    
        
    
          sds[i]=new Students(i+1,(int)(Math.random()*3+1),(int)(Math.random()*100));
          if((int)(Math.random()*3+1)==3)
          {
          System.out.println(“学号是:”+(i+1)+” ,年级:”+ 3
                  +”,成绩:”+(int)(Math.random()*100));
          }
          
        
           
        
        
        
     }
       // 求number的值
     for(int i=0;i<20;i++)
     {
        //System.out.println(sds[i]);  //此时是一个空数组,所以输出的结果就是null
     }
    
     // 求随机数的用法,年级要求在1~3之间
      
     for(int i=0;i<20;i++)
     {
         // 随机数Math.random(),产生的数是在0~1之间。
        // System.out.println((int)(Math.random()*3+1));
     }
    
     //求成绩
     /*
     for(int i=0;i<20;i++)
     {
         System.out.println((int)(Math.random()*100));
     }
     */
    
    
    
    
    
 }
}

三:分析

   1.首先是考虑如何创建一个数组,创建数组可以是一个引用型数据和基本型数据类型。而这里是引用型数据类型。涉及到引用型数据类型时要考虑到构造方法。而基本型数据则不一样。

  2.就是对随机数的应用。一般会用到Math.random()

  for(int i=0;i<20;i++)
     {
         // 随机数Math.random(),产生的数是在0~1之间。
        // System.out.println((int)(Math.random()*3+1));
     }

 注意: 用到随机数Math.random时,产生的数据在0~1之间,如果先要1~3的数据需要对Math.random()进行更改。

for(int i=0;i<20;i++)

 {

 System.out.println(sds[i].number);

 }

代码这样则会保错的。错误之处如图

java随机数与数组的使用。

则会出现没有指针。

Students sds[]=new Students[20]; 是基于学生类Students 而创建的数组,不是基本的数据类型的数组。所以会报错。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,494
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,133
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,297