-2

所以我的编程课有这个作业,我不知道第二部分要做什么。这是我到目前为止的代码:

    class SingleArray
    {
      public static void main(String[]args)
      {
        int[] b=new int[]{5,10,15,20,25,30,35,40,45,50};

我知道的不多,但我真的很困惑如何让它获取不同的数组值。我是否必须导入 util 扫描仪才能执行此操作?有什么帮助可以为我指明正确的方向吗?多谢你们!

4

4 回答 4

2

要访问 中的索引iint[] b请使用:b[i]。例如:

System.out.println(b[i]); //prints the int at index i

b[i] = 5; //assigns 5 to index i
b[i] = x; //assigns an int x, to index i

int y = b[i];  //assigns b[i] to y

在数组中搜索一个数字x

for (int i = 0; i < b.length; i++)
{
     if (b[i] == x)
     {
         //doSomething
     }
}

Java Arrays类还提供了一些辅助方法。

这是关于数组的教程,这是附加的Java 语言基础教程

于 2013-07-17T02:08:20.963 回答
0

请在下面的评论中做作业-

class SingleArray {

 // Declare an array of 10 integers. 
 // Assignment: Why did I declare it as static?
 private static int[] array = new int[] { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 };

 // A method that returns the value at a given index from the array
 // Assignment: Why the method below is static?
 private static int getValue(int index){

     return array[index];

 }    

 public static void main(String[] args){

    for (int i = 0; i < array.length; i++){

        int valueAtIndex = getValue(i);

        System.out.println("Index: " + (i + 1) + " Value: " + valueAtIndex);

        // Assignment: remove the statement "int valueAtIndex = getValue(i);" and 
        // modify the System.out.println statement to have the same result 

    }

  }

}
于 2013-07-17T02:14:12.900 回答
0
List<Integer> integerList=new ArrayList<Integer>();
for(int i=0;i<10;i++){
 integerList.add(i);
}
//you can fetch the values by using this method:
integerList.get(valueIndex);
于 2013-07-17T02:26:38.497 回答
0

这可能会有所帮助:

public class OneDimensionalArrays {
    public static void main(String[] args) {
        //initialize an array num with the respective values
        int []num={5,10,15,20,25,30,35,40,45,50};

        // The looping will work within the range of the array.
        for (int i = 0; i<num.length;i++){

            System.out.println("Enter the index to find the value of ");

            //To catch array index out of bound exception
            try{
                Scanner sc = new Scanner(System.in);
                //Save the user inputted value in indexValue variable

                int indexValue = sc.nextInt();
                // Enter 100 to terminate the program execution
                if (indexValue != 100) {
                    System.out.println("Value in the respective index of array is " + num[indexValue]);
                }
                else{
                    System.out.println("Program has been terminated by user");
                    break;
                                    }
            }
            catch (Exception e ){
                System.out.println("Enter the index within range of the array");
            }
        }
    }
}
于 2015-06-21T15:29:08.563 回答