确定重载方法的输入

发布于 2024-11-16 20:31:13 字数 403 浏览 6 评论 0原文

我在确定用户输入是 int 还是 double 时遇到了一些问题。

这是一个示例:

public static int Square(int x)
{
    return x*x;
}

public static double Square(double x)
{
    return x*x;
}

我需要弄清楚如何根据扫描仪确定上述方法的输入是 int 还是 double。然而,由于这是我的第一堂编程课,因此我不允许使用任何未教授过的内容 - 在本例中,这是基础知识。

无论如何,是否有可能将输入作为字符串并检查是否存在“。”涉及然后将其存储到 int 或 double 中?

最后,我不是要求你编写程序,而是帮助我想出一种解决方案。如有任何帮助,我们将不胜感激:)

I'm running into a bit of an issue with determining if the user input is an int or double.

Here's a sample:

public static int Square(int x)
{
    return x*x;
}

public static double Square(double x)
{
    return x*x;
}

I need to figure out how to determine based on the Scanner if the input is a int or double for the above methods. However since this is my first programming class, I'm not allowed to use anything that hasn't been taught - which in this case, has been the basics.

Is there anyway of possibly taking the input as a String and checking to see if there is a '.' involved and then storing that into an int or double?

Lastly, I'm not asking for you to program it out, but rather help me think of a way of getting a solution. Any help is appreciated :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

短暂陪伴 2024-11-23 20:31:13

扫描器有很多方法,例如 hasNextInthasNextDouble 等,它们告诉您是否可以解释“扫描器读取的下一个令牌”作为(无论如何)”。

The Scanner has a bunch of methods like hasNextInt, hasNextDouble, etc. which tell you whether the "next token read by the Scanner can be interpreted as a (whatever)".

情绪 2024-11-23 20:31:13

既然您提到您已经了解了扫描仪 对象,我假设该类的方法可供您使用。在这种情况下,您可以检测输入是否是整数、双精度数,或者只是获取整行。您在这里最感兴趣的方法是 hasNextDouble() 方法(返回一个 boolean 指示当前令牌是否在 Scanner实际上是 double 或不是)和 nextDouble() 方法(如果 Scanner 中的下一个标记实际上是 double,从扫描仪作为一个)。这可能是从文件或标准输入确定输入类型的最佳方向。

另一种选择是使用包装类静态方法来转换值。它们通常命名为 Integer.parseInt(str) 或 Double.parseDouble(str) ,它们会将给定的 String 对象转换为适当的基本对象类型。请参阅 Double 类方法 passrseDouble(String s) 了解更多详细信息。它可以这样使用:

String value = "123.45"
double convertedValue = 0.0;

try {
    convertedValue = Double.parseDouble(value);
} catch (NuberFormatException nfe) {
    System.err.println("Not a double");
}

此方法可能最适合应用程序中已经存在且需要验证的值(在一个小的 String 上构造一个 Scanner 有点过分了) 为此目的)。

最后,另一种可能的方法(但不是非常干净、简单或可能正确的技术)可以直接查看 String 对象并尝试查找它是否包含小数点或其他指示符实际上是一个double。您也许可以使用 indexOf(String substr) 来确定它是否出现在 String 中。我怀疑这个方法有很多潜在的问题(例如,如果 String 有多个“.”字符怎么办?)。我不会建议这条路线,因为它很容易出错并且很难遵循。然而,如果这就是限制的话,这可能是一个选择。

因此,恕我直言,您的选择应该如下:

  1. 使用 Scanner 方法 hasNextDouble()nextDouble()
  2. 使用包装类方法 Double.parseDouble(String s)
  3. 使用 String 方法尝试识别该值(如果上述任一选项可用,请不惜一切代价避免此技术)。

Since you mentioned you've learned about the Scanner object, I assume the methods of that class are available to you for your use. In this case, you can detect if an input is an integer, double, or just obtain an entire line. The methods you would most be interested here would be the hasNextDouble() method (returns a boolean indicating whether or not the current token in the Scanner is actually a double or not) and the nextDouble() method (if the next token in the Scanner is in fact a double, parse it from the Scanner as one). This is probably the best direction for determining input types from a file or standard input.

Another option is to use the wrapper classes static methods for converting values. These are generally named like Integer.parseInt(str) or Double.parseDouble(str) which will convert a given String object into the appropriate basic type. See the Double classes method pasrseDouble(String s) for more details. It could be used in this way:

String value = "123.45"
double convertedValue = 0.0;

try {
    convertedValue = Double.parseDouble(value);
} catch (NuberFormatException nfe) {
    System.err.println("Not a double");
}

This method is probably best used for values that exist within the application already and need to be verified (it would be overkill to construct a Scanner on one small String for this purpose).

Finally, yet another potential (but not very clean, straightforward, or probably correct technique) could be looking at the String object directly and trying to find if it contains a decimal point, or other indicators that it is in fact a double. You may be able to use indexOf(String substr) to determine if it appears in the String ever. I suspect this method has a lot of potential problems though (say for example, what if the String has multiple '.' characters?). I wouldn't suggest this route because it is error prone and hard to follow. It might be an option if that's what the constraints are, however.

So, IMHO, your options should go as follow:

  1. Use the Scanner methods hasNextDouble() and nextDouble()
  2. Use the wrapper class methods Double.parseDouble(String s)
  3. Use String methods to try and identify the value (avoid this technique at all costs if either of the above options are available).
ま昔日黯然 2024-11-23 20:31:13

由于您认为您不会被允许使用扫描仪方法,因此您可以尝试多种替代方法。您提到检查字符串是否包含 .。为此,您可以使用 String 上的 contains 方法。

"Some words".contains("or") // evaluates to true

这种方法的问题在于,有许多字符串包含 . 但不是浮点数。例如,句子、URL 和 IP 地址。然而,我怀疑你的讲师是否试图让你出局,并且可能只会给你整数和双打。

所以你可以尝试铸造。将 double 转换为 int 会导致数字的小数部分被丢弃。

double doubleValue = 2.7;

int castedDoubleValue = (int) doubleValue; // evaluates to 2

double integerValue = 3.0;

int castedIntegerValue = (int) integerValue; // evaluates to 3

希望这足以让您开始编写问题的解决方案。

Since you think you won't be allowed to use the Scanner methods there are a number of alternatives you try. You mentioned checking to see if a String contains a .. To do this you could use the contains method on String.

"Some words".contains("or") // evaluates to true

The problem with this approach is that there are many Strings that contain . but aren't floating point numbers. For examples, sentences, URLs and IP addresses. However, I doubt you're lecturer is trying to catch you out with and will probably just be giving you ints and doubles.

So instead you could try casting. Casting a double to an int results in the decimal portion of the number being discarded.

double doubleValue = 2.7;

int castedDoubleValue = (int) doubleValue; // evaluates to 2

double integerValue = 3.0;

int castedIntegerValue = (int) integerValue; // evaluates to 3

Hopefully, that should be enough to get you started on writing a solution to the problem.

无名指的心愿 2024-11-23 20:31:13

可以这样检查

            if(scanner.hasNextDouble()}
            {
               System.out.println("Is double");
            }


            if(scanner.hasNextDouble()}
            {
              System.out.println("Is double");
            }

Can be checked like this

            if(scanner.hasNextDouble()}
            {
               System.out.println("Is double");
            }


            if(scanner.hasNextDouble()}
            {
              System.out.println("Is double");
            }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文