Troubleshooting Array Lists in Java

In summary: Also, it's true that you can use 'break' to get out of a loop and you don't need to set found to false. But then you don't need to test if it's false either. It's a style thing. It's usually used when you're in a loop that you know you're going to exit when you find something. Not necessarily a bug, but it's a code smell.In summary, this code involves inputting a list of integer values into an array and performing several operations on it. These include determining the number of positive and negative values, updating the values based on their location in the array, and searching for specific values using the Sequential Search algorithm. There is also a Bubble
  • #1
Hypnos_16
153
1

Homework Statement



Input a list of n integer values into a 1-D array and do the following:
• determine and output the number of positive values and the number of negative values
• update the array values as follow
• if the value is located at an even-numbered subscript, replace the value by its square • if the value is located at an odd-numbered subscript, replace the value by its cube
• input a list of search values and, using the Sequential Search, search for each value and report its location in the list (if found); otherwise output a message
• using the Bubble Sort algorithm, sort the list into descending order.

Homework Equations



okay so i have most of this done, I'm just looking or some troubleshooting because something has gone wrong. The code will be below.

The Attempt at a Solution



Code:
import java.util.Scanner; 
public class Assignment6Question1{
	public static void main(String[] args){
		int index = 0;
		int PosCount = 0;
		int NegCount = 0;
		int SearchKey = 0;
		boolean found = false;
      		Scanner in = new Scanner(System.in);
		System.out.print("Enter number of values you would like to input: ");
		int SIZE = in.nextInt();
      		int [] Values = new int [SIZE];
		for (int NUM = 0; NUM < SIZE; NUM++)
      		{
         		System.out.print("Enter value of number: ");
         		index = in.nextInt();
			if (index < 0){
				NegCount++;
			} else {
				PosCount++;
			}
			if ((NUM % 2 != 0)||(NUM == 0)){
				index = (index * index * index);
			} else {
				index = (index * index);
			}
			Values[NUM] = index;
      		}
		int NUM = 0;
		System.out.print("Would you like to search for a value? (Y / N): ");
		String ANS = in.next().toUpperCase();
		while (ANS.equals("Y")){
			System.out.print("Enter value you would like to search for: ");
			SearchKey = in.nextInt();
			while ((!found)&&(NUM < SIZE))
				if (SearchKey == Values[NUM])
					found = true;
				else
					NUM = NUM + 1;
			if (found == true){
				System.out.print("Search for value " + SearchKey + " was Successful! It was found at location " + (NUM + 1) + " Would you like to search for another value? (Y / N): ");
				ANS = in.next().toUpperCase();	
			} else { 
				System.out.print("Search for value " + SearchKey + " was UnSuccessful. Would you like to search for another value? (Y / N): ");
				ANS = in.next().toUpperCase();			
			}		 
		}
		System.out.println("Number of Negative Values = " + NegCount);
		System.out.println("Number of Positive Values = " + PosCount);
   	}
}
whenever i attempt to run it and search for a number, the search is either always successful, or always a failure. Whenever it's success it says the answer is in the 1st slot in the array regardless of whatever number i put into search.
Any suggestions what's wrong?

Code:
Enter number of values you would like to input: 2
Enter value of number: 1
Enter value of number: 2
Would you like to search for a value? (Y / N): y
Enter value you would like to search for: 1
Search for value 1 was Successful! It was found at location 1 Would you like to search for another value? (Y / N): y
Enter value you would like to search for: 2
Search for value 2 was Successful! It was found at location 1 Would you like to search for another value? (Y / N):

a read of the typescript in case what i was saying got tangly.
 
Last edited:
Physics news on Phys.org
  • #2
A comment not related to the bug, but still important: All variables should start with a lower case letter. Very annoying when they're not, trust me. It's a universal convention in Java and many other languages.

You have a couple of problems. The big one is that you fail to initialize NUM to 0 and found to false at the start of the search loop. That's causing the lion's share of the problems. Remember, they need to be initialized every time the loop starts.

I also suggest that, after you set found to true when you find the number, break out of the loop. You've found it, no need to keep searching.

Also watch the curly braces. I suggest using them even when not strictly needed since not using them often causes needless bugs. Seems small, but it isn't. I see it happen *all the time*. Also, it's clearer and more obvious, which is one of the big important qualities of good code.
 
  • #3
Okay so I've gotten over the main problem of my program, but the problem I'm having now is that it seems to not be incrementing the NUM counter properly. Like it will check the value in the first element of the array and if the number isn't there it will just automatically then say it's not in the array at all. Or that's how I'm taking it now. Any advice for how i can modify that?

Scratch that. I figured it out. Thanks for your help though.
 
Last edited:
  • #4
Hypnos_16 said:
Okay so I've gotten over the main problem of my program, but the problem I'm having now is that it seems to not be incrementing the NUM counter properly. Like it will check the value in the first element of the array and if the number isn't there it will just automatically then say it's not in the array at all. Or that's how I'm taking it now. Any advice for how i can modify that?

Ok, so you've added this right after the 'while(ANS.equals("Y")){':
Code:
found = false;
NUM = 0;
Is that what you have? Or did you put it in the following while loop after 'while ((!found)&&(NUM<SIZE))'?

And does your matching if/else block look like this?
Code:
                                if (SearchKey == Values[NUM]) {
                                        found = true;
                                        break;
                                } else {
                                        ++NUM;
                                }
I should mention that I turned 'NUM = NUM + 1;' into '++NUM'. It does the same thing, but it's shorter and (I find) clearer. It's not a bug, but incrementing by one is what ++ is for. You may want to make sure you know the difference between pre and post incrementing, however.

EDIT: Ah, glad you got it working. And you're welcome.
 
  • #5


It seems like there are a few issues with your code that could be causing the problems you are experiencing. Here are some suggestions for troubleshooting:

1. Check your logic for updating the array values. In your code, you are using the variable "index" to store the input value and then updating it based on whether it is located at an even or odd index. However, you are also using "index" to store the input value in the array. This means that the original input value is being overwritten with the updated value before it is even added to the array. I would suggest using a separate variable for the updated value and then adding it to the array.

2. Double check your loop conditions. In your search loop, you are using a while loop with two conditions - one for checking if the value has been found and one for checking if the loop has reached the end of the array. However, if the value is not found, the loop will keep running indefinitely because the second condition will never be met. You could add a third condition to check if the loop has reached a certain number of iterations, or use a for loop with a set number of iterations.

3. Test your code with different input values. It's possible that your code is only working for certain input values and not others. Try using a variety of positive and negative numbers and see if the results are consistent.

I hope these suggestions help you troubleshoot and fix the issues with your code. If you continue to have trouble, try breaking down the problem into smaller parts and testing each part separately. This can help pinpoint where the issue is occurring. Good luck!
 

What is an array list in Java?

An array list in Java is a data structure that allows you to store and manipulate a collection of objects. It is similar to an array, but it is dynamically sized and can hold objects of different types.

How do I create an array list in Java?

To create an array list in Java, you can use the ArrayList class. First, you need to import the class using the import statement. Then, you can declare an array list variable and instantiate it using the new keyword, followed by the ArrayList class name and a set of parentheses.

How do I add elements to an array list in Java?

To add elements to an array list in Java, you can use the add() method. This method takes an object as a parameter and adds it to the end of the array list. You can also use the add(index, element) method to specify the position where you want to insert the element.

How do I access elements in an array list in Java?

To access elements in an array list in Java, you can use the get() method. This method takes the index of the element you want to retrieve as a parameter and returns the element at that position. You can also use a for loop to iterate through the elements in the array list.

How do I remove elements from an array list in Java?

To remove elements from an array list in Java, you can use the remove() method. This method takes the index of the element you want to remove as a parameter and deletes it from the array list. You can also use the clear() method to remove all elements from the array list.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
3
Views
878
  • Engineering and Comp Sci Homework Help
Replies
18
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
21
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
10
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
17K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
1K
Back
Top