2012-06-26 5 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

사이드 주석 - 자바 수도원 이온 -> CamelCase의 클래스 이름 – assylias

답변

0

그래서 당신이 원하는 것은 그렇게 입력이 문자열인지 확인합니다.

그래서 사용자는 9 또는 9.0을 입력 할 수 있습니다. 아니면 9 명이 미치고 싶을 수도 있습니다.

그러면 문자열을 파싱하여 int 또는 double로 캐스팅합니다. 오버로드 된 메서드 중 하나를 호출하십시오. 어떻게 당신은 예를 들어, 문자열, 또는 어떤 객체에 대한 다른 유형의 매개 변수를 오버로드 할 수있는 int

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

      } 
    }