Equals method not working Java - java

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

Related

Method with int and int[] parameters

I have a method with two parameters but they are different types (int , int[]). The problem is in the caller, Eclipse will not compile because it says both of the parameters need to be integer types. The caller looks like this:
boolean uniqueTorF = isUnique(count, userArray[i]);
The method is this:
public static boolean isUnique(int oneCount, int[] multiCount) {
for (int i = 0; i < multiCount.length; i++) {
if (oneCount == multiCount[i]) {
return false;
}
}
return true;
}
This is my entire code:
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int validCount = 0, i = 0, uniqueSoFar = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (validCount < 5) {
int count = entry.nextInt();
boolean validTorF = isValid(count);
boolean uniqueTorF = isUnique(count, userArray[i]);
if (validTorF == true) {
userArray[i] = count;
validCount++;
i++;
if (uniqueTorF == true){
uniqueSoFar++;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int validParameter) {
if (validParameter > 50 && validParameter < 100) {
return true;
} else {
return false;
}
}
public static boolean isUnique(int oneCount, int[] multiCount) {
for (int i = 0; i < multiCount.length; i++) {
if (oneCount == multiCount[i]) {
return false;
}
}
return true;
}
}
Get rid of the index [i]. userArray[i] is a single element of the array. userArray is the entire array.
boolean uniqueTorF = isUnique(count, userArray);
I'll bet it's saying the params ARE both integer types, not that they SHOULD BE. You're passing count and userArray[i], but you probably should be passing count and userArray.
Defined method expects second argument as array whereas the caller is sending specific element. So send the entire array as argument
The reason of the error is because you are passing the parameters wrongly...
When you do this:
boolean foo = isUnique(count, userArray[i]);
Then you are invoking the method with 2 int parameters, but you need a int, int [] instead...
You are for sure looking for something more like this:
boolean foo = isUnique(count, userArray);

Secret Word Game

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;
}

Java Arrays[] - Assigning Specific Elements in a For Loop to Certain Values

I was attempting to write some code for a program in BlueJ (Java) that lists bags and adds and removes items from those bags, that sort of thing. Then I got stuck in the first class; I couldn't get to add an item to the bag properly as you can notice below in the addItem() method; it keeps adding String s to every null element in the array rather the first encountered. Any help would be tremendously appreciated.
Best wishes & many thanks,
Xenos
public class Bag1 {
private String[] store; // This is an array holding mutlitple strings.
public Bag1(int storageCapacity) {
store = new String[storageCapacity];
} // That was the primitive array constructor.
public boolean isFull() {
boolean full = true;
for(int i = 0; i < store.length; i++) {
if(store[i] == null) {
full = false;
}
}
return full;
} // The method above checks if the bag is full or not, and returns a boolean value on that basis.
public void add(String s) {
for(int i = store.length; i >= 0; i--) {
if(store[i] == null) {
store[i] = s;
}
}
}
}
You should exit the loop after finding the first empty spot :
public void add(String s)
{
for(int i=store.length-1; i>=0; i--) { // note the change in the starting index
if(store[i]==null) {
store[i] = s;
break;
}
}
}

Can't get method (getTest) to return true boolean method result if input matches a number in my array list

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;
}

For loop input in BlueJ (infinite loop)

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!

Categories