Random Class in Java


    This week I wanted to keep improving my Java skills. I continued my Udemy course by John Purcell and watched his lecture on utilizing random class on Java. In his lesson, he utilized the the random class by creating Hangman in Eclipse but I wanted to try and use the random class with my own code from scratch. I figured the best way to learn the random class and to keep it simple would be to create a dice via Java. 

    It is a fairly simple project but it let me try something new and let me experiment with the random class and importing different items in Java. I had to begin the code by telling Java that I want the object DiceRoll to be Random after that I needed to initialize x, which could be labeled anything, and to have it be within the range of 1 to 6. If I were to change the line

int x = DiceRoll.nextInt(6) + 1; <-- to int x = DiceRoll.nextInt(10) + 5

It would make the dice roll start at 5 instead of 1 and make the dice roll any number from 5 to 15. There is no limit on the numbers so whatever I set them to, they'll adjust accordingly. After that, I needed to create a way to output what the dice is rolling and so I just went with a simple

 System.out.println("You rolled a: " + x");

I wrote it that way because I wanted it to have the perspective that the code would be talking to you. If I left it as just

System.out.println(x);

It would just print out the number and that is fairly boring. 



Comments

  1. Interesting, but as you said fairly simple. Contrasting this with something more elaborate would've made this a stronger blog.

    ReplyDelete

Post a Comment

Popular posts from this blog

Java Refresher

Rising of OLED