如何在Java中检查用户输入是float还是int?

我需要编写一个Java程序,要求用户从键盘输入数字。输出应指示它是正数还是负数,浮点数或整数,偶数或奇数。仅使用IF ... ELSE语句。

到目前为止,这是我的代码:

import java.util.Scanner;

public class PracticeClass1 {

public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter a number: ");

    int number = keyboard.nextInt();
    float Number = keyboard.nextFloat();

    if (number >= 1)
        System.out.print(number + " is a positive,");
    else 
        System.out.print(number + " is a negative,");

    if (number%2 == 0 )
        System.out.print(" even number");
    else 
        System.out.print(" odd number ");

    if (keyboard.hasNextInt()) 
        System.out.print(" is an integer");

    if (keyboard.hasNextFloat()) 
        System.out.println(" is a floating number");

    }
}
评论
xest
xest

By the time you call keyboard.hasNextInt() and keyboard.hasNextFloat(), you have already gotten the input, meaning these methods have nothing to check.

Instead, perform this before getting the number and store the result in a boolean:

System.out.println("Enter a number: ");

boolean isFloat = keyboard.hasNextFloat();
// Also get rid of the two input prompts, so you don't need to enter 2 numbers,
// of which only the first one would be used.
float number = keyboard.nextFloat();

// Perform other checks

if(isFloat)
    System.out.println(" is a floating number");
else
    System.out.println(" is an int");
点赞
评论