I'm constantly running into a logic issue that is causing my array output to be filled with zeros

I seem to have encountered a tricky logic error in my code where the output is not as expected due to values not being returned correctly. I'm seeking guidance on how to troubleshoot this issue. Before delving into that, let me provide some context about what's happening. In the main section of my code, I am assigning values to an array 'x' which should then be passed to another file called getAllEvens. However, somewhere in the process, the values get altered or are not carried over properly, resulting in all zeros being displayed instead. Any suggestions or assistance would be greatly appreciated. Please aim to align your advice with the structure of my code or utilize simpler methods since this is for a school project. Let's proceed to the actual code.

Here is the code snippet from the main:

`int[] x = {2,4,6,8,10,12,14};
 int[] x = {2,4,6,8,10,12,14};
 int[] y = {1,2,3,4,5,6,7,8,9};
 int[] z = {2,10,20,21,23,24,40,55,60,61};

 System.out.println("Odds - " + Arrays.toString(OddsAndEvens.getAllOdds(x)));
 System.out.println("Evens - " + Arrays.toString(OddsAndEvens.getAllEvens(x)));

And this is the corresponding section in the other file:

private static int[] cf = new int[20];
public static int countEm(int[] array, boolean odd)
{
    cf=array;
    return 0;
}
public static int[] getAllEvens(int[] array)
{
        int[]vegeta = new int[20];
        int VegetaScouterCount = 0;
        int[] XboxThreeYearOld = new int[20];
        for(int f : cf)
        {

            if(array[f]%2==0)
            {
                vegeta[VegetaScouterCount]=cf[f];
                VegetaScouterCount++;
                XboxThreeYearOld = Arrays.copyOfRange(vegeta, 0, VegetaScouterCount);
            }
            XboxThreeYearOld = Arrays.copyOfRange(vegeta, 0, VegetaScouterCount);
        }
        return XboxThreeYearOld;
}

(Ignore any informal language used)

The current output looks like:

Odds - []
Evens - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

The desired output should be:

Odds - []
Evens - [2, 4, 6, 8, 10, 12, 14]

I would really appreciate any pointers or hints in helping me resolve this issue.

Answer №1

The cf array needs to be initialized in Java to avoid default values being assigned, which results in each element having a value of zero.

In addition, using the uninitialized cf array (filled with zeros) to check for even numbers will always result in 0 % 2.

Furthermore, assigning elements from cf to vegeta, and subsequently copying it to

XboxThreeYearOld</code, will populate the returned array with zeroes.</p>

<p>To address this issue, consider the following code snippet:</p>

<pre><code>for (int i = 0; i < array.length; i++) {
    if (array[i] % 2 == 0) {
        vegeta[VegetaScouterCount] = array[i];
        VegetaScouterCount++;
        XboxThreeYearOld = Arrays.copyOfRange(vegeta, 0, VegetaScouterCount);
    }
    XboxThreeYearOld = Arrays.copyOfRange(vegeta, 0, VegetaScouterCount);
}

Answer №2

Here is a suggestion for your code:

for(int f : cf)
{
  if(array[f]%2==0)
  {

The above snippet accesses the value at index f of array and checks if it is even. Perhaps you meant to check if the number itself (f) is even.

for(int f : array)
{
  if(f%2==0)

To improve your code, consider implementing a method to count the number of even values in an array:

static int countEvens(int[] arr) {
    int count = 0;
    for (int i : arr) {
        if (i % 2 == 0) {
            count++;
        }
    }
    return count;
}

You can then use this method to separate the odds and evens:

static int[] getAllEvens(int[] array) {
    int[] evens = new int[countEvens(array)];
    int pos = 0;
    for (int f : array) {
        if (f % 2 == 0) {
            evens[pos++] = f;
        }
    }
    return evens;
}

And to get all the odd numbers:

static int[] getAllOdds(int[] array) {
    int[] odds = new int[array.length - countEvens(array)];
    int pos = 0;
    for (int f : array) {
        if (f % 2 != 0) {
            odds[pos++] = f;
        }
    }
    return odds;
}

Answer №3

If you don't actually need an array, using a dynamic collection like Sets or Lists might be more efficient. However, in the current structure, the for each loop is being used incorrectly.

The variable 'f' does not represent an index, but rather the value of 'cf' for each position. Since 'cf' has been initialized with a length of 20 and filled with zeros, it will always return 0.

Try using a traditional for loop like this:

for (int i=0; i<cf.length;i++){ // do work here }
and observe the output.

There could be other logical errors that the compiler may not detect since they are not related to syntax or data types.

Answer №4

  1. In order to display the odd and even numbers, make sure to first execute the countem() method.
  2. To resolve the issue, update
    vegeta[VegetaScouterCount]=cf[f];
    to
    vegeta[VegetaScouterCount]=array[f];
    . The problem arises from the fact that your array cf was initialized with a size of 20, but all its indexes default to 0 until explicitly changed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In JavaScript, you can update the class named "active" to become the active attribute for a link

My current menu uses superfish, but it lacks an active class to highlight the current page tab. To rectify this, I implemented the following JavaScript code. <script type="text/javascript"> var path = window.location.pathname.split('/'); p ...

What is the best way to access a cached value?

I am currently utilizing the node-cache-manager library to manage caching in my Node.js application. After successfully adding an item to the cache using the following code: import cacheManager from 'cache-manager'; const memoryCache = cacheMan ...

Angular's jQuery timepicker allows users to easily select a

Transitioning from jQuery to Angular, we previously utilized the for selecting times due to Firefox not supporting HTML5 input time. While searching for a similar timepicker plugin for Angular to maintain consistency with our past data and styles, I came ...

Swapping out the current div with the outcome from jQuery

I'm attempting to retrieve the most recent data for a div and replace it. The ajax query is fetching the entire HTML page, from which I am locating the right div. Now I want to update the current right div with the new content. $.ajax( { ...

Angular 2 System.config map leading to a 404 error message

I am encountering a 404 error in the browser console while attempting to map the Auth0 module from node_modules in my Angular 2 project using the system.config in the index file. Index File <!-- 2. Configure SystemJS --> <script> System.con ...

What is the process for deleting a token from local storage and displaying the logout page in Next JS?

I developed a Next.js web application and am looking to display a logout page when the token expires, while also removing the expired token from local storage. How can I ensure that this functionality works no matter which page the user visits within the a ...

"Encountering a strpos() issue while working with the Simple HTML DOM

Efficient HTML Parsing Comparison (1 min, 39s) <?php include('simple_html_dom.php'); $i = 0; $times_to_run = 100; set_time_limit(0); while ($i++ < $times_to_run) { // Find target image $url = "http://s ...

Using Java 8 Lambdas to Reset a Variable Conditionally Before Populating

Looking for a solution using lambdas in Java to populate a JSONArray based on a condition within the lambda. If condition x is met, I need to clear and reset the JSONArray, otherwise append values to it. However, due to the requirement of effectively fin ...

There was an unusual bug related to the sizeof() function that occurred while using DevC

Despite the fact that I am aware using Dev-C++ is not recommended, it is a requirement for my school assignments so I have no choice but to use it. Currently, we are studying pointers in C/C++ and I encountered a bug while trying to determine the length o ...

Can the hasClass() function be applied to querySelectorAll() in JavaScript?

As a beginner in javascript and jquery, I recently attempted to manipulate classes using the following code snippet: if ($(".head").hasClass("collapsed")) { $(".fas").addClass("fa-chevron-down"); $(".fas&qu ...

The settings in spring.jackson.properties seem to be overlooked by Jackson in my Spring Boot application

Jackson does not seem to be recognizing the property spring.jackson.property-naming-strategy=SNAKE_CASE. I am currently using version 1.4.2.RELEASE of Spring Boot. In my application.properties file, I have included: spring.jackson.property-naming-strate ...

Using Browserify to fetch external JSON data

I need some advice on the most effective method for retrieving external JSON data. Currently, I am using browserify and importing JSON data like this: const data = require('mydata.json'). However, I want to avoid having to recompile the browser ...

Select an item, then toggle classes on the other items to add or remove them

My code includes the following HTML elements: <ul> <li class="one"><a href="#">one</a></li> <li class="two"><a href="#">two</a></li> <li class="three"><a href="#">three</a>&l ...

Finding the Sum and Average of an Array

Currently tackling a challenging array problem as part of my college course. I am striving to calculate both the sum and average of an array. Below is the code I have managed to put together so far: public class Module55 { public static void main(Strin ...

Is there a way to extract subtitles from a javascript-controlled webpage using Python?

I am attempting to scrape information from this website: Link to Website Specifically, I am trying to extract the title ''Friday Night Lights'', but I am encountering difficulties accessing it due to JavaScript on the site. To achieve ...

Creating a custom theme for a tree panel in Ext JS 4

I'm looking to start customizing a Sencha 4 Tree panel, adjusting elements like text size and background colors. So far, I haven't been able to figure out the right approach, whether it's through viewConfig or some other method. Here's ...

Ways to invoke a function from the parent component that is delegated as a prop to the child component

const ParentComponent = () => { const [page, setPage] = useState(1); const handleSetPage = () => { setPage(2); }; return ( <div> {page === 1 && <ChildPage1Component handleSetPage={handleSetPage} /> } {p ...

Combining Django's CSRF token with AngularJS

I currently have Django running on an Apache server with mod_wsgi, and an AngularJS app being served directly by Apache rather than through Django. My goal is to make POST calls to the Django server that is utilizing rest_framework, but I am encountering d ...

using jquery to fill in fields in a table form

I am currently working with a basic html table that initially has two rows, each containing 2 form fields. Users have the ability to add more rows to the table by following this process: $('a#addRow').click(function() { $('#jTable tr:la ...

Creating a custom filter in an ng-repeat table using AngularJS

Utilizing a custom filter, I am able to filter values in a table based on a specific column. The data is sourced from an array of a multiple select input. For a complete example, please refer to: http://jsfiddle.net/d1sLj05t/1/ myApp.filter('filterM ...