2012-06-26 28 views
0

我想使用方法重載來查找矩形的區域。唯一的一點是用戶必須輸入值。但是如果它必須從用戶那裏接受,我們不應該知道他的輸入的數據類型嗎?如果我們這樣做,那麼重載的目的就變得毫無用處,因爲我已經知道數據類型。重載方法用戶輸入

你們能幫我嗎?

您可以添加到這個代碼:

import java.io.*; 
import java.lang.*; 
import java.util.*; 

class mtdovrld 
{ 
    void rect(int a,int b) 
    { 
     int result = a*b; 
     System.out.println(result); 
    } 

    void rect(double a,double b) 
    { 
     double result = a*b; 
     System.out.println(result); 
    } 
} 

class rectarea 
{ 
    public static void main(String[] args)throws IOException 
    { 
     mtdovrld zo = new mtdovrld(); 

     Scanner input= new Scanner(System.in); 

     System.out.println("Please enter values:"); 

     // Here is the problem, how can I accept values from user where I do not have to specify datatype and will still be accepted by method? 
     double a = input.nextDouble(); 
     double b = input.nextDouble(); 

     zo.rect(a,b); 

    } 
} 
+1

邊評論 - Java的修道院離子 - > CamelCase中的類名稱 – assylias

回答

0

所以,你想要做的是讓它所以輸入是一個字符串。

所以用戶可以輸入9或9.0,或者如果你想瘋了,也許是9。

然後您將解析字符串並將其轉換爲int或double。然後調用任一重載方法。

http://www.java2s.com/Code/Java/Language-Basics/Convertstringtoint.htm

,告訴您如何將字符串轉換成int

0

你可以用不同類型的參數,例如字符串,甚至一些對象超載。如果程序員使用你的矩形方法傳遞了錯誤的參數類型,那麼這將是一個預防措施,該方法不會中斷。

0

它更好地處理程序中的輸入檢查,而不是讓用戶煩擾它

如:

1. First let the user give values as String.

Scanner scan = new Scanner(System.in); 
    String val_1 = scan.nextLine(); 
    String val_2 = scan.nextLine(); 

2. Now Check the type using this custom method. Place this method in the class mtdovrld, Call this method after taking user input, and from here call the rect() method.

方法來驗證:

public void chkAndSet(String str1, String str2) 
    { 

     try{ 

      rect(Integer.parseInt(str1), Integer.parseInt(str2)); 


      } 
     catch(NumberFormatException ex) 
      { 

      rect(Double.parseDouble(str1), Double.parseDouble(str2)); 

      } 
    }