如何比较变量以查看它是否是正确的类类型?

Ora*_*ime 3 java java.util.scanner

自从2年生锈以来,我一直在从头学习Java,我正在玩一个简单的随机生成器代码.我的问题是当用户被问到他想要什么作为他的最高掷骰时,它必须是数字(int)类类型.

我试图创建一个if语句并将变量与其类进行比较,而不是让我的IDE停止并在用户键入字母的情况下向我显示错误消息.

这是我的代码(这是有史以来最简单的代码,但可以肯定地说我是新手并且激励自己再次学习Java.):

package firstguy;

import java.util.Random;
import java.util.Scanner;

public class randomnum {
  public static void main(String[] args){
      Random dice = new Random();
      Scanner userin = new Scanner(System.in);
      int number;
      int highnum;

      System.out.println("What's the highest roll you want? \n");
      highnum = userin.nextInt();



      for(int counter=1; counter<= highnum; counter++){
          number=  1 + dice.nextInt(highnum);
          System.out.println("This is the number " + number);
        }   
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够比较highnum,在这里看它是否作为类类型int而不是字母.如果键入字母或字符,则应显示消息或应重复该问题.我一直在努力寻找这个问题,但我不断得到比较同一类类型的两个变量的结果.

有没有办法将变量与类类型进行比较?

das*_*ght 7

原始类型的Java没有类.他们的包装器类型可以,但是你的代码不使用它们.

您要做的是检查最终用户输入是否存在表示整数与其他所有内容的字符组合.这相对容易,因为Scanner提供hasNext...了各种数据类型的方法.您可以hasNextInt()在循环中使用,丢弃不需要的输入,如下所示:

System.out.println("What's the highest roll you want? \n");
while (!userin.hasNextInt()) {
    System.out.println("Please enter an integer.");
    userin.nextLine();
}
// Since we reached this point, userin.hasNextInt() has returned true.
// We are ready to read an integer from the scanner:
highnum = userin.nextInt();
Run Code Online (Sandbox Code Playgroud)