2017-03-02 35 views
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,使其位於其他位置之外。 –

+0

感謝你們所有人......我知道我的錯誤是什麼。 – kkkjjj

回答

2

您的打印語句位於else塊內部,因此只有在它轉到else分支時纔會執行。將它移動到else塊的外部。

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

將數字輸入到數組而不是三個單獨的變量。那麼你可以使用這種方法:

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語句。它在第二個條件中,你希望它在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()List存儲您的INT值。

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)); 

的代碼很多這樣清潔