I was assigned to create a guessing game where you are given a secret word in asterisks and have 5 tries to guess the correct word. They enter in a letter at a time and those letters are revealed in the word. Unlike hangman each turn counts and not just every time they pick a letter that’s not in the word. The class only requires a default constructor Here is my code so far and here is the driver: http://pastebin.com/35T9B4wM
public class SecretWord {
private String secretWord;
private String hintWord;
private int numberOfTurns;
public SecretWord()
{
this.secretWord = "fruit";
this.numberOfTurns = 0;
for(int i=0;i<secretWord.length();i++)
{
hintWord+="*";
}
}
public String getSecretWord()
{
return this.secretWord;
}
public String getHintWord()
{
return this.hintWord;
}
public int getNumberOfTurns()
{
return this.numberOfTurns;
}
public void setSecretWord()
{
this.secretWord = "fruit";
}
public void setHintWord()
{
}
public void setNumberOfTurns(int i)
{
this.numberOfTurns = 5;
}
public void guessLetter()
{
}
}
I'm just not understanding what should go in the accessors or mutators. Or in the guessLetter variable where whenever the letter is found in the secret word, then that letter replaces that asterisk in the hint word.
Here is a list of instructions that may help.
This class has three instance variables
secretWord: the word the user
has to guess
hintWord: the word with the guess letters revealed
numberOfTurns: keeps track of the number of guesses
This class only requires a default constructor
You set the secret word
Number of turns to a default value of 0
The hint word is constructed using asterisk (*) for every letter that’s in the secret word
Accessors for every instance variable
Mutators for every instance variable CHECK FOR VALID VALUES!
Yup you are pretty close on the logic. You just have to update your hintWord after. Something like this should do the trick.
hintWord = "";
for (int i = 0; i < secretWord.length(); i++){
if (secretWord.charAt(i) == guess){ //Check if we found anything
//found = true; We do not need this variable since we already know if we found something
correctLetters[i] = guess;
}
hintWord += correctLetters[i];
}
Just make sure your correctLetters is set correctly in the beginning. You can set it in your setHintWord. Like this:
public void setHintWord(){
correctLetters = new char[secretWord.length()];
for(int i=0;i<secretWord.length();i++)
{
hintWord+="*";
correctLetters[i] += '*';
}
}
If you do not want to keep track of another instance variable (since your instructions say to only use 3) you can do something like this with a temporary String.
public void guessLetter(char guess){
String tempHintWord = "";
for (int i = 0; i < secretWord.length(); i++){
if (secretWord.charAt(i) == guess){ //Check if we found anything
//found = true; We do not need this variable since we already know if we found something
tempHintWord += guess;
}else{
tempHintWord += hintWord.charAt(i);
}
}
hintWord = tempHintWord;
}
Related
When the application is launched, it will ask the user to enter words one at a time. Once a word has been entered, it will ask if the user would like to add a new word. The user will continue adding words until they indicate they are done.
After all words have been entered, the application will output a report listing only the unique words. (No duplicate words should appear in the report.)
I have the issue with the function found word
it should work like that :
program such that it contains a list of keywords. Place whatever words you choose into this list (hard coding in values is ok). When your program runs compare the user entered words to the list of keywords. Indicate on the output report which user-entered words were keywords.
Also, I have the issue with function sort String :
program such that the words are alphabetized in the output report.
The program works perfectly for the display words, but it doesn't work for Find keywords and match words also not working with sort alphabetized
import java.util.*;
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Collection;
public class LabNineKennel {
private InputHelper2 input;
private ArrayList<LabNine> labNineWords;
public void run() {
entry();
displaywords();
findWord();
}
public void entry()
labNineWords = new ArrayList<LabNine>();
input = new InputHelper2();
String word = "";
String more = "";
LabNine newLabNine = null;
// the method to take the information fron the user
while (true) {
word = input.getUserInput(
"Enter the name of the client");
newLabNine = new LabNine();
newLabNine.setWord(word);
labNineWords.add(newLabNine);
// ask the user again if he want to addd any other client
more = input.getUserInput(
"Would you like to enter another?");
if (!more.equals("y")) {
break;
}
}
}
public void displaywords() {
LabNine labnine = null;
System.out.println("\n");
System.out.println("*****Your List Of Unique Word*********");
for (int i = 0; i < labNineWords.size(); i++) {
labnine = labNineWords.get(i);
System.out.println(labnine.display());
}
System.out.println( "\n*******************************************");
}
public void findWord() {
// creat the private instance variable for class Kennel
String [] codes = {"G22", "K13", "I30", "S20"};
LabNine labnine = null;
for (int i = 0; i < labNineWords.size(); i++) {
boolean isValid = false;
labnine = labNineWords.get(i);
if (labnine.equals( codes)) {
isValid = true;
}else isValid = false;
if (isValid = true) {
System.out.println(labnine.display2());
}
}
}
public void sortString()
{
LabNine labnine = null;
System.out.println("\n");
System.out.println("*****Your List Of Unique Word*********");
for (int i = 0; i < labNineWords.size(); i++) {
labnine = labNineWords.get(i);
Arrays.sort(labNineWords);
System.out.println(labnine.display());
}
}
}
The LabNine Class
// Creat a client class
public class LabNine {
// creat the private instance variable for class Client
private String word;
private String word1;
private String word2;
private String word3;
private String word4;
/**
* Sets the value of word4.
* #param word4 The value to assign word4.
*/
public void setWord4(String word4) {
this.word4 = word4;
}
/**
* Sets the value of word3.
* #param word3 The value to assign word3.
*/
public void setWord3(String word3) {
this.word3 = word3;
}
/**
* Sets the value of word2.
* #param word2 The value to assign word2.
*/
public void setWord2(String word2) {
this.word2 = word2;
}
/**
* Sets the value of word1.
* #param word1 The value to assign word1.
*/
public void setWord1(String word1) {
this.word1 = word1;
}
/**
* Returns the value of word.
*/
public String getWord() {
return word;
}
/**
* Sets the value of word.
* #param word The value to assign word.
*/
public void setWord(String word) {
this.word = word;
}
// creat the method display to display the data that user input
public String display() {
return
"\n " + getWord();
}
public String display2() {
return "\n" + getWord() + "*";
}
}
The line of code (labnine.equals(codes)) is checking if an Object is equal to an Array. This will return false.
This can be modified to the below to check if the codes does contain the word
if ((Arrays.asList(codes).contains(labnine.getWord()))) {
isValid = true;
} else {
isValid = false;
}
In the findWord you should check which words entered by the user are keywords. You iterate over words (labNineWords) but then check by simply doing labnine.equals(codes). You are basically comparing an instance of LabNine with an array of strings here. Unless your LabNine.equals method is specially programmed so that it will check if the word denoted by the given LabNine instance is contained in the array (and I highly doubt it is programmed this way), this equals call will not produce results you expect.
An easier way is to create a set of keywords and simply check if labnine.display() (or however you get the string representation of the word) is contained in this set. Something along the lines:
private static final Set<String> KEYWORDS =
Collections.unmodifiableSet(new HashSet<>(Arrays.asList("G22", "K13", "I30", "S20")));
public void findWord() {
for (int i = 0; i < labNineWords.size(); i++) {
LabNine labnine = labNineWords.get(i);
if (KEYWORDS.contains(labnine.display()) {
// This is a keyword
System.out.println(labnine.display2());
}
}
}
Next, sorting. You sort with Arrays.sort. This most probably won't even compile as your labNineWords is a collection, not an array. You can sort this list using Collections.sort. For this to work, either your LabNine class must implement Comparable or you have to provide a Comparator. Assuming you want to sort on LabNine.display(), you can easily construct a comparator with Comparator.comparing(LabNine::display)
Also you probably don't want to modify the original list, so better make a copy.
Something along the lines:
public void sortString()
{
List<LabNine> sortedLabNineWords = new ArrayList<>(labNineWords);
Collections.sort(sortedLabNineWords,
Comparator.comparing(LabNine::display));
System.out.println("\n");
System.out.println("*****Your List Of Unique Word*********");
for (int i = 0; i < sortedLabNineWords.size(); i++) {
LabNine labnine = sortedLabNineWords.get(i);
System.out.println(labnine.display());
}
}
I am calling a method from another class. The method contains an integer array. I am trying to stay away from inputting the index manually.
I am trying to search for numbers within a range.
example:
ArrayList: {1,5}, {5,10}, {10,15}
Input: enter 3
Process: search for number within range
output: 1,5
The driver class is storing the objects from the main class called Numbers into ArrayList. The main class have an accessor call getNumbers. getNumbers contains an integer array with 2 elements. The driver is calling getNumbers to validate the entry that users input.
The code below works but I'm told it's consider bad coding to code entering the indexes. I want to know how to output the array from getNumber method without knowing the array length of getNumber?
example of what I have:
for(int i = 0; i < example.size(); i++)
//number is the integer that is inputted.
if(example.get(i).getNumbers()[1] > number &&
example.get(i).getNumbers()[0] <= numbers)
System.out.println(example.get(i));
Should I add another for loop?
example of what I am thinking of:
for(int i = 0; i < example.size(); i++)
for(int j = 0; j < example.get(i).getNumbers.length; j++){
if(example.get(i).getNumbers()[j] > number &&
example.get(i).getNumbers()[j] <= numbers)
System.out.println(example.get(i));
}
}
Edit: Changed how I worded some things and fixed the code of what I think I should do.
The code below works but I'm told it's consider bad coding to code
entering the indexes. I want to know how to output the array from
getNumber method without knowing the array length of getNumber ?
If you don't want to do the validations with array indexes for your first element and second element in the array, then you can solve the problem by modifying your Numbers class as shown below:
(1) Define two int variable members (currently you have only one)
(2) Add a method isInLimits(int input) to validate the range
(3) Override toString() which can be used to print the object as String
Numbers class (modified):
public static class Numbers {
private int firstElement;
private int secondElement;
public int getFirstElement() {
return firstElement;
}
public void setFirstElement(int firstElement) {
this.firstElement = firstElement;
}
public int getSecondElement() {
return secondElement;
}
public void setSecondElement(int secondElement) {
this.secondElement = secondElement;
}
//checks the input is in the range of this object elements
public boolean isInLimits(int input) {
if(input >= firstElement && input < secondElement) {
return true;
} else {
return false;
}
}
#Override
public String toString() {
return "{"+firstElement+","+secondElement+"}";
}
}
Usage of Numbers Class:
public static void main(String[] args) {
int userInput = 10; //get it from user
List<Numbers> example = new ArrayList<>();
//Add Numbers objects to example list
for(int i=0;i< example.size();i++) {
Number numberTemp = example.get(i);
//call Numbers object's isInLimits
if(numberTemp.isInLimits(userInput)) {
System.out.println(numberTemp);
}
}
}
So I have my equals method here in the class below, and I doesn't seem to be returning true when the if statement is true! I can't seem to find out why...
public class Player {
private int[] anyplayer = new int[5];
// constructor for each player at the table
public Player(int[] anyplayer) {
this.anyplayer = anyplayer;
}
// checks if the player has a winning bet in the european roulette
public boolean europeanequals(){
boolean truth = false;
for (int i = 0; i < anyplayer.length; i++) {
if (roulettedriver.eurowinningnumber == anyplayer[i]) {
truth = true;}
else {
truth = false;
}
}
return truth;
}
Here is my driver where I call the method:
public class roulettedriver {
// declaring the two roulettes
final static int[] europeanroulettegame = {0,32,15,19,4,21,2,25,17,34,6,27,13,36,11,30,8,23,10,5,24,16,33,1,20,14,31,9,22,18,29,7,28,12,35,3,26};
final static int[] americanroulettegame = {0,28,9,26,30,11,7,20,32,17,5,22,34,15,3,24,36,13,1,00,27,10,25,29,12,8,19,31,18,6,21,33,16,4,23,35,14,2};
// declaring the two winning numbers
public static int eurowinningnumber = europeanroulette.getRandom(europeanroulettegame);
public static int uswinningnumber = americanroulette.getRandom(americanroulettegame);
public static void main(String[] args) {
Scanner keyin = new Scanner(System.in);
// initializing the six players (First player)
int[] player1 = {-1,-1,-1,-1,-1}; // the numbers are set to -1 because 0 is a winning number
Player first_player = new vipplayer(player1); // First player is automatically a VIP
try{
for(int i=0;i<=5;i++) {
player1[i] = Integer.parseInt(keyin.nextLine());
}
}
catch(NumberFormatException e){
System.out.println("Player 2 : ");
}
// booleans are set to true if the bets match the randomly generated number
boolean winbet1 = first_player.europeanequals();
And basically my equals isn't comparing the right values I think... Can't seem to make this work? Any input? The value is supposed to be returned in the boolean winbet1
Your code continues even after finding a match, potentially resetting truth back to false, and returning that.
You need to change the method like so:
public boolean europeanequals(){
for (int i = 0; i < anyplayer.length; i++) {
if (roulettedriver.eurowinningnumber == anyplayer[i]) {
return true;
}
}
return false;
}
or using a for-each loop:
public boolean europeanequals(){
for (int number : anyplayer) {
if (roulettedriver.eurowinningnumber == number) {
return true;
}
}
return false;
}
While other answered, I want to add few notes:
arrays are zero-based in Java, this code:
for(int i=0;i<=5;i++) {
player1[i] = Integer.parseInt(keyin.nextLine());
}
will throw an exception, you should loop until 4 (or better, plater1.length)
follow Java Naming Conventions and rename your class to begin with upper case, also try to name your variables like firstPlayer instead of first_player
indent your code for a better and safer world
You probably forgot a break:
if (roulettedriver.eurowinningnumber == anyplayer[i]) {
truth = true;
break; // here
}
Without it, the loop will continue and probably set truth back to false
I can't seem to get the "The numbers match" result if my input is a number that is in my array list in another class called SomeNumbers. If you run it, it will give you the result for it not being a number in the array at the speed of light though.
I am also having a hard time pin pointing where the actual problem is because I can use my debugging tools for whatever reason in jGrasp.
This is the main application that the user would input the number to see if there is a match.
import java.util.Scanner;
public class SomeNumbersClient {
public static void main(String[] args) {
SomeNumbers testNumbers = new SomeNumbers();
Scanner userInput = new Scanner(System.in);
System.out.print("Enter Integer Value: ");
int input = userInput.nextInt();
testNumbers.setNumber(input);
if (testNumbers.getTest()) {
System.out.println("The numbers match");
} else {
System.out.println("The numbers don't match");
}
}
}
Now this is the class where I call on the getTest method to see if the boolean result is true or false. I then have the if statement in the client see if it's true then it will display that there is a match, if not, there is no match.
public class SomeNumbers {
private int[] numbers = { 5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 8080152, 4562555, 5552012, 5050552, 7825877, 120255, 1005231, 6545231, 3852082, 7576651,7881200, 4581002};
private int number;
private int index = 0;
private boolean test = true;
public void setNumber(int input) {
number = input;
}
public boolean getTest(){
while (index < numbers.length){
if (number != numbers[index]){
test = false;
index++;
} else {
test = true;
}
}
return test;
}
}
Sorry the code kind of got chopped up, any help is appreciated.
here is proper version of getTest function, your problem was because you find match (and set variable test to true), but then you continue search and next number converts "test" to false
public boolean getTest()
{
index = 0;
while (index < numbers.length)
if (number != numbers[index])
index++;
else
return true;
return false;
}
I'm working on a project for school and am stumped at where I am at the moment. When I run my project, the VM seems to be stuck in a loop and will not load (A console should pop up allowing me to input characters for the CombinationLock class setDigit() method). I believe it has something to do with my for loop in my Interface.java class. If anyone could take a look and lead me in the right direction, that'd be much appreciated. Thanks a bunch!
Interface.java
import java.util.*;
public class Interface
{
public static void main() {
Scanner in = new Scanner(System.in);
CombinationLock combo = new CombinationLock();
for(int i = 0; i < 3; i++) {
String ltr = in.nextLine();
combo.setDigit(ltr.charAt(0), i);
System.out.println("Digit " + i + " has been set to " + ltr);
}
}
}
CombinationLock.java
public class CombinationLock
{
String[] combo = new String[3];
public CombinationLock() { }
public boolean setDigit(char letter, int index) {
if (Character.isDigit(letter)) {
return false;
}
combo[index] = String.valueOf(letter);
return true;
}
public boolean unlock(String combo) {
if (combo.length() > 3) {
return false; //Longer then it can be, not valid
}
char[] comboArray = combo.toCharArray();
for (char c : comboArray) {
if (Character.isDigit(c)) {
return false; //Contains numbers, not valid
}
}
boolean valid = true;
for (int i = 0; i < 3; i++) {
if (combo.charAt(i) != comboArray[i] && valid == true) {
valid = false;
break;
}
}
return valid;
}
}
You have initialized combo array in CombinationLock class with length 0 as String[] combo = {};. This is cause ArrayIndexOutOfBoundsException when you are calling combo.setDigit(ltr.charAt(0), i);. Please correct the initialization. I beleive you want to capture 3 inputs, in that case, please initialize combo in CombinationLock with length 3 as below:
String[] combo = new String[3];
Your problem is (the signature of the main method is wrong)
public static void main() {
it should be
public static void main(String[] args) {
I've found where my error was, using the BlueJ IDE one must output something to the console before it shows up and allows you to input data, therefore it never popped up as I never used System.out.println or System.out.print. After doing so, the console popped up and allowed me to input my data. Thanks you for all your suggestions and help!