简体   繁体   English

确定变量是浮点数还是 java 中的 integer

[英]Determine if a variable is a float or an integer in java

I need to write a program which uses multiple methods called average which return the average of those values, if both are ints the value returned should be an int, and if one or more is a floating point number, the value should be returned as a double.我需要编写一个程序,它使用多个称为平均的方法返回这些值的平均值,如果两者都是整数,则返回的值应该是一个整数,如果一个或多个是浮点数,则该值应该作为一个返回双倍的。 I keep running into errors with the following code:我不断遇到以下代码错误:

class Main
{
  class Unbruh{
  static int average(int x, int y)
  {
    return ((x + y) / 2);
  }
  static double average(double x, double y)
  {
    return ((x + y) / 2);
  }
}
  class Bruh
  {
  public static void main (String[] args)
  {

    System.out.println ("Enter number");
    Scanner input = new Scanner (System.in);
    float x = input.nextFloat ();
    float y = input.nextFloat ();
    System.out.println(Unbruh.average(x,y));
System.out.println(Unbruh.average(x,y));

    Unbruh a = new Unbruh ();
    a.average (x, y);
 // System.out.println (average (x, y));
 
  }

}
}

Is something wrong with the logic here, or is there just formatting errors?这里的逻辑有问题,还是只是格式错误?

The method main cannot be declared static;方法main不能声明static; static methods can only be declared in a static or top level type. static 方法只能在 static 或顶级类型中声明。

That comes from declaring a static method inside a class that is inside another class.这来自于在另一个 class 中的 class 中声明 static 方法。 That other class is not considered a top level class.其他 class 不被视为顶级 class。

I modified the code to demonstrate that overloading will select the proper method based on the argument types.我修改了代码以证明重载将 select 基于参数类型的正确方法。 That means calling the methods with either ints or floats.这意味着使用整数或浮点数调用方法。 Using a single float and the float method will be called.使用单个浮点数,将调用float方法。 Using two ints and the int method will be called.使用两个 int 和int方法将被调用。

Note: (And this is important).注意:(这很重要)。 If you prompt for ints or type in ints and assign to a float, then the float method will be called.如果提示输入整数或输入整数并分配给浮点数,则将调用浮点方法。 Even if you prompt for floats and type in 10 and 20 the float method will be called.即使您提示输入浮点数并输入1020 ,也会调用 float 方法。 This is not about what you typed in but the types to which the values were assigned.这与您输入的内容无关,而是与分配值的类型有关。

Checking for the presence of a decimal to determine if the user wanted to use a float won't work since both Scanner.nextFloat() will accept a value sans decimal point as will Float.parseFloat() .检查是否存在小数以确定用户是否想要使用浮点数将不起作用,因为Scanner.nextFloat()将接受一个没有小数点的值, Float.parseFloat() Neither will throw an exception.两者都不会抛出异常。 Thus it is not possible to determine the actual intent of the user.因此,无法确定用户的实际意图。 And imo, forcing a user to supply a decimal point is unreasonable.而且imo,强迫用户提供小数点是不合理的。

My suggestion is that you drop the following code as is directly into a file called Bruh.java .我的建议是您将以下代码直接放入名为Bruh.java的文件中。 There is no reason that I can think of that should prevent this from working as I just did it myself.我没有理由认为这应该阻止它像我自己那样工作。 Sorry you have been struggling with this issue.抱歉,您一直在为这个问题而苦苦挣扎。

import java.util.Scanner;

class Unbruh {
    static int average(int x, int y) {
        System.out.println("Calling int version");
        return ((x + y) / 2);
    }
    
    static float average(float x, float y) {
        System.out.println("Calling float version");
        return ((x + y) / 2);
    }
}

public class Bruh {
    public static void main(String[] args) {
        
        System.out.println("Enter two float numbers.");
        Scanner input = new Scanner(System.in);
        float x = input.nextFloat();
        float y = input.nextInt(); // converted to a float
        float floatResult = Unbruh.average(x, y);
        System.out.println(floatResult);

        System.out.println("Enter two int numbers.");
        int xx = input.nextInt();
        int  yy = input.nextInt();
        int intResult = Unbruh.average(xx, yy);
        System.out.println(intResult);
        
        x = xx; // converting int to float
        y = yy; // converting int to float
        // float method will be called.
        
        floatResult = Unbruh.average(x,y);
        System.out.println(floatResult);
    }
}

Here is what a session might look like这是 session 的样子

Enter two float numbers.
10 20                         <-- user input
Calling float version
15.0
Enter two int numbers.
10 40                         <-- user input
Calling int version
25
Calling float version
25.0

To determine if a number is integer or float, you should read the number as a String.要确定一个数字是 integer 还是浮点数,您应该将该数字读取为字符串。 In this case you are reading the numbers as floats and that may not work to determine what you want (or maybe there is a way to do that how you have your code, I don't know).在这种情况下,您将数字读取为浮点数,这可能无法确定您想要什么(或者也许有一种方法可以做到这一点,我不知道您的代码如何)。 So, if you read the line as a String and check if this contains a .因此,如果您将该行读取为 String 并检查它是否包含. , if does, then, that's a float number, but here, you must be careful, because if you input any string , that will cause a NumberFormatException when the String it's converted to Float or Integer. ,如果是,那么,那是一个浮点数,但是在这里,你必须小心,因为如果你输入任何字符串,当字符串转换为浮点数或 Integer 时,将导致 NumberFormatException。

You can try something like this in your code:你可以在你的代码中尝试这样的事情:

import java.util.Scanner;

class Unbruh {
    static int average(int x, int y) {
        System.out.println("Integer numbers");
        return ((x + y) / 2);
    }
    
    static float average(float x, float y) {
        System.out.println("Float numbers");
        return ((x + y) / 2);
    }
}

public class Bruh {
    public static void main(String[] args) {
        
        System.out.println("Enter number");
        Scanner input = new Scanner(System.in);
        String x = input.next();
        String y = input.next();
        
        if(x.contains(".") || y.contains("."))
        {
            System.out.println(Unbruh.average(Float.parseFloat(x), Float.parseFloat(y)));
        }
        else{
            System.out.println(Unbruh.average(Integer.parseInt(x), Integer.parseInt(y)));
        }
        
        Unbruh a = new Unbruh();
        if(x.contains(".") || y.contains("."))
        {
            System.out.println(a.average(Float.parseFloat(x), Float.parseFloat(y)));
        }


        else{
            System.out.println(a.average(Integer.parseInt(x), Integer.parseInt(y)));
        }
        // System.out.println (average (x, y));
        
    }
}

And about your code, you have a little warning, because you have a.average(...) where a is an instance from Unbruh class.关于您的代码,您有一点警告,因为您有a.average(...)其中a是来自 Unbruh class 的实例。 But, the methods inside that class are static, thus, it's not necessary to use a.average(...) that's not recommended.但是,class 里面的方法是 static,因此,没有必要使用不推荐的a.average(...) For static methods, identifiers you have to use the follow syntax:对于 static 方法,标识符必须使用以下语法:

className.static_method(...)

In this case, in your code you have that syntax, in the lines:在这种情况下,在您的代码中,您可以在以下行中使用该语法:

Unbruh.average(...)

If you see, you are using the name class Unbruh and then, the static method如果您看到,您使用的是名称 class Unbruh ,然后是 static 方法

PD: When I say that you input any string can cause a NumberFormatException I mean that, if you input a string like "fuzz" , that will cause the error, but If you input "10" or "20.5" that is correct, so when you use the parse method, it will not throw a NumberFormatException PD:当我说你输入任何字符串都可能导致 NumberFormatException 我的意思是,如果你输入一个像"fuzz"这样的字符串,那会导致错误,但是如果你输入"10""20.5"是正确的,所以当您使用 parse 方法时,它不会抛出 NumberFormatException

Your problem is that, no matter what you enter from the console (ie 4 2 or 4.0 2.0), the fact is that you are capturing these as floats and the same method will be called (the one that returns a float).您的问题是,无论您从控制台输入什么(即 4 2 或 4.0 2.0),事实是您将它们捕获为浮点数,并且将调用相同的方法(返回浮点数的方法)。

The way I would do this is to keep the digits as Strings and create a single method that evaluates the input strings and evaluates them based on the string pattern.我这样做的方法是将数字保留为字符串并创建一个评估输入字符串并根据字符串模式评估它们的方法。 If the string contains a period, assume it is a floating point number.如果字符串包含句点,则假定它是浮点数。 If it doesn't, assume it is an integer.如果不是,假设它是 integer。 If you try to convert the string into a number AND it is not a number, the method will throw a NumberFormatException .如果您尝试将字符串转换为数字并且它不是数字,则该方法将抛出NumberFormatException

Once you have the strings converted to numbers, if BOTH numbers are integers, return an integer.将字符串转换为数字后,如果两个数字都是整数,则返回 integer。 Else, return a double.否则,返回双倍。 You can track this by simply using a isFloat flag to remember that at least one of the inputs were a floating point number.您可以通过简单地使用isFloat标志来跟踪这一点,以记住至少有一个输入是浮点数。 The solution is included below and it is not that complicated.解决方案包括在下面,它并不复杂。

public Number average(String x, String y) throws NumberFormatException {
    
    Number d1;
    Number d2;
    boolean isFloat = false;
    
    if (x.contains(".")) {
        d1 = Double.parseDouble(x);
        isFloat = true;
    } else {
        d1 = Integer.parseInt(x);
    }
    
    if (y.contains(".")) {
        d2 = Double.parseDouble(y);
        isFloat = true;
    } else {
        d2 = Integer.parseInt(y);
    }
    
    if (isFloat) {
        return (d1.doubleValue() + d2.doubleValue()) / 2.0;
    }
    
    return (d1.intValue() + d2.intValue()) / 2;
  }
}

public class Bruh {
  public static void main(String[] args) {
  
    System.out.println("Enter number");
    Scanner input = new Scanner(System.in);
    String x = input.next();
    String y = input.next();
    input.close();
    Unbruh a = new Unbruh();
    System.out.println(a.average(x, y));
  }
}

The outputs using the modified Bruh class:使用修改后的Bruh class 的输出:

4
2
3

4.0
2.0
3.0

4.0
2
3.0

4
2.0
3.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM