Combination Lock assignment in Java - java

I have an assignment where there is a combination lock box that has a 4-letter word as the combination, and a player has to try to guess the combination by guessing the word one letter at a time. For each round, a clue should be outputted to show how close a person's guess is to the actual word. If the letter in the guess is also in the same position in the combination lock, then the matching letter is outputted. If the letter is in the word but not in the same position, a + is outputted, and when the letter is not present in the word at all, an * is outputted. All of those characters are added to a single string to show the result.
I've tried to code all of this in Java, but it returns an incorrect result with a null before it. Can someone help me fix these issues?
public class CombinationLock
{
private String lock;
private String guess;
private String guessLetter1;
private String guessLetter2;
private String guessLetter3;
private String guessLetter4;
private String lockLetter1;
private String lockLetter2;
private String lockLetter3;
private String lockLetter4;
private String modifiedGuess;
private char combinationLetter;
private char guessLetter;
public CombinationLock(String newLock)
{
lock = newLock;
}
public String getClue(String newGuess)
{
guess = newGuess;
for(int i = 0; i < lock.length(); i++)
{
combinationLetter = lock.charAt(i);
guessLetter = guess.charAt(i);
if(i == 0)
{
lockLetter1 += combinationLetter;
guessLetter1 += guessLetter;
}
else if(i == 1)
{
lockLetter2 += combinationLetter;
guessLetter2 += guessLetter;
}
else if(i == 2)
{
lockLetter3 += combinationLetter;
guessLetter3 += guessLetter;
}
else if(i == 3)
{
lockLetter4 += combinationLetter;
guessLetter4 += guessLetter;
}
if(combinationLetter == guessLetter)
{
modifiedGuess += combinationLetter;
}
else if(guessLetter1 == lockLetter1 || guessLetter1 == lockLetter2 || guessLetter1 == lockLetter3 || guessLetter1 == lockLetter4)
{
modifiedGuess += '+';
}
else if(guessLetter2 == lockLetter1 || guessLetter2 == lockLetter2 || guessLetter2 == lockLetter3 || guessLetter2 == lockLetter4)
{
modifiedGuess += '+';
}
else if(guessLetter3 == lockLetter1 || guessLetter3 == lockLetter2 || guessLetter3 == lockLetter3 || guessLetter3 == lockLetter4)
{
modifiedGuess += '+';
}
else if(guessLetter4 == lockLetter1 || guessLetter4 == lockLetter2 || guessLetter4 == lockLetter3 || guessLetter4 == lockLetter4)
{
modifiedGuess += '+';
}
else
{
modifiedGuess += '*';
}
}
return modifiedGuess;
}
}
public class MyProgram extends ConsoleProgram
{
public void run()
{
CombinationLock c1 = new CombinationLock("bird");
System.out.println(c1.getClue("barn"));
}
}

You need to initialise your modifiedGuess variable, i.e.
public CombinationLock(String newLock)
{
lock = newLock;
modifiedGuess = "";
}
Alternatively, you can look into StringUtils.difference function which may give you a similar result (if allowed for the assignment).
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#difference(java.lang.String,%20java.lang.String)

Related

Why won't an IF statement work with rounded floats and doubles?

I am trying to check if a user has inputted a double between 3.5 and 7. I have tried to use the actual double and Math.round();, as well as StrictMath.round(). I have also tried to parse the string inputted as a float but it didn't change anything. Here is the basic code I used:
import java.util.Scanner;
public class IfStatement {
public static void main(String[] args) {
//create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter first double: ");
double number = input.nextDouble();
if (isDouble(number)==true) {
double x = Double.parseDouble(number);
if (3.5 <= x <= 7) {
System.out.println("good");
} else {
System.out.println("incorrect input");
}
} else {
System.out.println("incorroct input");
}
}
public static booleen isDouble(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
++i;
}
int integerPartSize = 0;
int exponentPartSize = -1;
while (i < length) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
if (c == '.' && integerPartSize > 0 && exponentPartSize == -1) {
exponentPartSize = 0;
} else {
return false;
}
} else if (exponentPartSize > -1) {
++exponentPartSize;
} else {
++integerPartSize;
}
++i;
}
if ((str.charAt(0) == '0' && i > 1 && exponentPartSize < 1)
|| exponentPartSize == 0 || (str.charAt(length - 1) == '.')) {
return false;
}
return true;
}
}
I have also tried making 3.5 3 in the if statement but got no dice. I just need a loose explanation and not a full solution.
I've edited your code.
boolean spelling
isDouble() takes a String
a <= x <= b chained expressions are not allowed in Java
Also,
if ((str.charAt(0) == '0' && i > 1 && exponentPartSize < 1) || exponentPartSize == 0 || (str.charAt(length - 1) == '.')) {
return false;
}
return true;
can be simplified to
return (str.charAt(0) != '0' || i <= 1 || exponentPartSize >= 1)
&& exponentPartSize != 0 && (str.charAt(length - 1) != '.');
Here's the full code.
class Test {
public static boolean isDouble(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
++i;
}
int integerPartSize = 0;
int exponentPartSize = -1;
while (i < length) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
if (c == '.' && integerPartSize > 0 && exponentPartSize == -1) {
exponentPartSize = 0;
} else {
return false;
}
} else if (exponentPartSize > -1) {
++exponentPartSize;
} else {
++integerPartSize;
}
++i;
}
return (str.charAt(0) != '0' || i <= 1 || exponentPartSize >= 1)
&& exponentPartSize != 0 && (str.charAt(length - 1) != '.');
}
public static void main(String[] args) {
//create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter first double: ");
String number = input.nextLine();
if (isDouble(number)) {
double x = Double.parseDouble(number);
if (3.5 <= x && x <= 7) {
System.out.println("good");
} else {
System.out.println("incorrect input");
}
} else {
System.out.println("incorroct input");
}
}
}

Addition of two binary numbers

I tried to compere each number by putting the numbers in char arrays and compere them each by each with if conditions. Each outcome should be covered and each outcome should be saved in String result but the result of the whole operation is always blank. Java debugger isn't working and I donĀ“t see why it isn't working.
import java.util.Scanner;
public class BinaryAdder {
public static String add(String binary1, String binary2) {
String result = "";
char[] safea = binary1.toCharArray();
char[] safeb = binary2.toCharArray();
int lb1 = binary1.length() - 1;
int lb2 = binary2.length() - 1;
char reminder = 0;
while (lb1 != 0 || lb2 != 0) {
if (safea[lb1] == 0 && safeb[lb2] == 0 && reminder == 0) {
result += "0";
lb1--;
lb2--;
} else if (safea[lb1] == 1 && safeb[lb2] == 0 && reminder == 0) {
result += "1";
lb1--;
lb2--;
} else if (safea[lb1] == 1 && safeb[lb2] == 1 && reminder == 0) {
result += "0";
reminder = 1;
lb1--;
lb2--;
} else if (safea[lb1] == 1 && safeb[lb2] == 1 && reminder == 1) {
result += "1";
reminder = 1;
lb1--;
lb2--;
} else if (safea[lb1] == 1 && safeb[lb2] == 0 && reminder == 1) {
result += "0";
reminder = 1;
lb1--;
lb2--;
} else if (safea[lb1] == 0 && safeb[lb2] == 1 && reminder == 1) {
result += "0";
reminder = 1;
lb1--;
lb2--;
} else if (safea[lb1] == 0 && safeb[lb2] == 1 && reminder == 0) {
result += "1";
lb1--;
lb2--;
} else if (safea[lb1] == 0 && safeb[lb2] == 0 && reminder == 1) {
result += "1";
lb1--;
lb2--;
}
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Summand: ");
String input1 = scan.next("(0|1)*");
System.out.print("Summand: ");
String input2 = scan.next("(0|1)*");
scan.close();
System.out.println("Result: " + add(input1, input2));
}
}
You can parse the bits into integer with Integer.parseInt(s, radix). You need to use radix of 2:
public static String add(String binary1, String binary2) {
int i1 = Integer.parseInt(binary1, 2);
int i2 = Integer.parseInt(binary2, 2);
return Integer.toBinaryString(i1 + i2);
}

trouble with yahtzee in java

I have to create the yahtzee game and its methods like full house, small straight, big straight, 3 of kind, 4 of kind , and chance. Now this is what i have done so far and i would like to know if my methods are right and also i'm having a hard time trying to figure out how to check if its yahtzee , 3 of kind, 4 of kind , etc and this is in my main method. The program consists of seven rolls, where every roll can have up to two sub-rolls
static final int NUM_RERROLS_ = 2;
static final int NUM_OF_DICE = 5;
static final int NUM_ROLLS_ = 7;
static final int[] dice = new int[NUM_OF_DICE];
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
rollDice();
for (int i = 0; i < NUM_RERROLS_; i++) {
if (gotYatzee()) {
break;
}
System.out.println(diceToString());
askUser();
System.out.println("Which dice do you want to reroll: ");
secondReroll(convert(keyboard.nextLine()));
}
System.out.println(diceToString());
if (gotYatzee()) {
System.out.println("You got Yatzee & 50 points!");
} else if (largeStraight() == true) {
System.out.println("You got large straight");
} else {
System.out.println("Sorry no large straight");
}
if (smallStraight() == true) {
System.out.println("You got smallStraight");
} else {
System.out.println("Sorry no small straight");
}
if (fullHouse() == true) {
System.out.println("You got full house");
} else {
System.out.println("Sorry no full house");
}
{
System.out.println("SORRY NO YAHTZEE");
}
if (askUser() == false) {
if (largeStraight() == true) {
System.out.println("You got large straight");
} else {
System.out.println("Sorry no large straight");
}
if (smallStraight() == true) {
System.out.println("You got smallStraight");
} else {
System.out.println("Sorry no small straight");
}
if (fullHouse() == true) {
System.out.println("You got full house");
} else {
System.out.println("Sorry no full house");
}
}
}
public static void rollDice() {
for (int i = 0; i < NUM_OF_DICE; i++) {
dice[i] = randomValue();
}
}
public static int randomValue() {
return (int) (Math.random() * 6 + 1);
}
public static String diceToString() {
String dado = "Here are your dice: ";
for (int element : dice) {
dado = dado + element + " ";
}
return dado;
}
public static boolean gotYatzee() {
for (int element : dice) {
if (element != dice[0]) {
return false;
}
}
return true;
}
public static void secondReroll(int[] newValue) {
for (int element : newValue) {
dice[element - 1] = randomValue();
}
}
public static int[] convert(String s) {
StringTokenizer st = new StringTokenizer(s);
int[] a = new int[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
a[i++] = Integer.parseInt(st.nextToken());
}
return a;
}
public static boolean Chance() {
for (int element : dice) {
int i = 0;
if (element != dice[i]) {
i++;
return false;
}
}
return true;
}
public static boolean smallStraight() {
for (int i = 1; i <= NUM_OF_DICE; i++) {
boolean b = false;
for (int j = 0; j < NUM_OF_DICE; j++) {
b = b || (dice[j] == i);
}
if (!b) {
return false;
}
}
return true;
}
public static boolean largeStraight() {
int[] i = new int[5];
i = dice;
sortArray(i);
if (((i[0] == 1) && (i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5))
|| ((i[0] == 2) && (i[1] == 3) && (i[2] == 4) && (i[3] == 5) && (i[4] == 6))
|| ((i[1] == 1) && (i[2] == 2) && (i[3] == 3) && (i[4] == 4) && (i[5] == 5))
|| ((i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5) && (i[5] == 6))) {
return true;
} else {
return false;
}
}
public static boolean askUser() {
Scanner keyboard = new Scanner(System.in);
int a = 0;
String yes = "Yes";
String no = "No";
System.out.println("Do you want to reroll the dice again: Yes or No? ");
String userInput;
userInput = keyboard.next();
if (userInput.equals(yes)) {
System.out.println("ALRIGHTY!!");
return true;
} else if (userInput.equals(no)) {
}
return false;
}
public static boolean threeKind() {
int[] a = new int[5];
a = dice;
sortArray(a);
if ((((a[0] == a[1]) && (a[1] == a[2])) // Three of a Kind
|| ((a[1] == a[2]) && ((a[2] == a[3])
|| (((a[2] == a[3]) && (a[3] == a[4]))))))) {
return true;
} else {
return false;
}
}
/*public static boolean fourKind(int[] dice) {
}
*/
public static int[] sortArray(int[] numbers) {
int stop;
for (stop = 0; stop < numbers.length; stop++) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
swap(numbers, i, i + 1);
}
}
}
return numbers;
}
public static void swap(int[] numbers, int pos1, int pos2) {
int temp = numbers[pos1];
numbers[pos1] = numbers[pos2];
numbers[pos2] = temp;
}
public static boolean fullHouse() {
int[] a = new int[5];
a = dice;
sortArray(a);
if ((((a[0] == a[1]) && (a[1] == a[2])) && // Three of a Kind
(a[3] == a[4]) && // Two of a Kind
(a[2] != a[3]))
|| ((a[0] == a[1]) && // Two of a Kind
((a[2] == a[3]) && (a[3] == a[4])) && // Three of a Kind
(a[1] != a[2]))) {
return true;
} else {
return false;
}
}
}
basically i want to figure out a way to check if its full house, 3 of kind, 4 of kind , etc
You have 6 dice after three rolls. Sort the array of user-retained dice after the 3 rolls.
Yahtzee: ((die[0] == die[4]) || (die[1] == die[5]))
4 of a kind: ((die[0] == die[3]) || (die[1] == die[4] || (die[2] == die[5]))
Small straight, 3 tests (x = 3,4,5): ((die[x] - die[x-3]) == 3)
Large straight, 2 tests (x = 4,5): ((die[x] - die[x-4]) == 4)
etc.
Chance: Up to the user, right?
Unless I'm missing something (I'm a little rusty on Yatzee), this should be fairly straightforward.

String equation error checker not working

I have a method that checks to see if an equation written is correct.
This method check for:
Multiple Parentheses
Excess operators
Double Digits
q's
and any character in a string that is not and of these:
.
private static final String operators = "-+/*%_";
private static final String operands = "0123456789x";
It was working fine, but then I added in modular to the operators and now whenever my code reaches the part in the method that checks to the left and the right of an operand to see if it is neither the end of the string or the beginning I get an error saying
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
My method and all it's additional methods.
private static final String operators = "-+/*%_";
private static final String operands = "0123456789x";
public Boolean errorChecker(String infixExpr)
{
char[] chars = infixExpr.toCharArray();
StringBuilder out = new StringBuilder();
for (int i = 0; i<chars.length; i++)
{
System.out.print(infixExpr.charAt(i));
if (isOperator(infixExpr.charAt(i)))
{
if (i == 0 || i == infixExpr.length())
{
out.append(infixExpr.charAt(i));
}
else if (isOperator(infixExpr.charAt(i + 1)) && isOperator(infixExpr.charAt(i - 1)))
{
System.out.println("To many Operators.");
return false;
}
else if (isOperator(infixExpr.charAt(i + 1)))
{
if (infixExpr.charAt(i) != '-' || infixExpr.charAt(i + 1) != '-')
{
System.out.println("To many Operators.");
return false;
}
}
else if (isOperator(infixExpr.charAt(i - 1)))
{
if (infixExpr.charAt(i) != '-' || infixExpr.charAt(i - 1) != '-')
{
System.out.println("To many Operators.");
return false;
}
}
}
else if (isOperand(infixExpr.charAt(i)))
{
if (i == 0 || i == infixExpr.length())
{
out.append(infixExpr.charAt(i));
}//THE LINE RIGHT BELOW THIS COMMENT THROWS THE ERROR!!!!!
else if (isOperand(infixExpr.charAt(i + 1)) || isOperand(infixExpr.charAt(i - 1)))
{
System.out.println("Double digits and Postfix form are not accepted.");
return false;
}
}
else if (infixExpr.charAt(i) == 'q')
{
System.out.println("Your meow is now false. Good-bye.");
System.exit(1);
}
else if(infixExpr.charAt(i) == '(' || infixExpr.charAt(i) == ')')
{
int p1 = 0;
int p2 = 0;
for (int p = 0; p<chars.length; p++)
{
if(infixExpr.charAt(p) == '(')
{
p1++;
}
if(infixExpr.charAt(p) == ')')
{
p2++;
}
}
if(p1 != p2)
{
System.out.println("To many parentheses.");
return false;
}
}
else
{
System.out.println("You have entered an invalid character.");
return false;
}
out.append(infixExpr.charAt(i));
}
return true;
}
private boolean isOperator(char val)
{
return operators.indexOf(val) >= 0;
}
private boolean isOperand(char val)
{
return operands.indexOf(val) >= 0;
}
My main portion that runs the method:
Boolean meow = true;
while(meow)
{
System.out.print("Enter infix expression: ");
infixExpr = scan.next();//THE LINE RIGHT BELOW THIS COMMENT THROWS THE ERROR!!!!!
if(makePostfix.errorChecker(infixExpr) == true)
{
System.out.println("Converted expressions: "
+ makePostfix.convert2Postfix(infixExpr));
meow = false;
}
}
It was working fine before, but now it won't even pass 1+2 which was previously working and I changed NONE of that you see. What's wrong!?!?
What looks like what's happening is that you check for the character at index (i + 1) several times in your code. Lets say you input a string with a length of five characters. The program goes through and reaches the line:
else if (isOperator(infixExpr.charAt(i + 1)) && isOperator(infixExpr.charAt(i - 1)))
If i == 4, this will cause the code:
infixExpr.charAt(i + 1)
to throw an index error.
In essance, you're checking for a character at index five (the sixth character) in a string with a maximum index index of four which is five characters in length. Also, your checking for
if(i==0 || i == infixExpr.length)
won't work as is. Maybe check for (i==infixExpr.length-1).

Accessing variable from different methods (Java)

another question to put out there. I was working on an assignment to create hash functions and all that jazz, and i have stumbled across a small problem.
Line 35:21, where it reads arrpos += prearrpo & ______,
in my head works... What im trying to do is access arr.length from the HashTable() method. I've read around, suggestions with needing to creat an object of size arr.length; however in my mind, this seems overly complicated-
Is there another way i can access the variable in the HashTable method, but inside the insert method?
Another not so important question involves the giant block of if() statements in the letter(char c) class; im certain there must be a shorter way of doing this... I would have initially used the ascii values; but the specifications were quite particular about using the values 1-26 for lower/upper case letters-
Thanks
import java.io.*;
public class HashTable {
public HashTable() {
//Create an array of size 101
String arr[] = new String[101];
//System.out.println("Size1: ");
}
public HashTable(int tsize) {
int size = 2 * tsize;
//System.out.println("Size: " + size);
boolean isPrime = checkPrime(size);
//System.out.println("IsPrime: " + isPrime);
while (isPrime == false) {
//System.out.println("Size: " + size);
size++;
isPrime = checkPrime(size);
}
//System.out.println("Size: " + size);
String arr[] = new String[size];
}
public boolean insert(String line) {
String str = line;
char[] ch = str.toCharArray();
int slen = str.length();
int arrpos = 0;
int hash = slen;
for (int i = 0; i < slen; i++) {
double prearrpo = letter(ch[i]) * Math.pow(32, (hash - 1));
arrpos += prearrpo % arr.length();
hash--;
}
System.out.println(arrpos);
System.out.println("array size:");
System.out.println();
return false;
}
private int letter(char c) {
char ch = c;
if (ch == 'A' || ch == 'a') {
return 1;
}
if (ch == 'B' || ch == 'b') {
return 2;
}
if (ch == 'C' || ch == 'c') {
return 3;
}
if (ch == 'D' || ch == 'd') {
return 4;
}
if (ch == 'E' || ch == 'e') {
return 5;
}
if (ch == 'F' || ch == 'f') {
return 6;
}
if (ch == 'G' || ch == 'g') {
return 7;
}
if (ch == 'H' || ch == 'h') {
return 8;
}
if (ch == 'I' || ch == 'i') {
return 9;
}
if (ch == 'J' || ch == 'j') {
return 10;
}
if (ch == 'K' || ch == 'k') {
return 11;
}
if (ch == 'L' || ch == 'l') {
return 12;
}
if (ch == 'M' || ch == 'm') {
return 13;
}
if (ch == 'N' || ch == 'n') {
return 14;
}
if (ch == 'O' || ch == 'o') {
return 15;
}
if (ch == 'P' || ch == 'p') {
return 16;
}
if (ch == 'Q' || ch == 'q') {
return 17;
}
if (ch == 'R' || ch == 'r') {
return 18;
}
if (ch == 'S' || ch == 's') {
return 19;
}
if (ch == 'T' || ch == 't') {
return 20;
}
if (ch == 'U' || ch == 'u') {
return 21;
}
if (ch == 'V' || ch == 'v') {
return 22;
}
if (ch == 'W' || ch == 'w') {
return 23;
}
if (ch == 'X' || ch == 'x') {
return 24;
}
if (ch == 'Y' || ch == 'y') {
return 25;
}
if (ch == 'Z' || ch == 'z') {
return 26;
}
return 0;
}
public boolean lookUp(String string) {
//
return false;
}
public String getNum() {
//
return null;
}
public int length() {
return 0;
}
private static boolean checkPrime(int size) {
if (size % 2 == 0) {
return false;
}
double c = Math.sqrt(size);
for (int i = 3; i < c; i += 2) {
if (size % i == 0) {
return false;
}
}
return true;
}
}
public HashTable() is a constructor. Your arr[] should actually be a private member of your class and you should initialize it in all constructors or make sure you never access without intializing it.
public class HashTable {
private String[] arr;
public HashTable()
{
//Create an array of size 101
arr[] = new String[101];
System.out.println("Size1: ");
}
etc...
Since it seems that your implementation is array backed, you need to declare the array as a member variable:
public class HashTable {
String arr[] = null;
And then initialize it in your constructors ( note in Java world methods like HashTable() is called a constructor) as :
arr = new String[whatever_size];

Categories