A step-by-step guide to incorporating the maximum array function in Java

I need to create a similar function in JAVA, but I'm struggling to understand the role of -Infinity in JAVA and how it can be utilized.

Here is the code snippet in JS:

function arrayMax(arr) {
 var len = arr.length, 
 max = -Infinity;
 var rangomax=99999;
 while (len--) {
  if ((Number(arr[len]) > max)&&(Number(arr[len])<rangomax)) {
   max = Number(arr[len]);
  }
 }
 return max;
}

Answer №1

Give this a shot:

public double findLargestNumberInArray(double[] numbers){
    int length = numbers.length;
    double maxNumber = Double.NEGATIVE_INFINITY;
    double rangeMax = 99999;
    while(length--){
        if ((numbers[length] > maxNumber) && (numbers[length] < rangeMax)) {
             maxNumber = numbers[length];
        }
    }
    return maxNumber;
}

Answer №2

To achieve Java code that closely resembles JavaScript code, disregarding undefined and null values, it is best to assume that the input is an Object[], as indicated by the numerous Number() calls.

public static double arrayMax(Object... arr) {
    double rangomax = 99999;
    double max = Double.NEGATIVE_INFINITY;
    for (Object obj : arr) {
        double value = number(obj);
        if (value > max && value < rangomax) {
            max = value;
        }
    }
    return max;
}
// Function similar to JavaScript's Number()
private static double number(Object obj) {
    if (obj instanceof Number) {
        return ((Number) obj).doubleValue();
    }
    try {
        return Double.parseDouble(obj.toString());
    } catch (NumberFormatException e) {
        return Double.NaN;
    }
}

You may also consider creating overloads for primitive values, such as:

public static double arrayMax(double... arr) {
    double rangomax = 99999;
    double max = Double.NEGATIVE_INFINITY;
    for (double value : arr) {
        if (value > max && value < rangomax) {
            max = value;
        }
    }
    return max;
}

Answer №3

An easy method to determine the highest value in an array:

public Double findMaxValue(int[] values) { 

    double maxValue = Double.MIN_VALUE; 

    for (int index = 0; index < values.length; index++){ 

        if (values[index] > maxValue) { 

            maxValue = values[index];

        } 

    } 

    return maxValue; 

}

Answer №4

One suggested solution is to utilize Integer.MIN_VALUE to find the maximum value in an array. However, there are alternative methods that do not rely on Integer.MIN_VALUE.

  public int max(int[] arr){
    if(arr == null || arr.length == 0) {
      return 0; // Handle empty or null arrays by returning a default value
    }
    int max = arr[0];
    for(int num: arr){
      if(num >= max){
        max = num;
      }
    }
    return max;
  }

Note: This method can also be applied to double[] arrays.

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

Initiate a CSS animation only when a different animation has completed

I am trying to create a sequence of animations using 2 squares. I want the animation for the red square to start only after the blue square's animation is complete. How can I achieve this cycle of animations? .box { width: 100px; height: 1 ...

Guidelines for utilizing regex to match this specific string

Hey guys, I need help with parsing this string (a url). example.html/#playYouTubeVideo=id[lBs8jPDPveg]&width[160]&height[90] I'm trying to extract the values for id, width, and height within brackets. This is what I've come up with: [ ...

Having trouble passing data between view controllers

In my AngularJS application, I have a table column in main.html that is clickable. When clicked, it should redirect to a new customer page with the value of the column cell as the customer's name. There is a corresponding service defined for the app m ...

An unknown property exception was thrown due to the field name being unrecognized: "Symbol"

Seeking assistance with parsing JSON data from AlphaVantage using Jackson and Ebeans. { "Symbol": "IBM", "AssetType": "Common Stock", "Name": "International Business Machines Corporation", ... more details } Below is the code snippet I am usin ...

Creating a two-dimensional array in PHP through an SQL query

I am currently trying to create a multi-dimensional array in PHP using SQL query results. My goal is to push this data into a CSV file later on, with each line representing a member's "name" and "surname." This is what I have attempted so far: $ta ...

Caution: Ensure that you call JAWT_GetAWT only after the JVM has been loaded

Encountered an error while trying to run a Java project in IntelliJ: JavaVM WARNING: JAWT_GetAWT must be called after loading a JVM AWT not found Running on Mac OS 10.11 with jdk 1.8 Seeking solutions for this issue. Some sources suggest it may be relat ...

Determine if the webpage is the sole tab open in the current window

How can I determine if the current web page tab is the only one open in the window? Despite searching on Google for about 20 minutes, I couldn't find any relevant information. I would like to achieve this without relying on add-ons or plugins, but if ...

The requested resource was not found during the mapping process

Setting up Hibernate 5 with MySQL server AccountMap account = new AccountMap(); Configuration configuration = new Configuration(); configuration.addClass(AccountMap.class); configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Dr ...

Learn how to implement JavaScript code that allows a video to start playing only upon clicking a specific button

Within the confines of a div lies a <video autoplay> <source src='myvid'> </video>. This div initially has a display ='none' setting in its CSS. Upon receiving a click event, the display property changes from none to b ...

Why You Can Only Use elementByCssSelector Once on TheIntern.io/Selenium

I'm encountering a peculiar problem while running a functional test with Selenium (using the Intern.io framework) where only the first element is being recognized; any subsequent element I try to access throws an error: Error: Error response status: ...

When the React.js app is launched on the server, it appears as a blank page, but functions perfectly when accessed locally

When I launch my React.js frontend locally with npm start, it runs smoothly. However, when attempting to run it on the server by using npm install followed by nom start, a blank page appears. Upon inspecting the public folder, I found the following conten ...

Guide to importing a JavaScript file into a different JavaScript file

I encountered an issue while trying to import a JavaScript file into my server-side JavaScript file. The function I need to run cannot be executed on the server side. Is there a method to successfully import my source code to the server-side JavaScript fil ...

AngularJS and Select2's Multiple - Tags feature can display tags intermittently, showing some and hiding others as needed

Currently, I am implementing AngularJS along with select2 (not using ui-select). In my view, the following code is present: <select name="rubros" id="rubros" class="select2 form-control" ng-model="vm.comercio.tags" ng-options="rubro.nombre for rub ...

What is preventing me from creating accurate drawings on canvas?

I'm currently working on a paint application and facing an issue. When I place the painting board on the left side of the screen, everything works fine and I can draw without any problems. However, when I move it to the right side of the screen, the m ...

Inconsistency in the invocation of PageMethod within AJAX script manager

My AJAX call to a method in the code-behind seems to be unreliable even though I have everything set up correctly. The JavaScript function utilizes PageMethods to invoke the method in the code-behind. While most of the time it works fine, occasionally it ...

Utilizing diverse values retrieved from HTML data attributes

*UPDATE Within my HTML, I have a list titled "#wordlist" that contains the words for my game, along with corresponding audio and images for each word. Everything is functioning correctly. As there will be multiple versions of the game, I've been tas ...

Finding the total number of nested div elements within parent divs

Can someone help me with getting the count of specific divs on my page? Below is a visual representation of the structure. My goal is to count the cityUnderText divs. I've tried using the following scripts, but I'm consistently receiving a resul ...

Understanding the concept of passing values in JavaExplanation of pass-by-value

I'm puzzled by the fact that the code snippet below fails to update the data of Node a: public class Node{Node next; int data;} public static void change(Node a) { a = a.next; } public static void main(String [] args){ Node a = new Node(); Node b = ...

Not able to confirm the availability of the internet connection

Currently, I am developing an Android application that includes a web-view feature. One issue I am encountering is determining whether there is an active Internet connection before displaying the default message. I have referred to these resources Link1 ...

Serialization of Avro Enumerations

How can a Java enum be serialized in Avro? For example, consider this enum: enum Color { WHITE, RED, GREEN } When defining the Avro schema: { "type": "enum", "name": "Color", "symbols" : ["WHITE", "RED", "GREEN"] } Which interface should the ...