Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.concurrent.ThreadLocalRandom;
- public class JumbleGame {
- private static final String[] WORDS = new String[] {
- "magical","quarter","security","phrase","xylophone","hydrogen"
- };
- public static void main(String[] args) {
- JumbleGame jg = new JumbleGame();
- jg.startGame();
- }
- private void startGame() {
- int numberOfGuesses = 0;
- String original = selectRandomWord();
- String shuffled = getShuffledWord(original);
- boolean gameOn = true;
- while(gameOn) {
- System.out.println("Shuffled word is: "+shuffled);
- numberOfGuesses++;
- if(numberOfGuesses == 7) {
- System.out.println("HINT: Here are the first two letters in order: " + s1.charAt(0) + s1.charAt(1));
- }
- if(numberOfGuesses == 10) {
- System.out.println("Game Over! Try again next time!");
- System.exit(0);
- }
- String userGuess = getUserGuess();
- if(original.equalsIgnoreCase(userGuess)) {
- System.out.println("Congratulations! You found the word in "+numberOfGuesses+" guesses");
- gameOn = false;
- }
- else {
- System.out.println("Sorry, Wrong answer");
- }
- }
- }
- public String getUserGuess() {
- Scanner sn = new Scanner(System.in);
- System.out.println("Please type in the original word: ");
- return sn.nextLine();
- }
- public String selectRandomWord() {
- int rPos = ThreadLocalRandom.current().nextInt(0, WORDS.length);
- return WORDS[rPos];
- }
- public String getShuffledWord(String original) {
- String shuffledWord = original;
- int wordSize = original.length();
- int shuffleCount = 10;
- for(int i=0;i<shuffleCount;i++) {
- int position1 = ThreadLocalRandom.current().nextInt(0, wordSize);
- int position2 = ThreadLocalRandom.current().nextInt(0, wordSize);
- shuffledWord = swapCharacters(shuffledWord,position1,position2);
- }
- return shuffledWord;
- }
- private String swapCharacters(String shuffledWord, int position1, int position2) {
- char[] charArray = shuffledWord.toCharArray();
- char temp = charArray[position1];
- charArray[position1] = charArray[position2];
- charArray[position2] = temp;
- return new String(charArray);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement