2017-03-27 54 views
-3

我正在用兩種不同的數據類型實現方法重載。這就是我以代碼結束的過程。 但現在它找不到符號c和d。任何幫助?如何在函數調用中修復'找不到符號'?

import java.util.*; 
import java.lang.*; 
public class LargestOfTwoTest{ 
    public static void main(String args[]) throws Exception{ 
     Scanner scan = new Scanner(System.in); 



     System.out.println("Enter two numbers, and I wiil show you which one's largest!\n"); 
     System.out.println("Enter two numbers: "); 
     double a = scan.nextDouble(); 
     double b = scan.nextDouble(); 

     if (a==(Math.floor(a))){ 
      int c = (int) a; 
     } 
     else{ 
      double c = a; 
     } 

     if (b==(Math.floor(b))){ 
      int d = (int) b; 
     } 
     else { 
      double d = b; 
     } 

     System.out.print("Largest of the numbers is "+largest(c,d)); 
    } 




    public static int largest(int x, int y){ 
     if (x>y) 
      return x; 
      //System.out.print("Largest of the numbers is "+x); 
     else 
      return y; 
      //System.out.print("Largest of the numbers is "+y); 
    } 
    public static double largest(double x, double y){ 
     if (x>y) 
      return x; 
      //System.out.print("Largest of the numbers is "+x); 
     else 
      return y; 
      //System.out.print("Largest of the numbers is "+y); 
    } 
} 

顯示在此行

System.out.print("Largest of the numbers is "+largest(c,d)); 

誤差..

LargestOfTwoTest.java:29:錯誤:找不到符號

(c和d)

+5

您已聲明'c'和'd'超出了您的invo範圍'最大'的陽離子,這與超載無關。 – Mena

+0

在單個作用域中,只能有一個變量聲明。通過將聲明放入'if'來創建不同的聲明的嘗試將不起作用,因爲'if'塊是單獨的作用域,並且只要該塊完成,聲明就會超出範圍。 – RealSkeptic

+0

您應該將您的標題改爲特定問題,否則您將繼續陷入低調。只是一個友好的領導。 – samosaris

回答

0
import java.math.BigDecimal; 
import java.util.Scanner; 

public class LargestOfTwo { 

    private Scanner scanner; 
    private Number a; 
    private Number b; 

    public static void main(String args[]) throws Exception { 
     LargestOfTwo app = new LargestOfTwo(); 
     app.start(); 
    } 

    private void start() { 
     readInputs(); 
     Number largest = compare(a, b); 
     System.out.print("Largest of the numbers is: " + largest); 
    } 

    private void readInputs() { 
     scanner = new Scanner(System.in); 
     System.out.println("Enter two numbers, and I will show you which one is largest\n"); 
     a = readInput(); 
     b = readInput(); 
    } 

    private Number readInput() { 
     Double d = scanner.nextDouble(); 
     if (d == Math.floor(d)) { 
      return d.intValue(); 
     } else { 
      return d; 
     } 
    } 

    private Number compare(Number x, Number y) { 
     if (new BigDecimal(x.floatValue()).compareTo(new BigDecimal(y.floatValue())) > 0) { 
      return x; 
     } else { 
      return y; 
     } 
    } 
} 
+0

omg,感謝這, 我無法運行程序,但仍然取得進展,謝謝.. – JoeTinnySpace

+0

http://imgur.com/a/lP9is現在這是問題,因爲我無法弄清楚爲什麼,我將這個提交給我的任務,這個邏輯很強大。 :) – JoeTinnySpace

+0

看起來你的代碼中缺少一個右大括號 –