【问题标题】:overloading method user input重载方法用户输入
【发布时间】:2012-06-28 00:36:07
【问题描述】:

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

你们能帮帮我吗?

您可以在此代码中添加:

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 约定 -> CamelCase 中的类名

标签: java input overloading


【解决方案1】:

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

所以用户可以输入 9 或 9.0,或者如果你想疯狂,可以输入 9。

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      最好在程序中处理输入的检查,而不是让用户为之烦恼

      例如:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-08
        • 2010-09-30
        • 1970-01-01
        • 1970-01-01
        • 2015-02-18
        相关资源
        最近更新 更多