for-loop Java return value - java

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

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

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

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.

fibonacci recursive method with special output

I'm looking to generate a specific output with my fibonacci recursive method. I already have the recursive code. However the output should display the fibonacci number(one per line) and also the ratio of the current and previous fibonacci numbers on each line.
(if user enters 5)
Fib#1=0
Fib#2=1
Fib#3=1; 1/1=1
Fib#4=2; 2/1=2
Fib#5=3; 3/2=1
this is the code i have so far:
if(n == 0)
return "0";
else if(n == 1)
return "1";
else
return FibonacciCalc(n - 1) + FibonacciCalc(n - 2);
How do i make that output? Should i return a String or make a different print method? Thanks
The problem with this recursive function is that it would be very inefficient as it has the calculate the whole range every time. Better to do this in a loop.
int beforeLastNumber = 1;
int lastNumber = 1;
System.out.println("0");
System.out.println("1");
for(int number=2; number<max; number++) {
int nextNumber = beforeLastNumber + lastNumber;
beforeLastNumber = lastNumber;
lastNumber = nextNumber;
System.out.println(nextNumber);
}
The above keeps a running total of where we're at, which avoid recalculating a sum of lots of numbers to get the higher ones.
Try this:
public class fib {
public static int FibonnaciCalc(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return FibonnaciCalc(n - 1) + FibonnaciCalc(n - 2);
}
public static void main(String[] args) {
final List<Integer> fibList = new ArrayList<Integer>();
int limit = 5;
for (int i = 0; i < limit; i++)
fibList.add(FibonnaciCalc(i));
int tmp = 0;
for (int i=0;i<fibList.size();i++) {
tmp=i+1;
if (i <2)
System.out.println("Fib#" + tmp + "=" + fibList.get(i));
else
System.out.println("Fib#" + tmp + "=" + fibList.get(i)+"; "+fibList.get(i) +"/"+fibList.get(i-1)+"="+fibList.get(i)/fibList.get(i-1));
}
}
}
Recursive fibonacci output
class FibonacciContext {
int beforePrevious;
int previous;
public FibonacciContext(int beforePrevious, int previous) {
this.beforePrevious = beforePrevious;
this.previous = previous;
}
public int getBeforePrevious() {
return beforePrevious();
}
public int getPrevious() {
return previous;
}
public int getNext() {
return beforePrevious + previous;
}
public FibonnaciContext getNextContext() {
return new FibonnaciContext(previous, getNext());
}
}
public FibonacciContext outputFibonacciNumbers(int maxIndex) {
// 0 and 1 are 0 and 1 - non recursive termination
if (maxIndex<2) {
System.out.println(maxIndex);
return new FibonnaciContext(0, maxIndex);
}
// output all previous numbers before this one
FibonnaciContext context = outputFibonacciNumbers(maxIndex-1);
// print out this one
System.out.println(context.getNext());
// context passed back to the recursive call
return context.getNextContext();
}
Try this one:
public static void main(String[] args) {
new Main().f(5);
}
private void f(final int i) {
if (i > 2) {
f(i - 1);
System.out.println(String.format("Fib#%1$d=%2$d; %2$d/%3$d=%4$d", i, fib(i-1), fib(i-2), fib(i-1)/fib(i-2)));
} else if (i > 0) {
f(i - 1);
System.out.println(String.format("Fib#%1$d=%2$d", i, fib(i-1)));
}
}
private int fib(final int i) {
if (i == 0) {
return 0;
} else if (i == 1) {
return 1;
} else {
return fib(i - 2) + fib(i - 1);
}
}

Palindrome tester

So I have the majority of the code written and it works. Except for the iterative method keeps showing that it is not a palindrome regardless of what is typed in. I am at a loss as to how to remedy it here is the code.
//David Crouse Assignment 2
import java.util.Scanner;
public class Assignment2 {
public static boolean loop = false;
//main
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Palindrome Checker!");
do{
System.out.print("Enter a string to check if it is a palindrome. ");
System.out.print("Enter x to exit.");
String word = input.nextLine();
word = word.replaceAll("\\s","");
word = word.toLowerCase();
//Exit Program
if(word.equalsIgnoreCase("x")){
System.out.println("End of program. Good Bye!");
System.exit(0);
}
if(iterativePalindromeChecker(word)){
System.out.println("Iterative Result: Palindrome!");
}else{
System.out.println("Iterative Result: Not a palindrome");
}
if(recursivePalindromeChecker(word)){
System.out.println("Recursive Result: Palindrome!\n");
}else{
System.out.println("Recursive Result: Not a palindrome\n");
}
loop = true;
}while (loop == true);
}
//Iterative Method
public static boolean iterativePalindromeChecker(String str){
boolean result = false;
int length = str.length();
int i, begin, end, middle;
begin = 0;
end = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (str.charAt(begin) == str.charAt(end)) {
begin++;
end--;
}
else {
break;
}
}
if (i == middle + 1) {
result = false;
}
return result;
}
//Recusive Methods
public static boolean recursivePalindromeChecker(String str){
if(str.length() == 0 || str.length() == 1)
return true;
if(str.charAt(0) == str.charAt(str.length()-1))
return recursivePalindromeChecker(str.substring(1,str.length()-1));
return false;
}
}
Your iterative method never sets result to be true. Here's a modified version:
public static boolean iterativePalindromeChecker(String str){
int length = str.length();
int i, begin, end, middle;
begin = 0;
end = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (str.charAt(begin) == str.charAt(end)) {
begin++;
end--;
}
else {
return false;
}
}
return true;
}
Your iterative method does not set result = true anywhere, so it really can't help it. Although I think the iterative method could be better overall. Take a close look at what is happening in the recursive one and see if you can implement some of it (like the guard conditions) more closely in the iterative method, and keep in mind that you are not limited to a single index value in a for loop either. e.g.:
public static boolean iterativePalindromeChecker(String str) {
for(int start = 0, end = str.length() - 1; start < end; start++, end--) {
if(str.charAt(start) != str.charAt(end)) {
return false;
}
}
return true;
}
I'm guessing someone once told you that a function should only have one return point, and trying to follow that led you to using a mutable result variable which screwed you here. Using break poses the same ostensible problem anyway. Save yourself the headache and just return as soon as you know the answer.
public static boolean iterativePalindromeChecker(String str) {
int begin = 0;
int end = str.length() - 1;
while (begin < end) {
if (str.charAt(begin) != str.charAt(end)) {
return false;
}
begin++;
end--;
}
return true;
}

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