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

   }
}
4

3 に答える 3

0

したがって、入力が文字列になるようにする必要があります。

したがって、ユーザーは 9 または 9.0 を入力できます。または、夢中になりたい場合は 9 を入力できます。

次に、文字列を解析して int または double にキャストします。次に、オーバーロードされたメソッドのいずれかを呼び出します。

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

文字列を int に変換する方法を示します

于 2012-06-26T16:22:41.747 に答える
0

String や一部のオブジェクトなど、さまざまな型パラメーターでオーバーロードできます。これは、矩形メソッドを使用しているプログラマーが間違ったパラメーター タイプを渡した場合の予防策であり、メソッドは壊れません。

于 2012-06-26T16:23:18.267 に答える
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));

          }
    }
于 2012-06-26T16:37:50.370 に答える