Java Null Pointer Exception with ListSelectionEvent - java

I'm going mad with this method which results in a runtime NullPointer exception when I remove a row in my database:
private void menuListValueChanged(javax.swing.event.ListSelectionEvent evt) {
int index = menuList.getSelectedIndex();
int size = model.getSize();
if (index >= 0) {
bDeleteMenu.setEnabled(true);
} else {
bDeleteMenu.setEnabled(false);
}
Menu selectedMenu = (Menu)menuList.getSelectedValue();
menuName.setText(selectedMenu.getMenuName());
}
The error is in this line:
menuName.setText(selectedMenu.getMenuName());
and occurs only when I remove an item.
This is the error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.
I guess this happens because when I remove the item in the Jlist the selection doesn't change automatically to the next one, or something like that.
And this is the method which I use to remove an item:
private void bDeleteMenuActionPerformed(java.awt.event.ActionEvent evt) {
Menu selectedMenu = (Menu)menuList.getSelectedValue();
selectedMenu.getMenuName();
int index = menuList.getSelectedIndex();
DBConnection.deleteMenu(selectedMenu);
int size = model.getSize();
if (size == 0) {
bDeleteMenu.setEnabled(false);
} else {
if (index == model.getSize()) {
index--;
}
menuList.setSelectedIndex(index);
menuList.ensureIndexIsVisible(index);
}
model.removeElement(selectedMenu);
menuName.setText("");
}
Thank you!

Retrieving the name of the selected menu only makes sense in case where something is selected.
Replce
if (index >= 0) {
bDeleteMenu.setEnabled(true);
} else {
bDeleteMenu.setEnabled(false);
}
Menu selectedMenu = (Menu)menuList.getSelectedValue();
menuName.setText(selectedMenu.getMenuName());
with
if (index >= 0) {
bDeleteMenu.setEnabled(true);
Menu selectedMenu = (Menu)menuList.getSelectedValue();
menuName.setText(selectedMenu.getMenuName());
} else {
bDeleteMenu.setEnabled(false);
}
Hope this helps.

Related

Node problems with stack implementation of depth first search

If anyone could help me find out what I did wrong, it would be really appreciated. I have taken a few shots at this and have gotten closer with each version of my code. I started by having a linked list within the SearchPath class itself but now I moved it to the Node class. For some reason the code works and finds the end, but it does not properly remove some stuff from the stack. Feel free to give it a try. When the code finishes elements from the stack are supposed to be removed and it does but some extra coordinates end up in there. Not sure if it is because of the way I handled the processing of the already checked nodes or if it the recursion itself. This could also just be a horrible implementation of the problem that needs to be solved and maybe I need to think of another way to solve it, but I know the answer is right there. Possibly also take a look at how I included the linked list and stack as static variables within the node class. Should they have maybe been added elsewhere or could that have been causing some of the issues. Thanks a lot. Also the way it works is by inputting a grid of the same dimensions. Finish is indicated with F and start is indicated with S. The walls are X and the path is O to find the way throught path.
/* This program will implement a stack to try and traverse
a grid from a text file that contains a path. It will try
and find a path to the end and when it does it succeeds.
If it does not find the end that means that there was
not path that exists to it. Reads a file as input.
*/
import java.util.Stack;
import java.util.Scanner;
import java.io.File;
import java.io.FileReader;
import java.lang.Exception;
import java.util.LinkedList;
// This class will represent information about a part in the board and will be used by the
// algorithim to determine what to do next.
class Node {
private static Stack<Node> pathLocation = new Stack<>(); // Create a stack that will hold nodes for the algorithm
// to traverse the area.
private static LinkedList<int[]> checkedLocations = new LinkedList<int[]>();
private static int totalMoves = 0;
private int rowNumber, columnNumber;
private boolean checked;
public Node() { // Constructor for a default node.
}
// Gets the current node in the stack.
public Node getLocaiton() {
return pathLocation.peek();
}
// Removes a node from the stack.
public void removeLocation() {
pathLocation.pop();
}
// Adds a new node to the stack.
public void newLocation(Node nextPath) {
pathLocation.push(nextPath);
}
public Stack<Node> getStack() {
return pathLocation;
}
public int getRowLocation() {
return rowNumber;
}
public int getColumnLocation() {
return columnNumber;
}
public void setRowLocation(int inputRow) {
rowNumber = inputRow;
}
public void setColumnLocation(int inputColumn) {
columnNumber = inputColumn;
}
public void setChecked(boolean input) {
checked = input;
}
public boolean getChecked() {
return checked;
}
public int getTotalMoves() {
return totalMoves;
}
public void setTotalMoves(int input) {
totalMoves = input;
}
public boolean getChecked(int inputColumn, int inputRow) {
for (int[] i : checkedLocations) {
if (inputColumn == i[0] && inputRow == i[1]) {
return true;
}
}
return false;
}
public boolean addChecked(int inputColumn, int inputRow) {
this.setColumnLocation(inputColumn);
this.setRowLocation(inputRow);
for (int[] i : checkedLocations) {
if (this.getColumnLocation() == i[0] && this.getRowLocation() == i[1]) {
--totalMoves;
this.checked = true;
return this.checked;
}
}
int[] temp = { this.getColumnLocation(), this.getRowLocation() };
checkedLocations.push(temp);
this.checked = false;
++totalMoves;
return this.checked;
}
}
class Board {
private int size; // This will determine the size of the board which is obtained from the
// BoardFile class.
private char[][] boardArea; // The current location on the board. This current program supports double
// array. Could later be upgraded to support more dimensions.
private int boardColumn;
private int boardRow;
Board(BoardFile inputBoard) throws Exception { // This constructor could throw and exception.
Scanner boardRead = inputBoard.processedBoard(); // Obtained the scanner from the boardFile class.
String temp; // Strings that will be processed and saved by the scanner.
while (boardRead.hasNext()) { // Processes infromation from the board as long as there is information to read.
temp = boardRead.nextLine(); // Sets a temp string equal to what was next in the file.
int tempSize; // Remembers the size of the temp string.
size = temp.length(); // Sets the total size of game area.
boardColumn = size;
boardArea = new char[size][size];
int j = 0;
boolean startFound = false, endFound = false; // Makes sure there is a finish and a start.
while (temp.length() == size) {
for (int i = 0; i < temp.length(); ++i) { // This loop will construct the game board and
// and makes sure everything is correct.
if (temp.charAt(i) == 'X' || temp.charAt(i) == 'O' || temp.charAt(i) == 'F' || temp.charAt(i) == 'S') {
boardArea[i][j] = temp.charAt(i);
// The following if statements check to make sure there is only one instance of
// finish and start.
if (temp.charAt(i) == 'F' && !endFound) {
endFound = true;
}
else if (temp.charAt(i) == 'F' && endFound) {
throw new Exception("The finish was already found. Please check and try again.");
}
else if (temp.charAt(i) == 'S' && !startFound) {
startFound = true;
}
else if (temp.charAt(i) == 'S' && startFound) {
throw new Exception("The start was already found. Please check and try again.");
}
}
else {
// throws an exception in case one of the characters was not excpected.
throw new Exception("There was a incorrect character within the board. Please check and try again.");
}
}
if (boardRead.hasNext()) {
tempSize = temp.length(); // Assign the previous line size.
temp = boardRead.nextLine(); // Assign the next line.
if (tempSize != temp.length()) { // Check to make sure both lines are the same size.
throw new Exception("The size of the board is not correct. Please check and try again.");
}
}
else {
break;
}
++j; // Increment the row.
if (j > size - 1) { // Makes sure the area in the map is correct.
throw new Exception("The area in the map is not the same. Please check and try again.");
}
boardRow = j; // Sets the row number.
}
if (j != size - 1) {
throw new Exception("The area in the map is not the same. Please check and try again.");
}
if (!endFound) {
throw new Exception("The end was not found. Please check and try again.");
}
if (!startFound) {
throw new Exception("The start was not found. Please check and try again.");
}
}
}
public char[][] getBoardArea() { // Returns the array.
return boardArea;
}
public char getBoardLocation(int inputColumn, int inputRow) { // Gets a character a certain location
return boardArea[inputColumn][inputRow]; // within the array.
}
public int getBoardColumn() { // Gets the column total.
return boardColumn - 1;
}
public int getBoardRow() { // Gets the row total.
return boardRow;
}
}
// The class used to read a file.
class BoardFile {
private File file;
private FileReader createdBoard;
private Scanner readBoard;
BoardFile(String fileName) throws Exception { // Creates a file reader object.
file = new File(fileName);
if (!file.exists()) { // Makes sure the file is found.
throw new Exception("The file could not be found.");
}
createdBoard = new FileReader(file); // Creates the file reader.
readBoard = new Scanner(createdBoard); // Creates a new scanner object to read the board.
}
public Scanner processedBoard() { // Gets the scanner object from the read board.
return this.readBoard;
}
}
// This class is the actual searching and will be used to traverse the map.
public class PathSearch {
private Node node = new Node(); // Creates the node object to traverse the map area.
private Board board; // Creates the map.
private Integer[] saveLocation = new Integer[2]; // Create an array that saves a certain location.
PathSearch() throws Exception { // Accepts nothing but asks for a string that searchs for a file.
Scanner input = new Scanner(System.in);
String userFile;
System.out.println("Please enter the name of the file.");
userFile = input.nextLine();
input.close();
board = new Board(new BoardFile(userFile)); // This creates the board from a file that was input.
for (int i = 0; i < board.getBoardColumn(); ++i) { // Searches the board for the starting point.
for (int j = 0; j < board.getBoardRow(); ++j) {
if (board.getBoardLocation(i, j) == 'S') {
node.newLocation(new Node()); // Creates a new element in the stack.
saveLocation[0] = i; // Saves the column in which the node was found.
saveLocation[1] = j; // Saves the row in which the node was found.
System.out.println("Start found at " + (saveLocation[0]) + " " + (saveLocation[1]));
break; // Exits the loop since the information that was needed was processed.
}
}
}
if (saveLocation == null) {
throw new Exception("No starting point was found. Please check and try again.");
}
checkPath(saveLocation[0], saveLocation[1]);
}
// This method accepts two seperate inputs because it needs to remember if it
// checked the position it is currently at.
public Stack<Node> checkPath(int inputColumn, int inputRow) throws Exception {
node.addChecked(inputColumn, inputRow); // Get the current node and check if has been used already.
if (node.getChecked() && !node.getStack().empty()) { // Sees if it was checked and if the stack is not empty.
node.removeLocation(); // Removes the current node from the stack.
checkPath(node.getLocaiton()); // Uses the previous node to keep checking,
}
else {
Node tempNode = new Node(); // Creates a new temp node.
tempNode.setColumnLocation(inputColumn);
tempNode.setRowLocation(inputRow);
node.newLocation(tempNode); // Adds the temp node into the stack.
checkPath(node.getLocaiton()); // Starts checking at the new location.
}
return null; // Path was not found.
}
// This is a overloaded version of checkPath that accepts the current node
// and begins looking at the current node.
public Stack<Node> checkPath(Node node) throws Exception {
int inputColumn = node.getLocaiton().getColumnLocation();
int inputRow = node.getLocaiton().getRowLocation();
if (board.getBoardLocation(inputColumn, inputRow) == 'F') {
System.out.println("The end was found at " + node.getLocaiton().getColumnLocation()
+ " " + node.getLocaiton().getRowLocation());
System.out.println("Here is the path.");
while (!node.getStack().empty()) { // While the stack has information.
System.out.println(node.getLocaiton().getColumnLocation() + " " + node.getLocaiton().getRowLocation());
node.removeLocation(); // Remove the node to process the next.
}
System.out.println("The total moves were " + node.getTotalMoves());
return node.getStack();
}
// All statements to determine where to move next within the board.
if (inputColumn < board.getBoardColumn() && (board.getBoardLocation(inputColumn + 1, inputRow) == 'O'
|| board.getBoardLocation(inputColumn + 1, inputRow) == 'F')
&& !node.getChecked(inputColumn + 1, inputRow)) {
checkPath(inputColumn + 1, inputRow);
}
if (inputColumn > 0 && (board.getBoardLocation(inputColumn - 1, inputRow) == 'O'
|| board.getBoardLocation(inputColumn - 1, inputRow) == 'F')
&& !node.getChecked(inputColumn - 1, inputRow)) {
checkPath(inputColumn - 1, inputRow);
}
if (inputRow < board.getBoardRow() && (board.getBoardLocation(inputColumn, inputRow + 1) == 'O'
|| board.getBoardLocation(inputColumn, inputRow + 1) == 'F')
&& !node.getChecked(inputColumn, inputRow + 1)) {
checkPath(inputColumn, inputRow + 1);
}
if (inputRow > 0 && (board.getBoardLocation(inputColumn, inputRow - 1) == 'O'
|| board.getBoardLocation(inputColumn, inputRow - 1) == 'F')
&& !node.getChecked(inputColumn, inputRow - 1)) {
checkPath(inputColumn, inputRow - 1);
}
return null; // No path was found at that location.
}
}

JAVA how to implement wraparound on a deque

I am trying to implement wraparound on my double ended queue and for some reason my insertRight() and removeRight() methods are outputting wrong and my removeLeft() method is just throwing an error. I have looked around and I cannot seem to find an answer to why my methods are not working here they are:
public void insertRight(int newItem) {
if (isFull() == true) {
System.out.print("Full");
} // end of if
else {
if (right == capacity) {
right = 0;
} // end of nested if
else {
deque[right] = newItem;
nElems++;
right++;
} // end of nested else
} // end of else
}// end of insertRight
public void removeRight() {
if (isEmpty() == true) {
System.out.println("Empty");
} // end of if
if (isEmpty() == false) {
System.out.println(right);
if (right == capacity) {
right = 0;
} // end of nested if
int temp = deque[right];
right++;
nElems--;
} // end of if
}// end of removeRight
public void removeLeft() {
if (isEmpty() == true) {
System.out.println("Empty");
} // end of if
if (isEmpty() == false) {
if (left == capacity) {
left = -1;
} // end of nested if
else {
System.out.println(left);
int temp = deque[left];
left++;
nElems--;
} // end of else
} // end of if
}// end of removeLeft
A little more information on the actual meaning/values of left and right would be helpful.
At first glance, it looks like removeLeft() fails because the wrap-around point for left would be 0, not capacity, if my understanding of your code so far is correct.
Also, negative array indices do not work in java. You'll want to refer to the actual last index directly.
And I really recommend looking into code formatting. Your indentation makes it very hard to tell where one block ends and a new one begins. You could save yourself explicit comments by just following a consistent indentation pattern:
public void insertRight(int newItem) {
if (isFull()) {
System.out.print("Full");
} else {
if (right == capacity) {
right = 0;
} else {
deque[right] = newItem;
nElems++;
right++;
}
}
}
public void removeRight() {
if (isEmpty()) {
System.out.println("Empty");
} else {
System.out.println(right);
if (right == capacity) {
right = 0;
}
int temp = deque[right];
right++;
nElems--;
}
}
public void removeLeft() {
if (isEmpty()) {
System.out.println("Empty");
} else {
// My assumption inserted here:
if (left == 0) {
left = capacity - 1;
} else {
System.out.println(left);
int temp = deque[left];
left++;
nElems--;
}
}
}
I see a couple of issues here:
if (right == capacity) {
right = 0;
} // end of nested if
else {
deque[right] = newItem;
nElems++;
right++;
} // end of nested else
If right == capacity you reset the index but don't insert newItem to the array.
It should be something like this (directly typed, not tested):
if (right == capacity) {
right = 0;
} // end of nested if
deque[right] = newItem;
nElems++;
right++;
Now to your removeRight-method:
System.out.println(right);
if (right == capacity) {
right = 0;
} // end of nested if
int temp = deque[right];
right++;
nElems--;
Here you use the same algorithm to check boundaries but it should be a "mirror" to the one you used in insertRight, so something like this (directly typed, not tested):
System.out.println(right);
if (right == 0) {
right = capacity;
} // end of nested if
int temp = deque[right - 1];
right--;
nElems--;
And finally removeLeft:
if (left == capacity) {
left = -1;
} // end of nested if
else {
System.out.println(left);
int temp = deque[left];
left++;
nElems--;
} // end of else
Without the insertLeft method, I can only guess that it has similar problems.

thread "main" java.lang.NullPointerException, Implement three stack in a single array

The purpose of this code is to implement three stacks in a single array. I use linked node to implement stack. the elements are pushed into array one by one directly, and the elements in each stack are connected by previous pointer. the pointer is int value corresponding to index in array where the item is stored. nextAvaIndexmethod return next available index that can store new pushed item. Because there will space released in the beginning of the array after executing pop method. ifindexused < arr.lengthit will keep moving forward to store new item, while if indexusedreaches end of array, the method will search is there free space in beginning of array.
But when I run it, it throws NullPointerException, i know the meaning of this error, but I can't fix it. Thanks for your comments! Is the code correct? One more question of removal an item from int type array. I letarr[i].data = 0 to delete the item, and use statement arr[i].data == 0 to check if one space is null. But what if one space store0? Thanks for your suggestion!
public class FlexiblemultiStack {
private int[] toppoint = {-1, -1, -1};// assume number of stack ==3;
private int indexused = 0;
private stackNode[] arr;
public FlexiblemultiStack(int sizeEach, int stackNO) {
arr = new stackNode[sizeEach * stackNO]; //
}
public boolean isEmpty(int stackNum) {
return toppoint[stackNum] == 0;
}
public void push(int item, int stackNum) {
int lastIndex = toppoint[stackNum];
int nextIndex = nextAvaIndex();
if (nextIndex == -1) { // if nextIndex = -1, there is no more space!
System.out.println("There is no more space!");
} else {
toppoint[stackNum] = nextIndex;
arr[toppoint[stackNum]] = new stackNode(item, lastIndex);
indexused++;
}
}
public int pop(int stackNum) {
if (toppoint[stackNum] == -1) {
return 0;
} else {
int value = arr[toppoint[stackNum]].data;
int lastIndex = toppoint[stackNum];
toppoint[stackNum] = arr[toppoint[stackNum]].previous;
arr[lastIndex] = null;
indexused--;
return value;
}
}
public int peek(int stackNum) {
return arr[toppoint[stackNum]].data;
}
public int nextAvaIndex() {
int index = -1;
if (indexused == arr.length || arr[indexused].data != 0) {
for (int i = 0; i < arr.length; i++) {
if (arr[i].data == 0) { // error
index = i;
break;
}
}
return index;
} else {
return indexused;
}
}
public void print(int stackNum) {
while (toppoint[stackNum] != -1) {
System.out.print(arr[toppoint[stackNum]].data + "<--");
toppoint[stackNum] = arr[toppoint[stackNum]].previous;
}
}
public void printarr(){
for(int i = 0; i< arr.length;i++){
System.out.print(arr[i]);
}
}
public class stackNode { // Exception in thread "main" java.lang.NullPointerException
List item
private int previous;
private int data;
public stackNode(int StackSize) {
this.previous = -1;
}
public stackNode(int value, int prev) {
data = value;
previous = prev;
}
}
}
Exception in thread "main" java.lang.NullPointerException
at stackandqueue.FlexiblemultiStack$stackNode.access$000(FlexiblemultiStack.java:86)
at stackandqueue.FlexiblemultiStack.nextAvaIndex(FlexiblemultiStack.java:61)
at stackandqueue.FlexiblemultiStack.push(FlexiblemultiStack.java:32)
at stackandqueue.StackandQueue.main(StackandQueue.java:71)
/Users/xchen011/Library/Caches/NetBeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
In the pop() method, it appears you are denoting an open index by setting the array index to null (arr[lastIndex] = null). In nextAvaIndex() you check if the index is available by examining arr[i].data. If arr[i] has been set to null by pop(), you will get the NullPointerException. To make the definition of available consistent with the check for availability, try replacing arr[indexused].data != 0 with arr[indexused] != null and if(arr[i].data == 0) with if(arr[i] == null) in the nextAvaIndex() method.
public int nextAvaIndex() {
int index = -1;
if (indexused == arr.length || arr[indexused] != null) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == null) { // error
index = i;
break;
}
}
return index;
} else {
return indexused;
}
}

Java: Getting if there is an element before a specified element in an ArrayList

public static boolean isComponentBefore(GuiInterface component) {
int index = 0;
for (int i = 0; i < components.size(); i++) {
if (components.get(i).getName() == component.getName()) {
if(components.get(i- 1) == null){
return false;
}
}
}
return true;
}
I currently use this, though this can lead to ConcurrentModificationExceptions & it isn't working because it keeps throwing ConcurrentModificationExceptions whenever I try to see if the element before the element passed in is null.
I was wondering if there are other ways to do this.
Looking at your logic, you will a NullPointerException incase the component in the ArrayList before the given component is null, because components.get(i) would be null and components.get(i).getName() will throw the NPE.
You can try to change the logic here a bit. For every null element in the list, check if the next component is the component you're searching for and return accordingly.
for (int i = 0; i < components.size(); i++) {
if (components.get(i) == null) { // If a particular element is null, check if the next element is what you want
if(components.get(i+1).getName().equals(component.getName())) { // you need to handle the edge case for i+1 as well for the last iteration
return false;
}
}
}
Note that you need to compare the Strings using equals() method and not the == operator. You also need to handle the corner case of i+1 for the last iteration.
This line
if (components.get(i).getName() == component.getName()) {
Should be
if (components.get(i).getName().equals(component.getName())) {
However, your condition can never happen. If component.get(i-1) is null, then in the previous loop iteration
components.get(i).getName() // <-- null pointer exception, so
component.get(i-1) must not be null and you need to hope that i isn't 0 or you'd get an index out of bounds exception.
Use an iterator
e.g
int i = 0;
Iterator<GuiInterface > it = components.iterator();
while (it.hasNext()) {
i++;
GuiInterface thisComp = it.next ();
if (thisComp.getName().equals(component.getName())) {
if(i > 0 && components.get(i- 1) == null){ // this code does not make sense
return false;
}
}
}
Assuming the passed component is not in your list:
public static boolean isComponentBefore(GUIComponent component) {
// Start at 1 to avoid IndexOutOfBounds
for(int i = 1; i < components.size(); i++) {
if (components.get(i).getName().equals(component.getName())) {
return components.get(i - 1) != null;
}
}
// Given component is not in the list, or the list only has one element
return false;
}
Assuming the passed component is in the list:
public static boolean isComponentBefore(GUIComponent component) {
int index = components.indexOf(component);
return index > 0 && components.get(index - 1) != null;
}

Searching array for item. How to display position item was found at?

I am creating an application in BlueJ that allows the user to sort and search an unordered array. I have the search working. At present it asks the user to input a number to search the array for and returns found or not found which is fine.
I would like to be able to tell the user what position in the array that the number was found?
Below is my code for me search method:
public static void dosearch(OArray a)
{
clrscr();
if ( a.isEmpty() ) {
System.out.println("Array is Empty!");
pressKey();
return;
}
clrscr();
System.out.println("Enter number to search for : ");
int item;
item = Genio.getInteger();
if ( a.retrieve(item) == false )
System.out.println("Cannot find " + item);
else
System.out.println(item + " Found");
pressKey();
}
OArray Class code:
public class OArray extends Array
{
// These are the Fields
// Constructor
public OArray(){
super();
System.out.println("OArray Created!!! size 10");
}
public OArray(int newsize){
super(newsize);
System.out.println("OArray Created!!!");
}
public boolean addToEnd(int item)
{
if ( isFull() == true )
return false;
array[nextfree]=item;
nextfree++;
//bubbleSort();
return true;
}
public void bubbleSort()
{
int temp = 0;boolean swaps = true;int last = nextfree-1;int i = 0;
while (swaps == true )
{
swaps=false;
i = 0;
while (i < last)
{
if (array[i] > array[i+1])
{
temp = array[i+1];
array[i+1] = array[i];
array[i] = temp;
swaps=true;
}
i++;
}
}
}
public boolean retrieve(int item)
{
if ( isEmpty() )
return false;
int i=0;
while ( i < nextfree )
{
if ( array[i] >= item )
{
posfound=i;
if ( item == array[i] )
{
itemback = item;
posfound = i;
return true;
}
else return false;
}
i++;
}
posfound = nextfree;
return false;
}
public boolean addToFront(int item)
{
return addToEnd(item);
}
In general, the only way to access an item in an array is by index, so knowing the index is easy, since you already know it. The traditional idiom is that you have some sort of find() method which returns the index of the element if it is found, or -1 otherwise.
int[] a = new int[] { 7, 2, 4, 6 };
int foundAt = findItemInArray(a, 2);
if (foundAt >= 0) {
System.out.println("Found at [" + foundAt + "]");
} else {
System.out.println("Not found");
}
public static int findItemInArray(int[] a, int lookingFor) {
for (int i = 0; i < a.length; i++) {
if (a[i] == lookingFor) {
return i;
}
}
return -1;
}
You can use the linear search method.
Once you have found the number in the for loop store it's index there and then. You can display it later.

Categories