我用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] + " ");
}
}
}
但它不起作用?
答案 0 :(得分:0)
所以我实际上从你的评论中解析了代码(kudos到@Mat进行编辑,BTW)并将其放入Eclipse中。它从1-10写出20个随机数就好了。你必须更加具体地说明你的意思“不起作用。”
至于获得最低和最高,你可以尝试这样的最低价:
private int findLowest(int[] numberList)
{
//set the first item in the array as the lowest
int intLowest = numberList[0];
//then check if any of the remaining numbers are lower
for (int intCounter = 1; intCounter < numberList.length; intCounter++)
{
if (numberList[intCounter] < intLowest)
{
intLowest = numberList[intCounter];
}
}
return intLowest;
}
当然,如果将此函数添加到ArrayRandom类,则需要将此函数声明为“static”。基于此,找出最高数字的东西应该不会太难。
答案 1 :(得分:0)
此类将生成随机填充的数组或随机大小。这是你想要的吗?
import java.util.Random;
public class ArrRandom {
public static void main (String args[]) {
Random r = new Random();
int arr[] = new int[r.nextInt (100)];
for (int i = 0; i < arr.length; i++){
//random numbers from 1 to 10:
arr[i] = r.nextInt(10) + 1;
}
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
}
}