-5

Just a declaimer:i am a beginner in java.

Write a method named numUnique that takes three integers as parameters and that returns the number of unique integers among the three. For example, the call numUnique(18, 3, 4) should return 3 because the parameters have 3 different values. By contrast, the call numUnique(6, 7, 6) would return 2 because there are only 2 unique numbers among the three parameters: 6 and 7.

public int numUnique(int x,int y,int z){
    if(x==y||y==z){
    }
    return 1;

    else if(x!=y||y!=z){

    }
    return 2;
    
}

I am very confused about the relationship of if and return.I always put return inside if statement.But i dont understand why does it generate me an error message.if something is fulfil,i return in the loop.Why is it wrong.But on the other hand,the println statement can be put inside for loops.

Another issue,because this question,i tried to attempt using if else too.But my first condition is if and i return it.So after that i placed else if after the first return,it gives me error again.

I will appreciate someone will explain to me and i will alter the codes on my own.Please dont give me the full codes.Thank you.

Edited* By the way,i read through all the comments and i finally understand it.This is my codes that i work out on my own(:

public static int numUnique(int x, int y, int z) {
    if(x==y && y==z){
        return 1;
    }else if(x==y && y!=z || y==z && z!=x ||  x==z && y!=z ){
        return 2;
    }
    return 3;
}
4

9 に答える 9

2

return ステートメントは、中括弧内に配置する必要があります。

于 2013-04-18T12:40:17.650 に答える
2

「return」ステートメントを明確に理解するために、コードの 1 つのブロック、つまり {...} に return ステートメントは 1 つしか存在できないと言います。

「return」ステートメントは呼び出し元に戻るために使用され、ブロックの最後のステートメントである必要があります。

あなたが示唆したように、私は完全なコードを提供するのではなく、「return」ステートメントの使用法を認識させます。

コードでは、1 つのブロックに 2 つの「return」ステートメントを記述しています。

于 2013-04-18T12:59:13.317 に答える
0

コードの形式が正しくありません:

また、if-else ステートメントは次のとおりです。

if { code }
else { code }

だから、ifそしてelseブロックはペアを作ります。しかし、あなたは持っています:

if (condition) { code }
code
else { code }
code

そのためcode、単語のすぐ上がelseこのペアを分割し、else孤立したままになるため、プログラムは構文的に正しくありません。

あなたは「やりたい」:

if (x==y || y == z) {
   return 1;
}
else if (x != y || y != z) {
   return 2;
}

さらに、if(またはelse) ブロックに 1 行しかない場合は、括弧を消去できます。

if (x==y || y == z)
   return 1;
else if (x != y || y != z)
   return 2;

さらに、アルゴリズムは問題の解決策ではありません.3つの一意の値はどうですか?. より多くの状況をチェックする必要があります (すべて異なる、すべて等しい、または 1 つだけ異なる)。

于 2013-04-18T13:17:39.570 に答える
0

まず、返品はステートメントの外側にあり、ifステートメントの内側にある必要があります。あなたが書くなら:

if(Something) {

}
return 1;

ifyourが空であるため、常に 1 が返されます。あなたreturn 1だけがしたい場合は、本文if(Something)の中に書きます:if

if(Something) {
    return 1;
}

第二に、あなたの論理は良くありません。以下を確認する必要があります。

  • x == y == z の場合、それらはすべて等しいです。
  • x == y かつ x != z の場合、2 を返す必要があります。
  • x != y != z の場合、0 を返す必要があります。
  • ....

すべての状況をカバーする必要があります。

于 2013-04-18T12:44:40.263 に答える