重载方法用户输入

问题描述 投票:0回答:3

我正在尝试使用方法重载来查找矩形的面积。唯一的问题是这些值必须由用户输入。但是如果它必须从用户那里接受,我们不应该知道他输入的数据类型吗?如果我们这样做,那么重载的目的就变得毫无用处,因为我已经知道数据类型了。

你们能帮帮我吗?

您可以添加此代码:

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

   }
}
java input overloading
3个回答
0
投票

所以你要做的就是让输入是一个字符串。

因此用户可以输入 9 或 9.0,或者如果你想疯狂的话也可以输入 9。

然后您将解析该字符串并将其转换为 int 或 double。然后调用任一重载方法。

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

向您展示如何将字符串转换为 int


0
投票

您可以重载不同类型的参数,例如 String,甚至某些对象。这是一种预防措施,以防程序员使用矩形方法传递了错误的参数类型,该方法不会中断。


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

          }
    }
© www.soinside.com 2019 - 2024. All rights reserved.