Click here to Skip to main content
15,881,689 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have an array with 5 elements in it. Now, what I want is, when I enter one of those elements, the program should show me the address of that entered array.
Java
import java.util.Scanner;
public class location_of_an_element_in_array
{
	public static void main(String[] args)
	{
		int arr[];
		arr = new int[5];
		int i;
		int search;
		
		Scanner input = new Scanner(System.in)
		for(i=1;i<=5;i++)
		{
		System.out.println("Enter number:");
		arr[i] = input.nextInt();
		}
		
		System.out.println("\nWhich number's locattion you want to search?");
		search = input.nextInt();
		
		
	}
}

This is what I've done so far. Please help on how to achieve the desired task.
Posted
Updated 27-Jan-13 6:15am
v2
Comments
Sergey Alexandrovich Kryukov 27-Jan-13 12:17pm    
You mix app an array with its element and generally hardly understand what you are doing...
—SA
suhan 2012 27-Jan-13 12:26pm    
and that's why I need your help.
Sergey Alexandrovich Kryukov 27-Jan-13 13:05pm    
Yes, I understand that, but, as a result of your confusion, you did not explain what do you want to achieve. You always need to start with the ultimate goal, not technical terms. In particular, what this array should express, what's the scenario and why?
—SA

1 solution

Your code is quite weak:

- class names start with capital letter. Always!
- each code line has to end with a ";"
- init and assign variables as you need them - in the loop-header, when asking for a value. That limits the scope (not here in the example, but in general)
- the for-loop:
- all being beside of humans do count from 0. Do so too please.
- a loop with 5 elements is counted therefore from 0-4 (end condition "<5" is preferable over "<=4").


Java
public class Location_of_an_element_in_array {

	public static void main(String[] args) {
		int arr[] = new int[5];
		
		// fill Array
		Scanner input = new Scanner(System.in);
		for (int i = 0; i < 5; i++) {
			System.out.println("Enter number:");
			arr[i] = input.nextInt();
		}

		// search
		System.out.println("\nWhich number's location you want to search?");
		int search = input.nextInt();

		//TODO: add loop with search here!
		
	}
}


Now the code runs.
Please use Eclipse or Netbeans for coding - both IDE will guide you through the process! There is no reason not to use one of them.

This is a homework task. You will have to add the search yourself. Please ask when you get stuck in that, also debugging the code can help you a lot (google for that according to the IDE you're using).

Have fun!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900