Java导入java.util.Random后仍提示cannot find symbol问题求助
Fixing the "cannot find symbol" Error in Your Java Dice Code
Hey there! Let's break down why you're hitting that frustrating "cannot find symbol" error even after importing java.util.Random.
The Most Likely Culprit
From your code snippet, it looks like you're trying to use something like ra... (probably a Random instance) to generate your dice values—but you never created an instance of the Random class! Importing the class just tells the compiler where to find it, but you need to actually instantiate it to use its methods.
Here's How to Fix It
- First, create a Random object inside your
mainmethod (right before you need to generate rolls):Random rand = new Random(); - Then use this instance to generate your dice rolls (since dice are 1-6, we use
nextInt(6) + 1to get values in that valid range):
Corrected Code Snippet
import java.util.Random; public class dobbelsteen { public static void main(String[] args) { int dobb1; int dobb2; int dobb3; int dobb4; int dobb5; boolean alldobb = true; // Create Random instance here Random rand = new Random(); do { dobb1 = rand.nextInt(6) + 1; dobb2 = rand.nextInt(6) + 1; dobb3 = rand.nextInt(6) + 1; dobb4 = rand.nextInt(6) + 1; dobb5 = rand.nextInt(6) + 1; // Example check for all dice being the same alldobb = (dobb1 == dobb2 && dobb2 == dobb3 && dobb3 == dobb4 && dobb4 == dobb5); } while (!alldobb); } }
Other Quick Checks
- Double-check variable spelling: If you named your Random instance something else (like
randominstead ofrand), make sure you're using the exact same name when callingnextInt(). - Side note: While not an error, Java convention uses PascalCase for class names—so
Dobbelsteeninstead ofdobbelsteenwould be more standard.
内容的提问来源于stack exchange,提问作者Frank
相关产品推荐
相关产品推荐

