我用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