2014-08-28 93 views
-1

我想接受兩個輸入。如果兩個輸入都是整數然後添加它們。如果任何一個或兩個輸入都是字符串,則將它們連接起來。我想知道代碼來確定輸入是整數還是字符串? 感謝您的閱讀...如何確定輸入數據類型?

+2

針對您的技術正在嘗試?你到目前爲止嘗試過什麼? – 2014-08-28 05:38:41

+0

如果對於Java,嘗試解析爲整數,如果發生異常,那麼它的字符串其他整數 – Nabin 2014-08-28 05:39:49

+0

檢查我的答案爲Java,您可以使用方法重載相同。 – Rohit 2014-08-28 05:46:54

回答

2

您可以使用方法重載此, 退房Java代碼如下

public class MethodExample 
{ 
    public static void main (String[] args) 
    { 
     int a,b; 
     String string1,string2; 
     //accept values for all variables...;>> 
     System.Out.Println("Addtion is "+sum(a,b)); 
     System.Out.Println("Contact is "+sum(string1,string2)); 
    } 

    int sum(int a,int b) 
    { 
     return(a+b); 
    } 

    String sum(string a,string b) 
    { 
     return(a+b); 
    } 
} 
0

我已經使用了以下邏輯給出:

 Console.WriteLine("Enter two inputs:"); 
     string s1 = Console.ReadLine(); 
     string s2 = Console.ReadLine(); 
     double num; 
     int s3; 
     string s4; 

     bool isNum1 = double.TryParse(s1, out num); 
     bool isNum2 = double.TryParse(s2, out num); 
     if(isNum1==true && isNum2==true) 
     { 
      s3 = Convert.ToInt32(s1) + Convert.ToInt32(s2); 
      Console.WriteLine("Output = {0}", s3); 
     } 
     else 
     { 
      s4 = s1 + s2; 
      Console.WriteLine("Output = {0}",s4); 
     }