gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:25:30 24 4
gpt4 key购买 nike

自从生锈 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);
}
}
}

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

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

最佳答案

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

关于java - 如何比较变量以查看它是否是正确的类类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27322907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com