为什么相同的逻辑在Java中失败并显示索引错误,而在JavaScript中却不会?

huangapple go评论87阅读模式
英文:

Why does same logic fail and show index error in Java but not JavaScript?

问题

以下是您的Java代码的翻译部分:

class Solution {
    public int maxProfit(int[] prices) { 
        int profit = 0;
        int i = 0;
        int len = prices.length;
        while(i < len){
            int go = i + 1;
            while(prices[go] > prices[go-1]){
                go++;
            }
            profit += Math.abs(prices[i] - prices[go-1]);
            i = go;
        }
        return profit;
    }
}

这是您的JavaScript函数的翻译部分:

var maxProfit = function(prices) { 
    let profit = 0;
    let i = 0;
    let len = prices.length;
    while(i < len){
        let go = i + 1;
        while(prices[go] > prices[go-1]){
            go++;
        }
        profit += Math.abs(prices[i] - prices[go-1]);
        i = go;
    }
    return profit;
};

请注意,这些代码已经被翻译成中文,不包含其他内容。

英文:

Here's my Java code:

class Solution {
    public int maxProfit(int[] prices) { 
        int profit = 0;
        int i = 0;
        int len = prices.length;
        while(i &lt; len){
            int go = i + 1;
            while(prices &gt; prices[go-1]){
                go++;
            }
            profit += Math.abs(prices[i] - prices[go-1]);
            i = go;
        }
        return profit;
    }
}

I wrote a function in JS with the same logic and it worked fine, but running the above Java code with input

[2,3,4,6,3,9]

gives me the error "java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6"

Why?

P.S. My JavaScript function is:

var maxProfit = function(prices) { 
    let profit = 0;
    let i = 0;
    let len = prices.length;
    while(i &lt; len){
        let go = i+1
        while(prices &gt; prices[go-1]){
            go++;
        }
        profit += Math.abs(prices[i] - prices[go-1])
        i = go
    }
    return profit;
};

答案1

得分: 2

将您的Java条件更改为

while (go < len && prices > prices)

以防止调用未定义的索引。

英文:

Change your Java conditional to

while(go &lt; len &amp;&amp; prices &gt; prices)

to prevent an undefined index from being called

答案2

得分: 1

JavaScript的工作方式如下:
假设我们有一个长度为N的数组,那么当X>=N且0<=Y<N时,arr[X]>arr[Y]会返回false,而不是索引越界异常。
在这里,arr[X]返回undefined,因此它将是undefined>arr[Y]。
因此,它打破了循环,你得到了正确的输出。

英文:

Javascript works in the following way:
Say, lets have an array of length N, then
arr[X]>arr[Y] where X>=N and 0<=Y<N returns false instead of indexoutofbound exception.
Here arr[X] returns undefined so it will be undefined > arr[Y].
So its breaking the loop and you are getting the output correct.

答案3

得分: 1

这部分代码中出现了越界错误:

int len = prices.length;
while(i < len){
    int go = i + 1;
    while(prices > prices[go-1]){
        go++;
    }

举个例子,如果prices数组有四个元素,那么len就是4,但在越界之前可以使用的最大索引是3(因为数组从零开始索引)。你在代码中使用了i作为索引,这没问题,因为根据你的循环逻辑,i始终会小于len

然而,当你有int go = i + 1,然后使用prices时,某个点上i会成为数组的最大索引,而go会超过最大索引,从而引发越界错误。

那么,为什么JavaScript不会抛出相同的错误,而你的代码似乎可以正常运行呢?

JavaScript在数组中的越界索引不会抛出错误,而是prices将被解释为undefined。然后,(undefined > prices)将会评估为false,从而停止while循环,继续执行。

如果你希望你的Java代码片段与JavaScript代码类似,你可以将while循环的条件改为while(go < len && prices > prices)

英文:

This part of your code is where the out of bounds error is coming from:

int len = prices.length;
while(i &lt; len){
    int go = i + 1;
    while(prices &gt; prices[go-1]){
        go++;
    }

As an example, if the prices array had four elements in it, len will be 4, but the maximum index you could use before getting out of bounds would be 3 (because the array is zero-indexed). You end up indexing prices with i, which is fine because according to your while loop logic, i will always be less than len.

However, when you have int go = i + 1 and then prices, at some point i will be the maximum index of the array and go will be beyond that, throwing the out of bounds error.

So, why does JavaScript not throw the same error, and your code seemingly works?

JavaScript won't throw an error for an out of bounds index in an array, instead prices will evaluate to undefined. (undefined &gt; prices) will then evaluate to false, stopping your while loop, and execution continues.

If you would like your Java snippet to work the same as the JavaScript one, you could change your while loop condition to while(go &lt; len &amp;&amp; prices &gt; prices).

huangapple
  • 本文由 发表于 2020年7月23日 11:11:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63046286.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定