我用java编写代码,但我需要将它转换为硬拷贝(这意味着用户不需要输入元素)。我需要程序自动使用随机数。我知道随机的方法。 这是我的代码:如何在数组中使用随机数?
import java.io.*;
class arr
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
int ar[]=new int[100];
int n,i,j,pos,ch;
System.out.print("Enter number of element :-");
n=Integer.parseInt(br.readLine());
if(n<=99)
{
for(i=0;i<n;i++)
{
System.out.print("Enter any no :-");
ar[i]=Integer.parseInt(br.readLine());
}
do
{
System.out.println("\n1.Ele insert...");
System.out.println("2.Ele delete...");
System.out.println("3.Ele display...");
System.out.println("4.Exit");
System.out.print("Enter your choice :-");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.print("Enter position number :-");
pos=Integer.parseInt(br.readLine());
if(pos<n)
{
for(j=n-1;j>=pos-1;j--)
ar[j+1]=ar[j];
System.out.print("Enter new inserting element :-");
ar[j+1]=Integer.parseInt(br.readLine());
n++;
}
else
System.out.println("Sory invalid position number enterde.....");
break;
case 2:
System.out.print("Enter position number :-");
pos=Integer.parseInt(br.readLine());
if(pos<n)
{
for(j=pos-1;j<n;j++)
ar[j]=ar[j+1];
System.out.println("element deleted......");
n--;
}
else
System.out.println("Sory invalid position number enterde.....");
break;
case 3:
for(i=0;i<n;i++)
System.out.print(ar[i]+"\t");
System.out.println();
break;
case 4:
System.out.println("Program end.......");
break;
default:
System.out.println("Invalid enter select......");
}
}while(ch != 4);
}
else
System.out.println("Out of range........");
}
}
所以我的问题是:
- 如何使用随机数
- ,我想添加更多的功能,用于寻找最小号和最大号
我一直在使用这个方法试了随机:
import java.util.Random;
public class ArrayRandom{
public static void main(String args[]){
Random r = new Random();
int arr[] = new int[20];
for(int i = 0; i < 20; i++){
//random numbers from 1 to 10:
arr[i] = r.nextInt(10) + 1;
}
for(int i = 0; i < 20; i++){
System.out.print(arr[i] + " ");
}
}
}
但它不起作用?
请不要在评论中张贴代码,这是不可读的。编辑您的问题,下次添加它。你的问题是非常不清楚的,你的'ArrayRandom'类_does_工作,所以请编辑你的问题,以更好地解释你的代码中没有工作或失踪的东西。 – Mat 2011-12-24 14:42:41
它的工作。你期望从中得到什么? – Lion 2011-12-24 14:45:57
随机它不工作? – user578613 2011-12-24 14:52:19