2017-03-02 11 views
0

最大3つの整数を取得する必要がありますが、2番目の数値が0より小さい場合は、コードから出力されません。Javaで最大数を取得

package main; 

import java.util.Scanner; 

public class Max { 
    public static void main(String[] args) { 
    Scanner in=new Scanner(System.in); 
    int a=in.nextInt(); 
    int b=in.nextInt(); 
    int c=in.nextInt(); 
    int max; 
    if(a>b){ 
     if(a>c)max =a; 
     else max =c; 
     } 
    else{ 
     if(b>c)max=b; 
     else max=c; 
    System.out.println(max); 
     } 
    } 
} 

これは他の状況のテストに合格しました。なぜそれが起こったのか教えていただけますか?

+1

は 'List'に値を格納してください多くのクリーナーです。次にCollections.max()を使って最大値を取得します。 –

+0

System.out.printlnをelseの外部に移動する必要があります。 –

+0

皆さんありがとうございます...私の間違いは何ですか? – kkkjjj

答えて

2

あなたのprintステートメントはelseブロックの内側にあるので、elseブランチに行くと実行されます。 elseブロックの外側に移動します。あなたのint型の値を格納するList

... 
else { 
    if(b>c) 
     max=b; 
    else 
     max=c; 
} 
System.out.println(max); 
-1

番号を3つの別々の変数の代わりに配列に入力します。この方法を使用することができます:

public int getLargest(int[] nums){ 
    int largest = Integer.MIN_VALUE; 
    if(nums.length == 0) 
     return -1; 
    for(int i : nums){ 
     if(i > largest) 
      largest = i; 
    } 
    return largest; 
} 
+0

これは、長さ0の配列に対して 'Integer.MIN_VALUE'を返します。 – byxor

+0

固定されていますが、大部分の人が空の配列を送信しないと仮定しています。 – Ryan

+0

私は、例外を返さずに配列内に存在します。私はあなたを野生のガチョウの追跡に導かないでしょう。 – byxor

2

あなたのprintlnステートメントがあるからです。その2番目の条件では、if文の外側にしたいと思っています。

public class Max { 
    public static void main(String[] args) { 
    Scanner in=new Scanner(System.in); 
    int a=in.nextInt(); 
    int b=in.nextInt(); 
    int c=in.nextInt(); 
    int max; 
    if(a>b){ 
     if(a>c)max =a; 
     else max =c; 
    } 
    else{ 
     if(b>c)max=b; 
     else max=c; 
     } 
    } 
    System.out.println(max); 
} 
0

使用Collections.max()

package main; 

import java.util.Scanner; 

public class Max { 
    public static void main(String[] args) { 
    List<Integer> list = new ArrayList<>(); 
    Scanner in = new Scanner(System.in); 
    int a= in.nextInt(); 
    list.add(a); 
    int b= in.nextInt(); 
    list.add(b); 
    int c= in.nextInt(); 
    list.add(c); 
    System.out.println("Largest: " + Collections.max(list)); 
    } 
} 
0

私は、コードを別の方法に

public int max(int a, int b) { 
    return Math.max(a, b); 
} 

を書い示唆して

max(a, max(b, c)); 

ようにそれを呼び出すには、このよう

関連する問題