【发布时间】:2021-09-04 03:01:35
【问题描述】:
这是用 Java 15.0.2 和 netbeans 12.0LTS 编码的 我想假设我正确地编码了这个硬币翻转发生器,但 0 是唯一给我正确的选项,1 从来没有。我不知道是我把 Math.random 搞砸了,还是我就是这么倒霉。
package pkgthis.thing;
import java.util.Scanner;
/**
*
* @author Student
*/
public class LabQuestion6 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int coin = (int) (Math.random()*1);
int choice;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please choose 1 or 0: \n");
choice = keyboard.nextInt();
if (choice == coin)
{
System.out.println("You are correct");
}
else
{
System.out.println("You are incorrect");
}
}
}
【问题讨论】:
-
先阅读Math.random()的文档。然后尝试打印一些值
System.out.println(Math.random());以了解该方法的工作原理。 -
int coin = (int) (Math.random()*1);; Math.random() 将是 0 和 1 之间的某个值,然后将其乘以 1。这是同一件事,所以它仍然是 0 和 1 之间的某个值。然后将其转换为 int。在java中从浮点数(小数)到整数(不是小数)总是向0舍入,这称为截断。所以这个数字永远是0。你的错误就在这条线上。 -
[1]
nextInt(bound)method ofRandom是比使用Math.random()更好的方法。 [2] 另外,请注意 NetBeans 12.0 不支持使用 Java 15。From the 12.0 release notes:“Apache NetBeans 12.0 在 JDK LTS 版本 8 和 11 以及 JDK 14 上运行,即,此 NetBeans 发布时的当前 JDK 版本。"