Java处理数组
1.使用输入值初始化数组
public class javaP213数组 {
public static void main(String[] args) {
double[] mylist=new double[10];
java.util.Scanner input =new java.util.Scanner(System.in);
System.out.print("Enter "+mylist.length+"values: ");
for(int i=0;i<mylist.length;i++) {
mylist[i] = input.nextDouble();
System.out.print(mylist[i] + " ");
}
}
}
2.使用随机数初始化数组
随机指定范围内N个不重复的数_王陈锋的博客-CSDN博客public class zuoye9_23_2 { public static int[] randomCommon(int min,int max,int n) { int str[]=new int[n]; int i=0,j=0; while(i<n){ int num=(int)(Math.random()*(max-min+1))+min;//分配一个随机数 for(j=0;j.https://blog.csdn.net/m0_58138734/article/details/120436045?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163955454216780357239180%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=163955454216780357239180&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_v2~rank_v29-2-120436045.pc_v2_rank_blog_default&utm_term=%E9%9A%8F%E6%9C%BA&spm=1018.2226.3001.4450
(Math.random() 使用)Java随机抽数(48人),随机抽出j个_王陈锋的博客-CSDN博客_随机抽人package com;import java.util.*;public class sentence { public static void main(String[] args) { int i,j; int a[]=new int[49]; Scanner reader=new Scanner(System.in); System.out.println("本程序从48座号中进行随机抽数"); ...https://blog.csdn.net/m0_58138734/article/details/118976161?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163955454216780357239180%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=163955454216780357239180&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_v2~rank_v29-1-118976161.pc_v2_rank_blog_default&utm_term=%E9%9A%8F%E6%9C%BA&spm=1018.2226.3001.4450
3.显示数组
利用for、while循环输出数组内容
对于char[]类型数组,可以使用一条打印语句打印。例如下面:
char[] city={'d','a','b'}; System.out.println(city);
4.对所有元素求和
double[] mylist={1,2,3,4,5,6,7,8,9,0};
double total =0;
for(int i=0;i<mylist.length;i++)
total+=mylist[i];
System.out.println("total="+total);
5.找出最大元素
double[] mylist={1,2,3,4,5,6,7,8,9,0};
double max=mylist[0];
for(int i=1;i<mylist.length;i++)
if(mylist[i]>max)max=mylist[i];
System.out.println("max="+max);
6.找出最大元素的最小下标值
mylist={1,5,3,4,5,5}如果数组中含有多个最大元素,那么找出最大元素的最小下标值也是常态。
double[] mylist={1,5,3,4,5,5};
double max=mylist[0];
int indexOfMax=0;
for(int i=1;i<mylist.length;i++)
if (mylist[i] > max) {max = mylist[i];
indexOfMax = i;}
System.out.println("max="+max);
System.out.println("indexOfMax="+indexOfMax);
7.随机打乱
需要对数组中的元素进行任意的重新排序,打乱(shuffling)
产生随意一个下标,然后数组互换
double[] mylist={1,5,3,4,5,5};
for(int i=0;i<mylist.length-1;i++){
int j=(int)(Math.random()*mylist.length);
double temp=mylist[i];
mylist[i]=mylist[j];
mylist[j]=temp;
}
for(double ss:mylist)
System.out.print(ss+" ");
8.移动元素
下面的例子:将元素向左移动一个位置并且将第一个元素放在最后一个元素的位置
double[] mylist={1,2,3,4,5,6,7,8,9,0};
double temp=mylist[0];
for(int i=1;i<mylist.length;i++)
mylist[i-1]=mylist[i];
mylist[mylist.length-1]=temp;
for(double ss:mylist)
System.out.print(ss+" ");