NullPointerException initializing variable with string length - java

We were told to implement a method to detect if a string is a palindrome with iteration and recursion. I was successful in implementing the method with iteration but I am getting this error when I try and do it recursively.
Exception in thread "main" java.lang.NullPointerException
at recursion.RecursivePallindrome.isPallindrome(RecursivePallindrome.java:14)
at recursion.RecursivePallindrome.main(RecursivePallindrome.java:44)
I'm currently clueless on what has gone wrong.
package recursion;
public class RecursivePalindrome {
static String word;
public RecursivePalindrome(String a)
{
a = word;
}
public static boolean isPalindrome()
{
int start = 0;
int end = word.length()-1; //Line 14
char a = word.charAt(start);
char z = word.charAt(end);
Character.toLowerCase(a); Character.toLowerCase(z);
if(start >= end)
{
if(Character.isLetter(a) && Character.isLetter(z))
{
if(a == z)
{
a++;
z--;
}
else
return false;
}
else if(!Character.isLetter(a))
start++;
else if(!Character.isLetter(z))
end--;
else
return false;
}
return true;
}
public static void main(String[] args)
{
new RecursivePalindrome("testing");
if(isPalindrome())
System.out.println("Is!");
else
System.out.println("Is not!");
}
}

Try:
public RecursivePalindrome(String a) {
word = a;
}
This code works, but it isn't a recursion!
package recursion;
public class RecursivePalindrome {
static String word;
public RecursivePalindrome(String a) {
word = a;
}
public static boolean isPalindrome() {
int start = 0;
int end = word.length() - 1;
char a = word.charAt(start);
char z = word.charAt(end);
Character.toLowerCase(a);
Character.toLowerCase(z);
while (start < end) {
if (Character.isLetter(a) && Character.isLetter(z)) {
if (a == z) {
start++;
end--;
a = word.charAt(start);
z = word.charAt(end);
} else {
return false;
}
} else if (!Character.isLetter(a)) {
start++;
} else if (!Character.isLetter(z)) {
end--;
} else {
return false;
}
}
return true;
}
public static void main(String[] args) {
new RecursivePalindrome("testing");
if (isPalindrome())
System.out.println("Is!");
else
System.out.println("Is not!");
}
}

Here's a case of me not taking my time. In the constructor I got my assignment mixed up.
public RecursivePalindrome(String a)
{
a = word;
}
with the proper code being
public RecursivePalindrome(String a)
{
word = a;
}

You forgot to initialize word.
You may want to change
a = word;
to
word = a;

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

Way to access stack top element to recursively compare if both stack elements are the same

How do I access the top elements of each stack so I can compare them? I used (iTop,i2Top,nTop,n2Top) because I've been testing to make this work but I can't seem to get the right output.
What am I doing wrong?
I assumed this would work, but it's not either. Basically I want to reference the top element of stack, and compare it to the top element of stack2. Then if they are equal, pop them and do the same for the rest of the stack. At the end, if the stack is empty because all elements were the same and got popped, then it's true the stacks are the same. And push back stack 1 and stack 2.
Thank you
public Boolean sameStack(StackArray<E> s2) {
E t1, t2;
//E iTop = this.items[top];
//E i2Top= s2.items[top];
int nTop = this.top; //
int n2Top= s2.top; // nTop == n2Top is true even when elements are not equal
boolean t = true;
if(this.isEmpty() && s2.isEmpty()) {
return t;
}//if
if(this.top != s2.top) {
t = false;
return t;
}
if(this.items[top] == s2.items[s2.top]){
t1 = this.pop();
t2 = s2.pop();
t = sameStack(s2);
push(t1);
push(t2);
}
else{
t = false;
}
return t;
}
public class StackArray<E> {
private int top=-1;
private static final int MAX_ITEMS = 10;
private E items[];
#SuppressWarnings("unchecked")
public StackArray() {
items = (E[]) new Object[MAX_ITEMS];
System.out.println("Stack Created!");
}
public void push(E e) {
if (isFull()==true) {
System.out.println("Stack Full!");
}
else{
top=top+1;
items[top] = e;
}
}//Push
public E pop() {
if (isEmpty()==true) {
System.out.println("Stack Empty!");
}
else{
E e = (E) items[top];
items[top] = null;
top = top-1;
return e;
}
return null;
} //pop
public boolean isFull() {
if (top == items.length-1) {
return true;
}
return false;
} //isFull
public boolean isEmpty(){
if (top==-1) {
return true;
}
return false;
}//isEmpty
#Override
public String toString()
{
System.out.println("Array:");
System.out.print("{");
for(int i = 0; i < items.length ;i++) {
System.out.print(items[i]+" ");
}
System.out.print("}");
return "";
}//toString
public Boolean sameStack(StackArray<E> s2) {
E t1, t2;
//E iTop = this.items[top];
//E i2Top= s2.items[top];
int nTop = this.top; //
int n2Top= s2.top; // nTop == n2Top is true even when elements are not equal
boolean t = true;
if(this.isEmpty() && s2.isEmpty()) {
return t;
}//if
//This is the part I need to compare the elements
if(nTop == n2Top) {
t1 = this.pop()
t2 = s2.pop();
// t = sameStack(s2);
// push(t1);
// s2.push(t2);
}
return t;
}
public static void main(String[] args)
{
// Code reference for sameStack method
StackArray<Integer> stack = new StackArray<Integer>();
StackArray<Integer> stack2 = new StackArray<Integer>();
stack.push(111);
stack.push(222);
stack.push(7177);
// stack.push(40);
stack2.push(444);
stack2.push(555);
stack2.push(777);
// stack2.push(40);
System.out.println(stack);
System.out.println(stack2);
// //Calling comparison method
if (stack.sameStack(stack2) == true) {
System.out.println("True, both stacks are equal.");
}//if
else {
System.out.println("False, stacks are not equal.");
}//else
System.out.println(stack);
System.out.println(stack2);
}//main
}//class
Just iterate the items array and compare the elements using equals() (not ==).
public boolean sameStack(StackArray<E> s2) {
if (this.top != s2.top) {
return false;
}
for (int i = 0; i <= this.top; i++) {
if (! this.items[i].equals(s2.items[i])) {
return false;
}
}
return true;
}
This works, because any method of StackArray can access private members of StackArray, whether it's the current instance (this) or some other instance (e.g. s2).
If you specifically need to use recursion to test equality of your stacks then an easier method would be to pass the index to the method. Then you don't need to push and pop.
public boolean equals(Stack<E> other) {
return equalsFrom(other, 0);
}
private boolean equalsFrom(Stack<E> other, int from) {
if (from >= this.top || from >= other.top)
return from >= this.top && from >= other.top;
else
return this.items[from].equals(other.items[from])
&& equalsFrom(other, from + 1);
}
Hopefully that method makes sense to you. The first branch of the if statement could be read as "if I've reached the end of either stack then I must have reached the end of both stacks for them to be equal". the second branch could be read as "if I haven't reach the end of either stack then the current element must be equal and the rest of the stacks must be equal for the entire stacks to be equal".
Spongebob meme Many Hours Later...........Figured it out by myself at last!
import java.util.NoSuchElementException;
public class StackArray<E> {
private int top=-1;
private static final int MAX_ITEMS = 10;
private E items[];
#SuppressWarnings("unchecked")
public StackArray() {
items = (E[]) new Object[MAX_ITEMS];
System.out.println("Stack Created!");
}
public void push(E e) {
if (isFull()==true) {
System.out.println("Stack Full!");
}
else{
top=top+1;
items[top] = e;
}
}
public E pop() {
if (isEmpty()==true) {
System.out.println("Stack Empty!");
}
else{
E e = (E) items[top];
items[top] = null;
top = top-1;
return e;
}
return null;
}
public boolean isFull() {
if (top == items.length-1) {
return true;
}
return false;
}
public boolean isEmpty(){
if (top==-1) {
return true;
}
return false;
}
#Override
public String toString()
{
System.out.println("Array:");
System.out.print("{");
for(int i = 0; i < items.length ;i++) {
System.out.print(items[i]+" ");
}
System.out.print("}");
return "";
}
public int peek() {
if (this.isEmpty()) throw new NoSuchElementException("Stack underflow");
//System.out.println("items[top]"+this.items[top]);
//System.out.println("e"+e);
return (int) this.items[top];
}
public Boolean sameStack(StackArray<E> s2) {
E t1, t2;
boolean t = true;
if(this.isEmpty() && s2.isEmpty()) {
return t;
}
if ((int) this.peek() == s2.peek()) {
t1 = this.pop();
t2 = s2.pop();
t = sameStack(s2);
this.push(t1);
s2.push(t2);
}
else {
t = false;
return t;
}
return t;
}
public static void main(String[] args)
{
// Code reference for sameStack method
StackArray<Integer> stack = new StackArray<Integer>();
StackArray<Integer> stack2 = new StackArray<Integer>();
stack.push(122);
stack.push(222);
stack.push(3313);
stack.push(46);
stack2.push(122);
stack2.push(222);
stack2.push(3313);
stack2.push(46);
System.out.println(stack);
System.out.println(stack2);
stack.peek();
if (stack.sameStack(stack2) == true) {
System.out.println("They are equal");
}
else {
System.out.println("They are NOT equal");
}
System.out.println(stack);
System.out.println(stack2);
//Calling comparison method
// stack.sameStack(stack2);
}
}

Any assistance for specific method calling using Driver class? (Palindrome)

Alright, so Im new to using a driver to call methods, and so far this is what ive come up with:
public boolean isPalindrome(String s)
{
int begin = 0;
int end = s.length() - 1;
while (begin < end)
{
if (s.charAt(begin) != s.charAt(end))
{
return false;
}
begin++;
end--;
}
return true;
}
How do I get my driver to print out true when they detect the String "Racecar".
Referencing can be done like:
class Palindrome {
public static void main(String[] args) {
Palindrome test1 = new Palindrome();
String str = "Racecar";
System.out.println("result: " + test1.isPalindrome(str.toLowerCase()));
}
public boolean isPalindrome(String s)
{
int begin = 0;
int end = s.length() - 1;
while (begin < end)
{
if (s.charAt(begin) != s.charAt(end))
{
return false;
}
begin++;
end--;
}
return true;
}
}
Output:
result: true

using a boolean method to return true if the string inputed is alphabetically arranged

I'm writing a program that takes a string and returns a boolean indicating whether the word is alphabetically arranged e.g. abdest, acknow, adempt etc.
My problem is that the program returns no output but just terminates... Please I would really appreciate some corrections.
Here is my code:
public class test{
public static boolean Abecedarian(String s) {
String alp="";
for(char c ='A'; c<='Z'; c++){
alp +=c;
}
if(s.equals(alp)){
return true;
}else
return false;
}
public static void main(String[] args) {
Abecedarian("victor");
}
}
Try with this:
public static void main(String[] args) {
String [] words = {"abdest", "acknow", "adempt" };
for (String word : words) {
System.out.println(" isAbecedarian '"+word+"': "+isAbecedarian(word));
}
}
public static boolean isAbecedarian(String s) {
if (s == null ) throw new IllegalArgumentException("Error");
if (s.length() < 2) return true;
char last = s.charAt(0);
char current;
for (int i = 1; i < s.length(); i++) {
current = s.charAt(i);
if (current < last) {
return false;
}
last = current;
}
return true;
}
output:
isAbecedarian 'abdest': true
isAbecedarian 'acknow': true
isAbecedarian 'adempt': true

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

Categories