Java program- finding if all the values in an array are equal - java

This program will print a statement for when they are all equal, but not when they aren't. What is wrong?
int k = 0;
while (k < numbers.length - 1 )
{
if(numbers[k]==numbers[k+1])
{
k++;
}
}
if(k == numbers.length - 1)
{
System.out.println("All the numbers are the same");
}
else
{
System.out.println("All the numbers are not the same");
}

You have an infinite loop, see:
int[] numbers = {3,3,5,3,3};
int k = 0;
while (k < numbers.length - 1 ) // k never be k >= numbers.length - 1
{
if(numbers[k]==numbers[k+1]) // if not, k never increase
{
k++;
}
}
if(k == numbers.length - 1)
{
System.out.println("All the numbers are the same");
}
else
{
System.out.println("All the numbers are not the same");
}
You can use following code instead of you solution:
private static boolean isEqual(int[] numbers) {
Integer oldNumber = null;
for(int number: numbers) {
if(oldNumber != null && oldNumber != number) {
return false;
}
oldNumber = number;
}
return true;
}
public static void main(String[] args) {
int[] numbers = {3,3,5,3, 3};
if(isEqual(numbers))
{
System.out.println("All the numbers are the same");
}
else
{
System.out.println("All the numbers are not the same");
}
}

Change your code to use a for loop, and break out when you find a difference:
boolean allSame = true;
for(int i = 0; i < numbers.length - 1; i++)
{
if(numbers[i]!=numbers[i+1])
{
allSame = false;
break;
}
}
if(allSame)
{
System.out.println("All the numbers are the same");
}
else
{
System.out.println("All the numbers are not the same");
}

Try this:
boolean allSame = true;
while (allSame == true) {
for (int i = 0; i < numbers.length; i++) {
if (numbers[0] != numbers[i+1]) {
allSame = false;
}
}
}
//Lets user know if array contained same elements or not
if (allSame) {
System.out.println("All the numbers are the same. ");
}
else {
System.out.println("Not all numbers are the same. ");
}
Check out the "numbers[0]" in that for loop. We can always compare all the elements to the first element because if they're not the same even once, obviously they're not all the same.

Related

Trying to find palindrome number

I am trying to find palindrome no but every time it is showing false for every no even for 121
please Help....
public boolean isPalindrome(int x) {
if(x<0 || x%10==0){
return false;
}
int rev = 0;
while(x!=0){
rev=(rev*10)+(x%10);
x/=10;
}
if(x==rev){
return true;
}
else{
return false;
}
}
enter image description here
As an option, you may create something like this:
public boolean isPalindrome(int x) {
StringBuilder sb = new StringBuilder();
sb.append(x);
return sb.toString().equals(sb.reverse().toString());
}
Because after your while loop ends, x will be 0, you have to act on a copy instead
public boolean isPalindrome(int x) {
int num = x;
if(x<0 || x%10==0){
return false;
}
int rev = 0;
while(x!=0){
rev=(rev*10)+(x%10);
x/=10;
}
if(num==rev){
return true;
}
else{
return false;
}
}
All you need to do is build the new number as you reduce the original. Then compare the two.
for (int i : new int[]{121,12321, 123,34543,20012}) {
System.out.printf("%6d - %s%n", i, isPalindrome(i));
}
public static boolean isPalindrome(int numb) {
int n = 0;
for (int b = numb; b > 0;) {
n *= 10;
n += b%10;
b/=10;
}
return n == numb;
}
Prints
121 - true
12321 - true
123 - false
34543 - true
20012 - false
Hope this is useful:
public static boolean palindrome(int n) {
int nPalindrome = 0;
int nCopy = n;
while (n != 0) {
nPalindrome = nPalindrome *10 + n % 10;
n = n / 10;
}
if (nCopy == nPalindrom) {
return true;
} else {
return false;
}
}
You function can be as simple as below
public static void main(String args[]){
int r,sum=0;
int n=454;//It is the number variable to be checked for palindrome
if(isPalindrome(n)) {
System.out.println("palindrome number ");
} else {
System.out.println("not palindrome number ");
}
}
public boolean isPalindrome(int n) {
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
return n==sum;
}

Sort array using if condition in java

Below program is in java which is suppose to sort array elements in ascending order but it is not functioning as such. Please try out the program below and explain me why it is not storing some of the values in 'second' array. Some values in second array is stored as 0. Which I couldn't able to figure. Kindly solve this program and let me know. Thank you.
public static void main(String[] args) {
int first[]={9,8,2,6,3};
int second[]=new int[5];
for(int i=0;i<first.length;i++){
int count=0;
for(int j=0;j<second.length;j++){
if(first[i]<first[j]){
count++;
}
}
if(count == 0){
second[4]=first[i];
}
if(count == 1){
second[3]=first[i];
}
if(count == 2){
second[2]=first[i];
}
if(count == 3){
second[1]=first[i];
}
if(count == 4){
second[0]=first[i];
}
System.out.print(second[i]);
}
}
Here's the code that will do what you asked for:
public class SortIt{
public static void main(String[] args){
int[] arr = {9,8,2,6,3};
boolean a = true;
int index = 0;
int arrBuffer;
int check = 0;
while(a){
if(index + 1 != arr.length){
if(arr[index] > arr[index+1]){
arrBuffer = arr[index+1];
arr[index+1] = arr[index];
arr[index] = arrBuffer;
index += 1;
check = 0;
}
else if(arr[index] <= arr[index+1]){
index += 1;
check += 1;
}
if(check == arr.length){a = false;}
}
else
index = 0;
}
System.out.print("[");
for(int i = 0; i + 1 < arr.length; i++){
System.out.print("'" + arr[i] + "', " );
}
System.out.println("'" + arr[arr.length-1] + "']");
}
}
Input:
9,8,2,6,3
Output:
['2', '3', '6', '8', '9']
public static void main(String[] args) {
int first[]={9,8,2,6,3};
int second[]=new int[5];
for(int i=0;i<first.length;i++){
int count=0;
for(int j=0;j<second.length;j++){
if(first[i]<first[j]){
count++;
}
}
if(count == 0){
second[4]=first[i];
}
if(count == 1){
second[3]=first[i];
}
if(count == 2){
second[2]=first[i];
}
if(count == 3){
second[1]=first[i];
}
if(count == 4){
second[0]=first[i];
}
//System.out.print(second[i]);
}
for(int a:second){
System.out.println(a);
}
}
you are printing array inside the loop that's why some values are printed as zeros.Her is the modified code.
public static void main(String[] args) {
int first[]={9,8,2,6,3};
int second[]=new int[5];
for(int i=0;i<first.length;i++){
int count=0;
for(int j=0;j<second.length;j++){
if(first[i]<first[j]){
count++;
}
}
if(count == 0){
second[4]=first[i];
}
if(count == 1){
second[3]=first[i];
}
if(count == 2){
second[2]=first[i];
}
if(count == 3){
second[1]=first[i];
}
if(count == 4){
second[0]=first[i];
}
}
System.out.println(new Gson().toJson(second));
}

for-loop Java return value

I am very new to Java, sorry if the question is too simple. I am trying to evaluate whether an array is part of the fibonacci sequence. I do not know how to return "true" value when the whole "for" loop does not break. Any ideas? Thank you in advance! This is what I have for now:
public boolean checkFibb(ArrayList<Integer> array1) {
int i;
int fibb;
if (array1.size() < 3) {
System.out.println("Your array is too short!");
} else {
for (i = 0; i <= array1.size() - 2; i++) {
fibb = array1.get(i + 2) - (array1.get(i + 1) + array1.get(i));
if (fibb != 0) {
System.out.println("Elements are not part of the Fibonacci sequence.");
break;
} else {
System.out.println("Elements are part of the Fibonacci sequence.");
}
}
}
return true;
}
You always return true from the method. You should do something as follows:
public boolean checkFibb(ArrayList<Integer> array1) {
int i;
int fibb;
boolean isFibb = true;
if (array1.size() < 3) {
System.out.println("Your array is too short!");
isFibb = false;
} else {
for (i = 0; i <= array1.size() - 2; i++) {
fibb = array1.get(i + 2) - (array1.get(i + 1) + array1.get(i));
if (fibb != 0) {
System.out.println("Elements are not part of the Fibonacci sequence.");
isFibb = false;
break;
} else {
System.out.println("Elements are part of the Fibonacci sequence.");
}
}
}
return isFibb;
}
What you're doing in your code is you're breaking the current iteration of the loop when you detect that the elements aren't part of a fibonacci sequence. break only stops the current iteration of the loop that you are in. What you want to do is return false from the function at this point. When you detect that the array is indeed a fibonacci sequence you would want to return true at this point.
If you array is too short, it cannot be a fibonacci sequence thus you would return false at this point.
public boolean checkFibb(ArrayList<Integer> array1) {
int i;
int fibb;
if (array1.size() < 3) {
System.out.println("Your array is too short!");
return false;
} else {
for (i = 0; i <= array1.size() - 2; i++) {
fibb = array1.get(i + 2) - (array1.get(i + 1) + array1.get(i));
if (fibb != 0) {
System.out.println("Elements are not part of the Fibonacci sequence.");
return false;
} else {
System.out.println("Elements are part of the Fibonacci sequence.");
return true;
}
}
}
}

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.

Testing parentheses in a equation using stack java

I'm writing a program that will take in an equation and check if all the parentheses line up and it will output if it is good or not.
For Ex: (3+4) is good
((3*8) is NOT Good
I'm not allowed to use java's built in push() pop() methods ext..
I have to make my own which I think I got....I think!
The problem I'm having is in the Test() method.
First I'm not sure how to write the while loop like:
while(there are still characters)
Anyway the output I'm getting is: stack is empty -1
Any help is appreciated. I'm one of the slower program learners and I couldn't be trying any harder. Thanks.
Here's what I got:
public class Stacked {
int top;
char stack[];
int maxLen;
public Stacked(int max) {
top = -1;
maxLen = max;
stack = new char[maxLen];
}
public void push(char item) {
top++;
stack[top] = item;
}
public int pop() {
//x = stack[top];
//top = top - 1;
top--;
return stack[top];
}
public boolean isStackEmpty() {
if(top == -1) {
System.out.println("Stack is empty" + top);
return true;
} else
return false;
}
public void reset() {
top = -1;
}
public void showStack() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j = top; j > -1; j--){
System.out.println(stack[j]);
}
System.out.println(" ");
}
public void showStack0toTop() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j=0; j>=top; j++){
System.out.println(stack[j]);
}
System.out.println(" ");
}
//}
public boolean test(String p ){
boolean balanced = false;
balanced = false;
//while ( )
for(char i = '('; i < p.length(); i++ ){
push('(');
}
for (char j = ')'; j < p.length(); j++){
pop();
}
if (isStackEmpty()) {
balanced = true;
//return balanced;
}
return balanced;
}
public static void main(String[] args) {
Stacked stacks = new Stacked(100);
String y = new String("(((1+2)*3)");
stacks.test(y);
//System.out.println(stacks.test(y));
}
}
Now I'm getting somewhere. I need to be pointed in the right direction again. Thanks everyone this helped big time. I still have a lot more to do but this is good for now. Eventually I need to create a two more methods: one "infix to postfix" and the other "evaluating postfix" and at the end I'll need to read in answers from a text file instead of putting my own into the main method. Thanks again much appreciated.
Unless you need to actually evaluate the equation, a stack is too complicated a solution here. You simply need a counter:
int openParentheses = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
openParentheses++;
} else if (p.charAt(i) == ')') {
openParentheses--;
}
//check if there are more closed than open
if (openParentheses < 0) {
return false;
}
}
if (openParentheses == 0) {
return true;
} else {
return false;
}
If you absolutely must use stacks, use this:
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
push('x'); //doesn't matter what character you push on to the stack
} else if (p.charAt(i) == ')') {
pop();
}
//check if there are more closed than open
if (stackIsEmpty()) {
return false;
}
}
if (isStackEmpty()) {
return true;
} else {
return false;
}
I agree with Griff except that you should include another check if you didn't have more closed parentheses than open. (x*y))( is not a valid entry.
int openParentheses = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
openParentheses++;
} else if (p.charAt(i) == ')') {
openParentheses--;
}
if(openParentheses<0)
return false;
}
if (openParentheses == 0) {
return true;
} else {
return false;
}
You may be required to use a stack, but this could be done with a simple counter. This will show you a how to iterate over the characters of a String:
boolean test(String p) {
int balance = 0;
for (int idx = 0; idx < p.length(); ++idx) {
char ch = p.charAt(idx);
if (ch == '(')
++balance;
else if (ch == ')')
--balance;
if (balance < 0)
return false;
}
return balance == 0;
}
Of course, you could replace the increment and decrement with pushes and pops, respectively, on a stack.
For parsing you can use a for loop over the index and address the character of the string at the certain index.
But you actually do not need a stack, an integer variable openBraces is sufficient:
initialize with 0
for '(' you increment the variable one
for ')' you decrement the variable one
if openBraces is <0, you immediately give an error
if at the end openBraces is not equal to 0, you give an error.
Since you should do your homework yourself, I did not post source code, only explanations ;)
I think you just need this --
for ( int i = 0 ; i < p.length(); i++ ) {
char c = p.charAt(i);
if ( c == '(' )
push('(');
else if ( c == ')' ) {
if ( isStackEmpty() ) {
// Return error here because of unbalanced close paranthesis
}
pop();
}
else {
// do nothing
}
}
You CAN use a stack if you must, but considering how simplistic this is, you just need a counter that you increment and decrement and check for 0 at the end.
If you do use a counter, you should check after every decrement if the value is less than 0. If so, throw an error.
Edited based on Ryan/Dave Ball's comments.
It could be done like this:
String equation = "(2+3))";
Integer counter = 0;
//while(equation)
for(int i=0; i<equation.length();i++)
{
if(equation.charAt(i)=='(')
{
counter++;
}
else
if(equation.charAt(i)==')')
{
counter--;
}
}
if(counter == 0)
{
System.out.println("Is good!!!");
}
else
{
System.out.println("Not good!!!");
}
}

Categories