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);
}
Related
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");
}
}
}
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)
This question already has answers here:
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
(3 answers)
Closed 3 years ago.
I am a bit new to java and was hoping if anyone could help me. I'm writing this code on virtual machine Ubuntu using the text editor. The RAM errors is right here if you would like to reference the file. http://users.cis.fiu.edu/~crahn/CGS3767/RAMerrors. The error is located in the public static readingLine in the System.out.printf. If anyone could help me idenify the error, I would greatly appreciate it. Thank you!
import java.io.*;
import java.util.*;
public class MemoryCalculator
{
private static Scanner convertingFiles;
public static String convertFile = "RAMerrors.txt";
public static void readFile(String nameOfFile) throws IOException
{
convertingFiles = new Scanner(new File(nameOfFile));
}
public static void readingLine(String nameOfFile) throws IOException
{
System.out.println();
int recordingNum = 0;
while(convertingFiles.hasNext())
{
recordingNum = recordingNum +1;
String recordingLine = convertingFiles.nextLine();
System.out.printf("( %d) %g ) \n", recordingNum, recordingLine );
String conv = fromHexToBi(recordingLine);
long decimal = fromBiToDec(conv);
System.out.println(errorRamRangeWeb(decimal));
}
}
public static String fromHexToBi(String input)
{
int fromHexToBi = 0;
String record = "";
char var;
for(int x = 0; x < input.length(); x++)
{
var = input.charAt(x);
if(var == '0')
{
record += "0000";
}
else if (var == '1')
{
record += "0001";
}
else if (var == '2')
{
record += "0010";
}
else if (var == '3')
{
record += "0011";
}
else if (var == '4')
{
record += "0100";
}
else if (var == '5')
{
record += "0101";
}
else if (var == '6')
{
record += "0110";
}
else if (var == '7')
{
record += "0111";
}
else if (var == '8')
{
record += "1000";
}
else if (var == '9')
{
record += "1001";
}
else if (var == 'A')
{
record += "1010";
}
else if (var == 'B')
{
record += "1011";
}
else if (var == 'C')
{
record += "1100";
}
else if (var == 'D')
{
record += "1101";
}
else if (var == 'E')
{
record += "1110";
}
else if (var == 'F')
{
record += "1111";
}
else
{
System.out.print("Sorry, the error is .out of range");
}
}
System.out.println(record);
return record;
}
public static long fromBiToDec(String bi)
{
long decimal = 0;
for(int y = 0; y < bi.length(); y++)
{
if(bi.charAt(y) == '1')
{
decimal = (long) (decimal + Math.pow(2, bi.length() - 1 - y));
}
}
System.out.println(decimal);
return (long) decimal;
}
public static String errorRamRangeWeb(long decimal)
{
String chipRangeFall = "";
long errorRamRange0 = 0;
long errorRamRange1 = 8589934584L;
long errorRamRange2 = 8589934585L;
long errorRamRange3 = 1717986184L;
long errorRamRange4 = 17179869185L;
long errorRamRange5 = 25769803768L;
long errorRamRange6 = 25769803769L;
long errorRamRange7 = 34359738368L;
long result = decimal;
if((result >= errorRamRange0) && (result <= errorRamRange1))
{
chipRangeFall = "1";
}
else if ((result >= errorRamRange2) && (result <= errorRamRange5))
{
chipRangeFall = "2";
}
else if ((result >= errorRamRange4) && (result <= errorRamRange3))
{
chipRangeFall = "3";
}
else if ((result >= errorRamRange6) && (result <= errorRamRange7))
{
chipRangeFall = "4";
}
else
{
System.out.println("ram chip does not exist");
}
return chipRangeFall;
}
public static void main(String[] args) throws IOException
{
readFile(convertFile);
readingLine(convertFile);
}
}
You want a %s conversion for your String argument recordingLine, not %g
recordingLine is expected to be float but found to be string.
I'm searching for ways on how to compute mathematical expressions that can compute inputs with string such as sin(90) and 10E8, until I saw these codes which I can't fully understand how these works. I want to make these as a basis because I want to improve my MDAS calculator.
I am having difficulty on understanding these codes. I'm not familiar with StringBuffer, StringTokenizer, Math.ceil, ans += mul(); , ( b.toString(), "\t" ); , but I have idea on how the trigonometric function & MDAS operation works.
Update: I've understand what is StringTokenizer but what is its relation with StringBuffer?
import java.util.*;
public class Expression {
String s, x;
double term() {
double ans = 0;
StringBuffer temp = new StringBuffer();
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
if (s.length() > 0 && s.charAt(0) == '.') {
temp.append('.');
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
if (s.length() > 0 && (s.charAt(0) == 'e' || s.charAt(0) == 'E')) {
temp.append('e');
s = s.substring(1);
temp.append(s.charAt(0));
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
ans = Double.valueOf(temp.toString()).doubleValue();
return ans;
}
double paren() {
double ans;
if (s.charAt(0) == '(') {
s = s.substring(1);
ans = add();
s = s.substring(1);
} else {
ans = term();
}
return ans;
}
double exp() {
boolean neg = false;
if (s.charAt(0) == '-') {
neg = true;
s = s.substring(1);
}
double ans = paren();
while (s.length() > 0) {
if (s.charAt(0) == '^') {
s = s.substring(1);
boolean expNeg = false;
if (s.charAt(0) == '-') {
expNeg = true;
s = s.substring(1);
}
double e = paren();
if (ans < 0) {
double x = 1;
if (Math.ceil(e) == e) {
if (expNeg)
e *= -1;
if (e == 0)
ans = 1;
else if (e > 0)
for (int i = 0; i < e; i++)
x *= ans;
else
for (int i = 0; i < -e; i++)
x /= ans;
ans = x;
} else {
ans = Math.log(-1);
}
} else if (expNeg)
ans = Math.exp(-e * Math.log(ans));
else
ans = Math.exp(e * Math.log(ans));
} else
break;
}
if (neg)
ans *= -1;
return ans;
}
double trig() {
double ans = 0;
boolean found = false;
if (s.indexOf("sin") == 0) {
s = s.substring(3);
ans = Math.sin((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("cos") == 0) {
s = s.substring(3);
ans = Math.cos((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("tan") == 0) {
s = s.substring(3);
ans = Math.tan((trig() * Math.PI) / 180);
found = true;
}
if (!found) {
ans = exp();
}
return ans;
}
double mul() {
double ans = trig();
if (s.length() > 0) {
while (s.length() > 0) {
if (s.charAt(0) == '*') {
s = s.substring(1);
ans *= trig();
} else if (s.charAt(0) == '/') {
s = s.substring(1);
ans /= trig();
} else
break;
}
}
return ans;
}
double add() {
double ans = mul();
while (s.length() > 0) {
if (s.charAt(0) == '+') {
s = s.substring(1);
ans += mul();
} else if (s.charAt(0) == '-') {
s = s.substring(1);
ans -= mul();
} else {
break;
}
}
return ans;
}
public double evaluate() {
s = x.intern();
double last = add();
return last;
}
public Expression(String s) {
StringBuffer b = new StringBuffer();
StringTokenizer t = new StringTokenizer(s, " ");
while (t.hasMoreElements())
b.append(t.nextToken());
t = new StringTokenizer(b.toString(), "\t");
b = new StringBuffer();
while (t.hasMoreElements())
b.append(t.nextToken());
x = b.toString();
}
public String toString() {
return x.intern();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter expression: ");
Expression e = new Expression(sc.nextLine());
System.out.println("\n" + e + " = " + e.evaluate() + "\n");
}
}
This program is generally reading in a string representation of a mathematical expression, and interpreting and executing that expression. As for the Java elements you're curious about:
StringBuffer is a more efficient interface to manipulating String objects.
StringTokenizer(String, String) is a class to break a string into tokens. In this constructor, the first argument is a string to break into tokens, the second argument is the delimiter used to create those tokens.
Math.ceil() returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.
StringBuffer.toString() writes out a String representing the data in the buffer
\t is a tab
+= and -= are the {add/ subtract} assignment operators, which {add / subtract} right operand to the left operand and assign the result to left operand. E.g.
int x = 0;
x += 2; // x is now 2
See javadoc for StringBuffer at http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
See javadoc for StringTokenizerat http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
I will try to comment all but the obvious lines
import java.util.*;
public class Expression {
String s, x;
double term() {
double ans = 0;
StringBuffer temp = new StringBuffer(); //Efficient than simple String
while (s.length() > 0 && Character.isDigit(s.charAt(0))) { //Check if the first character is a digit
temp.append(Integer.parseInt("" + s.charAt(0))); //If true, add to temp String
s = s.substring(1);
}
if (s.length() > 0 && s.charAt(0) == '.') {
temp.append('.');
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
if (s.length() > 0 && (s.charAt(0) == 'e' || s.charAt(0) == 'E')) {
temp.append('e');
s = s.substring(1);
temp.append(s.charAt(0));
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
ans = Double.valueOf(temp.toString()).doubleValue();
return ans;
}
double paren() {
double ans;
if (s.charAt(0) == '(') {
s = s.substring(1);
ans = add();
s = s.substring(1);
} else {
ans = term();
}
return ans;
}
double exp() {
boolean neg = false;
if (s.charAt(0) == '-') {
neg = true;
s = s.substring(1);
}
double ans = paren();
while (s.length() > 0) {
if (s.charAt(0) == '^') {
s = s.substring(1);
boolean expNeg = false;
if (s.charAt(0) == '-') {
expNeg = true;
s = s.substring(1);
}
double e = paren();
if (ans < 0) {
double x = 1;
if (Math.ceil(e) == e) { //Check Math.ceil documentation at http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil(double)
if (expNeg)
e *= -1;
if (e == 0)
ans = 1;
else if (e > 0)
for (int i = 0; i < e; i++)
x *= ans;
else
for (int i = 0; i < -e; i++)
x /= ans;
ans = x;
} else {
ans = Math.log(-1); //http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#log(double)
}
} else if (expNeg)
ans = Math.exp(-e * Math.log(ans));
else
ans = Math.exp(e * Math.log(ans)); //http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#exp(double)
} else
break;
}
if (neg)
ans *= -1;
return ans;
}
double trig() {
double ans = 0;
boolean found = false;
if (s.indexOf("sin") == 0) {
s = s.substring(3);
ans = Math.sin((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("cos") == 0) {
s = s.substring(3);
ans = Math.cos((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("tan") == 0) {
s = s.substring(3);
ans = Math.tan((trig() * Math.PI) / 180);
found = true;
}
if (!found) {
ans = exp();
}
return ans;
}
double mul() {
double ans = trig();
if (s.length() > 0) {
while (s.length() > 0) {
if (s.charAt(0) == '*') {
s = s.substring(1);
ans *= trig();
} else if (s.charAt(0) == '/') {
s = s.substring(1);
ans /= trig();
} else
break;
}
}
return ans;
}
double add() {
double ans = mul();
while (s.length() > 0) {
if (s.charAt(0) == '+') {
s = s.substring(1);
ans += mul();
} else if (s.charAt(0) == '-') {
s = s.substring(1);
ans -= mul();
} else {
break;
}
}
return ans;
}
public double evaluate() {
s = x.intern();
double last = add();
return last;
}
public Expression(String s) {
StringBuffer b = new StringBuffer();
StringTokenizer t = new StringTokenizer(s, " "); //Creates a iterable t object so you can iterate over each "word" separate by space
while (t.hasMoreElements())
b.append(t.nextToken());
t = new StringTokenizer(b.toString(), "\t");
b = new StringBuffer();
while (t.hasMoreElements())
b.append(t.nextToken());
x = b.toString();
}
public String toString() {
return x.intern();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter expression: ");
Expression e = new Expression(sc.nextLine());
System.out.println("\n" + e + " = " + e.evaluate() + "\n");
}
}
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.