2015-05-10 144 views
0

當我運行代碼時,我得到提示輸入數字,然後輸入數字,但之後沒有任何反應!我試圖在這裏實現方法重載。任何幫助,將不勝感激。我的代碼出錯了?我試圖實現方法重載

import java.util.Scanner; 
public class MethodOverload { 
public static void main(String [] args){ 
    Scanner input = new Scanner(System.in); 
    Scanner inputDoub = new Scanner (System.in); 
    System.out.println ("Enter the int or double number"); 
    int x = input.nextInt(); 
    double y = inputDoub.nextDouble(); 
    //int x; 
    //double y; 
    System.out.printf("Square of integer value %d", x, "is", square(x)); 
    System.out.printf("Square of double value %f", y, "is", square(y)); 
     } 

    public static int square(int intValue){ 
     System.out.printf ("\nCalled square method with int argument: %d", intValue); 

     return intValue*intValue; 
    } 

    public static double square (double doubleValue){ 
     System.out.printf ("\nCalled sqauer method with double argument: %d", doubleValue); 
     return doubleValue*doubleValue; 
    } 

} 
+3

嘗試使用一個'掃描儀'。此外,請參閱[這個線程](http://stackoverflow.com/questions/2912817/how-to-use-scanner-to-accept-only-valid-int-as-input)的例子使用'掃描儀'輸入多個號碼。 –

回答

1
import java.util.Scanner; 
public class MethodOverload { 
public static void main(String [] args){ 
    Scanner input = new Scanner(System.in); 
    System.out.println ("Enter the int or double number"); 
    double y = input.nextDouble(); 

    if(y % 1 == 0) { 
     int x = (int) y; 
     System.out.printf("Square of integer value %d is %d", x, square(x)); 
    }else{ 
     System.out.printf("Square of double value %f is %f", y, square(y)); 
    } 

} 

public static int square(int intValue){ 
    System.out.printf ("\nCalled square method with int argument: %d", intValue); 

    return intValue*intValue; 
} 

public static double square (double doubleValue){ 
    System.out.printf ("\nCalled sqauer method with double argument: %f", doubleValue); 
    return doubleValue*doubleValue; 
} 

} 

如果我理解正確的話,你只是想獲得用戶的輸入,如果用戶進入雙用一個重載的方法,如果他進入整數用其他的。上面的代碼是這樣做的。

它只是將用戶輸入存儲爲double,如果用戶輸入模1 = 0(表示它是一個整數),則將其轉換爲整數並調用重載方法傳遞整數參數。另外,在上一次重載的方形方法中,您在printf函數中使用了%d而不是%f,如果要使用double,則使用%f。

您的前兩個printf語句也是錯誤的,語法只允許顯示一個字符串,其他參數用於替換所有的%符號。

+0

感謝兄弟..我很感激。我現在明白了。 – vib321

0

您嘗試使用%d進行格式設置不正確。 PFB需要更改:

public static double square (double doubleValue){ 
    System.out.printf ("\nCalled sqauer method with double argument: %f", doubleValue); 
    return doubleValue*doubleValue; 
} 

一個觀察:使用2個獨立的掃描器實例沒有意義。沒用。 修正你的代碼是這樣的:

Scanner input = new Scanner(System.in); 
//Scanner inputDoub = new Scanner (System.in); 
System.out.println ("Enter the int or double number"); 
int x = input.nextInt(); 
double y = input.nextDouble(); 
+0

@ vib321更改您的代碼並提供反饋。 – Rajesh

+0

我嘗試了你提到的整改,但它不起作用。同樣的事情發生在我上面提到的。但與其他提到的答案,它工作正常。我認爲通過使用if語句,它可以工作.. – vib321

+0

@ vib321當問題陳述不明確時,會發生這種情況。我只是試圖讓你的代碼工作。它以其他方式工作。我會說你應該去理查德建議的解決方案......如果這符合你的要求。 – Rajesh

相關問題