Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

So I have this assignment for my Programming class, and I'm lost on what to do for the second part. This is the code I have so far:

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

Not much I know, but I really am confused on how I would get it to fetch the different array values. Do I have to import the util scanner to do this? Any help to point me in the right direction? Thanks guys!

share|improve this question
1  
Break down the big problem into little problems: 1) how to prompt the user and get input, and 2) with the input get and return the value based on index. –  Hovercraft Full Of Eels Jul 17 at 2:05
 
 
(Off-topic) Close your teacher's assignment. It's unclear. –  johnchen902 Jul 17 at 2:18

3 Answers

To access an index i in int[] b, you use: b[i]. For example:

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

To search through the array for a number x:

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

There are also auxiliary methods provided by the Java Arrays class.

Here's a tutorial on arrays, here's an additional Java Language Basics tutorial.

share|improve this answer

Please do the assignments in the comments below-

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 

    }

  }

}
share|improve this answer
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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.