Palindrome using Three Stacks (Java) [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have an assignment that is supposed to use three stacks to ultimately find palindromes. Two stacks will need to hold the reverse of the input sequence. I need to pop the items from one of those stacks and push them into the third stack. This will obviously create two stacks with reverse items that can be compared to see if the input string is a palindrome.
I have already written a class 'ArrayStack' and 'LinkedStack'. I am now supposed to write a class that has three ArrayStack instance variables, a constructor that takes no parameters and will create three stacks of type ArrayStack and a method that takes a string parameter and returns a boolean. The incoming string will be used to check for Palindromes. The individual characters of the string will need to pushed into one of the stacks.
After that is figured out, I need to do the same thing, but with using the 'LinkedStacked' class.
This is the code I have so far and have tried multiple things and have gotten multiple errors (NPE, etc). Any pointers / explanations / advice would be appreciated. I think I have gotten myself really confused. Thanks in advance for any help offered.
Please note I am a beginner.
public class ArrayPalindrome {
static ArrayStack one;
static ArrayStack two;
static ArrayStack three;
public ArrayPalindrome(){
this.one = one;
this.two = two;
this.three = three;
}
public static boolean isPalindrome (String input ){
String input2 = "";
for (int i = 0; i < input.length(); i++) {
char character = input.charAt(i);
one.push(character);
}
while (!one.isEmpty()) {
// add the character at the top to a string
input2 = input2 + one.pop();
}
return true;
}
public static void main(String[] args) {
if (one.equals(two)){
System.out.println("Palindrome");
}
else {
System.out.println("Not a Palindrome");
}
}

If you have a NPE in one.equals(two) is becausw one is null. One is a reference pointing to nothing, you are not setting it in your main method.
I suppose that you set this reference in the constructor of ArrayPalindrome. You have to call in your main method the constructor ArrayPalindrome.
Remeber that your constructor should be change, not to use this.one=one where you are saying the one variable has to refer to one and one is nothing. You have to create an object f.e: one=new ArrayStack().
You are not calling isPalindrom anywhere you have only defined It.

Related

Better explanation of unreachable code and getting value of int to another class

I've searched for similar posts on this matter and honestly there is a lot, but please understand that I don't. I would appreciate it if someone could explain a little better, simpler.
I am trying to write my first program. The first part of the program is to reverse the number that is entered by the user, and I don't have a problem with this. The problem is when I try to get the that reversed number into another class
Here is the code:
package secretIDpack;
import java.util.Scanner;
public class renNum {
int reverse = 0;
int storeNumber;
public int revMethod(){
Scanner in = new Scanner(System.in);
storeNumber = in.nextInt();
while(storeNumber != 0) {
reverse = reverse * 10;
reverse = reverse + storeNumber%10;
storeNumber = storeNumber/10;
} return reverse;
System.out.println(reverse);
}
}
The System.out.println part is just so I can confirm that the above code is working properly, which it is as long as I keep the return part out of the code. As soon as I put the return part in, I get the message that there is unreachable code at the System.out.println
Now you probably already see what is being done here, but I will make sure you understand. I need the value of the reversed number in another class where it will be worked on further like adding some value multiplying etc. So let's say the number entered is 1234 and when revMethod does its part it will be 4321, I need this number in this class
package secretIDpack;
public class NewSecretID {
public static void main(String[] args){
renNum revObject = new renNum();
revObject.revMethod();
System.out.println(reverse);
}
}
Now in this class I get an error that "reverse" cannot be resolved to a variable, why isn't this class pulling the "reverse" value from the previous class?
As for your first question, you have a return statement followed by a print statement. In this case, the problem is that when the return keyword is found, the execution flow will exit that method. Thus, anything which follows will never executed.
To fix this, you would simply need to invert the order of your return and print statement such that the printing will take place before returning.
As per your second question, the reverse string does not exist within your main method. It exists in some other method which you are calling, but it is never declared in your NewSecretID class, which is why you are getting that error.
Variables declared within methods are not available outside the declaring method. Same applies for class lever variables, since they are not available outside that class. Just to be clear, you can access them, just not in the way you are doing it.
To solve your second issue, just do int reverse = revObject.revMethod(). This would place whatever it is that revMethod gives back into an integer variable called reverse. For the sake of completeness you can rename reverse to anything you like. int foo = revObject.revMethod() would also work.
First part of your question:
The return statement will exit the method! That means that code after the return statement will not be executed and is therefore "unreachable". Just switch those two lines:
System.out.println(reverse);
return reverse;
Second part of your question:
The revMethod has a return value of int. To use the return value of the method you'll have to assign it to a variable in the calling method. e.g.:
int returnValue = revObject.revMethod();
System.out.println(returnValue);

Passing value of a string in an array to a method in java? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
thank you for taking the time to read this. Sorry if my question is dumb, I tried searching but couldn't quite figure out why I'm having this problem. I was trying to test some code for another application, but I'm having issues. Perhaps I just don't understand arrays properly.
I have a method named halfStepUp in a class named Transpose that, for testing purposes, should return "c#" if given "c" and "d#" if given "d". This is the code:
public class Transpose{
public static String halfStepUp(String note){
String n = null;
if (note == "c") n = "c#";
if (note == "d") n = "d"#;
return n;
}
}
I have the following code in my main method:
String [] scale = new String[2];
scale[0] = "c";
scale[1] = "d";
System.out.println(Transpose.halfStepUp(scale[0]));
This prints "null." What am I doing wrong?
I know the method works because if I use
System.out.println(Transpose.halfStepUp("c"));
It works fine. The solution is probably embarrassingly easy but I couldn't find a good way to word it when searching for help.
Thanks again for reading, and any answers are greatly appreciated!
To add a little more info to the answers you already got:
Java has two types of storage. One is the stack, which includes variable names and their values. One is the heap, that is just a huge collections of free-floating objects.
Now, if you're working with primitive types (like int, boolean or char), assigning a variable like
int myInt = 1;
pushes that variable on thje stack - the name is myInt, the value is 1.
If you, however, have an object (like strings are), assigning a variable does a little bit more.
String myString = "Hey!";
now creates an object (instance of String) somewhere on the heap. It has no name there, only some address in the memory where it can be found.
In addition to that, it pushes a variable on the stack. The name is myString - and the value is the address of the object on the heap.
So why is this relevant to comparing variables? Because == compares values of variables. ON THE STACK, that is. SO if you compare primitive types, everything works as expected. But if you're comparing Objects, == still only compares the values of the variables - which is, in that case, the addresses to the objects. If the addresses are the same, it returns true. That does mean, both variables point to the same object. If the addresses are different, == returns false., Without ever looking at the heap, where the objects really are.
An example:
String a = new String("Hey!");
String b = a;
if (a == b) System.out.println("true");
else System.out.println("false");
will echo "true" - because both variables contain the same object.
String a = new String("Hey!");
String b = new String("Hey!");
if (a == b) System.out.println("true");
else System.out.println("false");
will echo "false" - because you have two objects on the heap now, and a points to the one, while b points to the other. So while the contents of both objects may be the same, the contents of a and b on the stack are different.
Therefore, to compare any object, always use .equals() if you want to compare contents, not instance-equality.
[Addendum]:
With strings, this is even more complicated. As you already found out already,
String a = "Hey!"; // mention the difference to the example above:
String b = "Hey!"; // I did NOT use the `String()` cosntructor here!
if (a == b) System.out.println("true");
else System.out.println("false");
will actually give you "true". Now why is THAT? One might think that we still create two objects. But actually, we are not.
String is immutable. That means, once a String has been created, it cannot be modified. Ever. Don'T believe that? Take a look!
String myString = "test"; // we create one instance of String here
myString += " and more"; // we create another instance of String (" and more")
// and append that. Did we modify the instance stored in
// myString now? NO! We created a third instance that
// contains "test and more".
Therefore, there is no need to create additional instances of String with the same content - which increases performance, as Strings are widely used, in masses, so we want to have as few of them as possible.
To archive that, the JVM maintains a list of String Objects we already created. And every time we write down a String literal (that is something like "Hey!"), it looks in that lists and checks if we already created an instance that has that value. If so, it returns a pointer to that exact same instance instead of creating a new one.
And THIS is, why "Hey!" == "Hey!" will return true.
You should use the .equals() method when comparing strings, not ==. The == operator compares the references to see if they are pointing to the same underlying object. The .equals() method, compares the underlying objects to each other to see if they are semantically equivalent.
Try this instead: (edited from comments)
public class Transpose{
public static String halfStepUp(String note){
String n = null;
if ("c".equals(note)) n = "c#"; //using .equals as a string comparison
if ("d".equals(note)) n = "d#"; //not "d"#
return n;
}
}
The glitch is in this line:
if (note == "c") n = "c#";
This compares strings by address, not by value. Try using "c".equals(note) instead.
class Transpose{
public static String halfStepUp(String note){
String n = null;
if (note == "c") n = "c#";
if (note == "d") n = "d#";
return n;
}
}
public class TransposeTest {
public static void main(String... args) {
String [] scale = new String[2];
scale[0] = "c";
scale[1] = "d";
System.out.println(Transpose.halfStepUp(scale[0]));
}
}
working code

Dictionary Program using Arraylist and Text File

Currently I am writing a program, for learning purposes, that is more or less a user defined dictionary. You are given a word, and then you input the corresponding word in English, and then it should tell you whether or not it is true or false, depending on what was put in as a answer previously.
Now, the trouble I am having is that I am currently unable to figure out how to check if the user input is correct, as I do not know how to compare the 2 values within the arraylist.
Currently I have this:
public void add(String question, String answer) throws FileNotFoundException, IOException
{
wordlist.add(new WordPair(question, answer));
}
to add new elements to the array, which is just 2 strings, and then I am stuck on this:
public boolean checkGuess(String question, String quess)
{
}
which is where I want to compare the 2 strings. Any help is much appreciated.
Override the equals method in your Word class and simply do :
public boolean checkGuess(String question, String quess)
{
return wordlist.contains(new WordPair(question, quess));
}
I assumed that each question is unique.
Note that a Map would be a better implementation.
To compare two strings you would use the equals() method:
String a = "a";
String b = "a";
if(a.equals(b)){
//TRUE
}
To cycle through the array list you can use a for each loop
for(WordPair pair : wordlist){
if(guess.equals(pair.getAnswer())){
// Equals the word
}
}
alternatively equalsIgnoreCase() can be used if the capitalisation of the word is not considered important.
String a = "A";
String b = "a";
if(a.equalsIgnoreCase(b)){
// TRUE
}

Determine Subclass Type of an Object of the Parent Class

I have this problem where there are several parts in my code where I check if these certain conditions are met so that I can understand if what I am checking is of one type or the other. this ends up becoming large if else trees because I am making lots of checks, the same checks in each method, and there are several different types the thing I am checking can be. This I know can be solved using objects!
Specifically, the things I am checking are 4 string values from a file. based on these string values, the 4 strings together can make one of 3 types. Rather than making these same checks every time I need to get the type the 4 strings make up, I am wondering if I can create a general object given these 4 strings and then determine if that object is an instanceof either specific class 1, 2, or 3. Then I would be able to cast that general object to the specific object.
Say I name the general object that the 4 strings create called Sign. I would take those 4 strings and create a new Sign object:
Sign unkownType = new Sign(string1, string2, string3, string4);
I need to check which specific type of sign this sign is.
EDIT:
for more detail, the Signs I am checking are not symbols like "+" or "-", they are signs with text like you would see on the road. there are 4 lines on each sign and they need to be checked to see if each line evaluates to match a specific type of sign.
The first line of SignType1 will be different of the first line of SignType2, and I want to take those 4 lines (Strings) and pass it onto an object and use that object throughout my code to get the values from it rather than making the same checks in each method.
If you want me to show some code, I can, but it won't make much sense.
What you seem to asking for is a factory pattern
public interface ISign {
public void operation1();
public void operation2();
}
and a Factory class to generate classes based on input
public class SignGenerator {
public static ISign getSignObject(String str1,String str2, String str3, String str4) {
if(str1.equals("blah blah"))
return new FirstType();
if(str1.equals("blah blah2") && str2.equals("lorem ipsum"))
return new SecondType();
return new ThirdType();
}
}
public class FirstType implements ISign {
}
public class SecondType implements ISign {
}
public class ThirdType implements ISign {
}
Implement all Type specific logic in these classes so you can call them without checking with tons of if..else clauses first
From what I gathered from your statement.
Say: create the method that returns a certain object provided the given string is equal to whateva value you specify
//provided the objects to be returned are subtypes of Sign
public Sign getInstance(String first, String second, String third, String fourth)
{
if(first==null || second==null || third==null || fourth===null )
return null;
if(compare1.equals(first))
return new SignType1();
else
if(compare2.equals(second))
return new SignType2();
else
if(compare3.equals(third))
return new SignType3();
else
if(compare4.equals(fourth))
return new SignType4();
}
Above code checks and returns thee appropriet instance corresponding to the string passed
Hope that's what was your concern

Var-arg of object arrays vs. object array -- trying to understand a SCJP self test question

I'm having trouble understanding this question, and the explanation of the answer for an SCJP 1.6 self test question. Here is the problem:
class A { }
class B extends A { }
public class ComingThru {
static String s = "-";
public static void main(String[] args) {
A[] aa = new A[2];
B[] ba = new B[2];
sifter(aa);
sifter(ba);
sifter(7);
System.out.println(s);
}
static void sifter(A[]... a2) { s += "1"; }
static void sifter(B[]... b1) { s += "2"; }
static void sifter(B[] b1) { s += "3"; }
static void sifter(Object o) { s += "4"; }
}
What is the result? The answer is -434, but what throws me off is the book's explanation. It is vastly different than how the concept was explained earlier in the chapter.
"In general, overloaded var-args
methods are chosen last. Remember that
arrays are objects. Finally, an int
can be boxed to an Integer and then
"widened" to an Object."
Splitting that up, can someone please further define that explanation?
In general, overloaded var-args methods are chosen last.
Arrays are objects (I actually get that, but why is that relevant to this question).
An int can be boxed to an Integer and then "widened" to an Object.
Thanks!
The book is trying to explain why the first two overloads are never selected: because the var-args marker ... makes them be used only if every other possible overload fails. In this case, this doesn't happen -- the two sentences starting with "Remember" is explaining WHY it doesn't happen, why other possible overloads exists in the first and last case (the second case and its match with the 3rd overload of sifter is obvious): an array is an object, and an int can be boxened then widened to an Object, so the 4th overload matches the first and last ones of the calls to sifter.
When attempting to determine which method to invoke, the compiler first looks for non vararg method (e.g. sifter(Object)) before considering a vararg one (e.g. sifter(A[]...)), when both of the methods belong to the same class (more or less).
Since an array is an Object, the invocation of sifter(aa) will match sifter(Object), hence not even considering sifter(A[]...).
Starting from Java 5, the compiler may "box" primitive, i.e. convert primitive values (e.g. int) to their corresponding Object (e.g. Integer). So for sifter(6), the compiler converts the int 6 into an Integer 6, thus it would match the sifter(Object) method.

Categories

Resources