Queues and Stacks - java

I'm having trouble writing a program that determines whether a string is a palindrome that gets an input string from the user while skipping whitespace characters and punctuation, and ignoring differences in case, storing each character in both a stack and a queue. I already have it determining if it's a palindrome. The part i'm having trouble in is sorting it in the queue and stack. The following is what I have right now.
import java.util.Scanner;
public class Pali
{
static int length;
static String st;
static ListStack stack = new ListStack();
static ListQueue lq = new ListQueue();
static Scanner input = new Scanner(System.in);
public static void main (String[] args)
{
text();
String s = null;
createStack(s);
String q = null;
createQueue(q);
}
public static void text()
{
String st, _n = "y";
int left, right;
Scanner scan = new Scanner (System.in);
while (_n.equalsIgnoreCase("y"))
{
System.out.println ("Enter a potential palindrome:");
st = scan.nextLine();
left = 0;
right = st.length() - 1;
while (st.charAt(left) == st.charAt(right) && left < right)
{
left++;
right--;
}
System.out.println();
if (left < right)
System.out.println ("That string is NOT a palindrome.");
else
System.out.println ("That string IS a palindrome.");
System.out.println();
System.out.print ("Test another palindrome (y/n)? ");
_n = scan.nextLine();
}
}
public static void createStack(String s)
{
for (int i = 0; i < s.length(); i++)
{
stack.push(s.charAt(i));
}
}
public static void createQueue(String q)
{
for (int i = 0; i < q.length(); i++)
{
lq.enqueue(q.charAt(i));
}
}
public static void palindrome(ListQueue l, ListStack m)
{
for(int i = 0; i < m.size();i++)
{
}
}
}

Do you need to use a stack and a queue? Or are you only doing it because someone suggested it to you?
In your current code you're not actually using the stack or queue at all, you just making them and filling them with null strings.
Your original code bit manipulating the string isn't so bad, but try to add in a step that formats your string, so you get rid of case, get rid of other anything not a letter, get rid of white space's etc etc. Get that step working, then try and check if it's a palindrome.
And no I'm not going to tell you how to do it, because I recently had to do that same thing and I know how easy it is to find...

Related

How could I get my program to check if a word is a palindrome irrespective of the case entered by the user

import java.util.Scanner;
public class Pailindrome {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter a word");
String ori = sc1.nextLine();
isPailindrome(ori);
if (isPailindrome(ori))
System.out.println(ori + "is a Pailindrome");
else
System.out.println(ori + "is NOT a Pailindrome");
}
public static boolean isPailindrome(String ori) {
int i = 0;
int j = ori.length() - 1;
while (i < j) {
if (ori.charAt(i) != ori.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}
The code works perfectly I'm just confused how I will get it to work irrespective of the case
inputted by the user. For example aBba is a palindrome but It says it's not in the code I've done. I
would like any help if possible thanks.
You can convert all of the letters to lowerCase before you start the processing.
You can write your own function or use toLowerCase() String function.
import java.util.Scanner;
public class Pailindrome {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter a word");
String ori = sc1.nextLine();
ori = ori.toLowerCase();
isPailindrome(ori);
if (isPailindrome(ori))
}
System.out.println(ori + "is a Pailindrome");
} else {
System.out.println(ori + "is NOT a Pailindrome");
}
}
public static boolean isPailindrome(String ori) {
int i = 0;
int j = ori.length() - 1;
while (i < j) {
if (ori.charAt(i) != ori.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
Take the input and call toUpper(); that way when you check to see if it is a palindrome, all of the characters are uppercase.
String ori = scr.nextLint();
if(isPalindrome(ori.toUpperCase()))
//do something
Convert all the cases to lowercase/uppercase before checking the palindrome
isPailindrome(ori.toLowerCase());
Zoom in from both ends and adjust the case as required.
public static boolean isPalindrome(String str) {
int len = str.length();
for (int i = 0; i < len >>1; i++) {
if (Character.toLowerCase(str.charAt(i)) !=
Character.toLowerCase(str.charAt(len - i - 1))) {
return false;
}
}
return true;
}

Program stops printing one character at a time from two strings after the Characters are printed from the shorter string

I have a problem with this code. Otherwise it does exactly what the title says, but if the given strings are "aa" and "bbbb", it prints just "abab" instead it should print "ababbb". The program seems to stop after the characters are printed from the shorter string. Here's the code:
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
System.out.print("Anna merkkijono: ");
String merkkijono1 = lukija.nextLine();
System.out.println("Anna toinen merkkijono: ");
String merkkijono2 = lukija.nextLine();
for (int index = 0; index < merkkijono1.length() || index < merkkijono2.length(); index++) {
if (merkkijono1.length() > index) {
System.out.print(merkkijono1.charAt(index));
if (merkkijono2.length() > index) {
System.out.print(merkkijono2.charAt(index));
}
}
}
}
}
So somehow i should make it continue even when the Characters are printed from the shorter string, any tips?
Also for some reason one of the brackets didn't fit into the code text and i wasn't able to include the java.util.Scanner and public class without turning the whole code text into a mess, sorry about that.
Move the second if-statement out of the first one.
for (int index = 0; index < merkkijono1.length() || index < merkkijono2.length(); index++) {
if (merkkijono1.length() > index) {
System.out.print(merkkijono1.charAt(index));
}
if (merkkijono2.length() > index) {
System.out.print(merkkijono2.charAt(index));
}
}
It seems the if statement was inside the wrong loop.
Here, I tested it and it works.
import java.util.Scanner;
public class Program1 {
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
System.out.print("Anna merkkijono: ");
String merkkijono1 = lukija.nextLine();
System.out.print("Anna toinen merkkijono: ");
String merkkijono2 = lukija.nextLine();
for (int i = 0; i < merkkijono1.length() || i < merkkijono2.length(); i++) {
if (merkkijono1.length() > i) {
System.out.print(merkkijono1.charAt(i));
}
if (merkkijono2.length() > i) {
System.out.print(merkkijono2.charAt(i));
}
}
}
}

How do you double each letter in a string using a for loop and an if statement in java

I need to double each letter in a string using a for loop and an if-then statement. How can you comb through a string and test if each character is a letter or a symbol like an exclamation point? And then print the string back out with each letter doubled and each exclamation point tripled.
This is what I have so far. It's unfinished and it doesn't work at all, but am I on the right track?
import java.util.Scanner;
public class DoubleLetters{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scan.nextLine();
boolean isLetter = false;
for (int i = 0; i < sentence.length(); i++){
isLetter = Character.isLetter(sentence.charAt(i));
if (i == sentence.length() || sentence.charAt(i) == ' ' || isLetter == false){
System.out.print(sentence.charAt(i) + sentence.charAt(i));
}
}
It looks like you were on the right way, then passed the right exit and carried on the wrong way.
for (int i = 0; i < sentence.length(); i++){ [...] } is a right way to iterate over a string's characters.
Character.isLetter(c) is a right way to check whether a character is a letter.
However, your condition is chaotic :
why would you make special conditions for spaces and end characters?
why is your isLetter condition negated?
I think your condition should simply be
if (isLetter) { /* print twice */ }
else if (isExclamationPoint) { /* print "thrice" */ }
else { /* print once */ }
Try this:
import java.util.*;
public class DoubleLetters{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scan.nextLine();
StringBuilder sb = new StringBuilder();
for (Character c: sentence.toCharArray()){
sb.append(c);
if(Character.isLetter(c)){
sb.append(c);
}
else if(c == '!'){
sb.append(c).append(c);
}
}
sentence = sb.toString();
System.out.println(sentence);
}
}
When manipulating strings like this, it is best to use StringBuilder, which allocates a contiguous character buffer of a given size. You can count how big your output String needs to be, and pass this size to the StringBuffer on construction.
I would also recommend continuing to call String.charAt for maximum efficiency.
You may also want to encapsulate your routine in a function. You can take the input as a CharSequence for maximum utility.
public class DoubleLetters {
private static int getRepetitionCount(char c) {
if (Character.isLetter(c)) {
return 2;
} else if (c == '!') {
return 3;
} else {
return 1;
}
}
public static String doubleLetters(CharSequence in) {
int inLength = in.length();
int outLength = 0;
for (int i = 0; i < inLength; ++i) {
outLength += getRepetitionCount(in.charAt(i));
}
StringBuilder out = new StringBuilder(outLength);
for (int i = 0; i < inLength; ++i) {
char c = in.charAt(i);
int reps = getRepetitionCount(c);
for (int r = 0; r < reps; ++r) {
out.append(c);
}
}
return out.toString();
}
public static void main(String[] args) {
String test = "hello! world!";
System.out.print(doubleLetters(test));
}
}
In this specific case, you could alternatively allocate a buffer of size 3 * inLength, which will be large enough to hold any potential output string.

Reversing a word with a Stack

I am new here and in programming as well. I am trying to study other topics alone since my instructor isn't enough help when I have a question so here it goes. I want reverse a word with a generic Stack.
My pop,push,isEmpty and peek methods work (I tested them with a simpler program I made before I tried it on this one.) and the output seems to be giving me the reversed word char by char but always giving me a null before each char!
My questions are:
Why is this happening? And even though I have an expandCapacity method to work when the capacity is at 9 but it doesn't apply when the input passes the limit.
Here's my code
package Stack;
import java.util.Scanner;
public class ReverseDriver<T> {
private static String out;
private static String in;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your sentence: ");
in = input.nextLine();
int size = in.length();
ArrayStack<Character> revStack = new ArrayStack<>(size);
for (int i = 0; i < in.length(); i++) {
char u = in.charAt(i);
revStack.Push(u);
if (in.length() > 9) {
revStack.expandCapacity();
}
}
while (!revStack.IsEmpty()) {
char u = revStack.Pop();
out = out + u;
System.out.flush();
System.out.print(out);
}
}
}
Here's the Output
run:
Enter a word:
word
nullr
nullro
nullrow
Exception in thread "main" java.lang.NullPointerException
at Stack.ReverseDriver.main(ReverseDriver.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
EDIT: here's the methods that I said that were working.
#Override
public void Push ( T element)
{
if (count == stack.length){
expandCapacity();
}
stack[++count] = element;
//System.out.println(count);
}
#Override
public String toString()
{
String result = "<top of stack>\n";
for (int index=count-1; index >= 0; index--){
result += stack[index] + "\n";
}
return result + "<bottom of stack>";
}
#Override
public boolean IsEmpty()
{ //Checks if array is empty
if(count == 0){
System.out.println("Nothing");
}
return count == 0;
}
public T Pop()
{
T output;
output = (stack[count - 1]);
count--;
return(output);
}
#Override
public T Peek()
{
//looks at the object at the top of this stack without removing it
//from the stack.
if(stack.length == 0){
// {
System.out.println("Cant peek a ghost");
}
return(stack[--count]);
}
// else
// {
// System.out.println( stack[count-1]);
// }
// }
#Override
public int Size()
{
//Sets the size of this vector
if(stack.length == 0){
System.out.println("Nothing inside");
}
System.out.println("The array's size is : " + count);
return count;
}
}
private static String out;
The value in out is null.
out = out + u;
// This is null = null + u;
Hence the null at the beginning of your output.
You simply need to create a new String object to give out an initial value:
private static String out = "";
i'm not sure why you need the ExpandCapacity bit there, this works aswell:
public static void main(String[] args)
{
String word ="reverse please";
Stack<Character> chStack = new Stack<Character>();
for (int i = 0; i < word.length(); i ++)
{
chStack.push(word.charAt(i));
}
String out = "";
while (chStack.size() != 0)
{
out += chStack.pop();
System.out.println(out);
}
}
There are a few notes:
You are not writing a generic class so drop .
Leave the iteration to for as much as possible.
Try using Java standard classes as much as possible, in this case Stack instead of ArrayStack.
You don't need to resize the stack, it will handle its size dynamically as you put more data in.
You should write the string once you are done creating it not once in every step.
Appending strings using + is very inefficient. Use StringBuilder.
Use methods they make your code readable.
Heres the code:
import java.util.Scanner;
import java.util.Stack;
public class ReverseDriver {
public static String reverse(String string) {
Stack<Character> revStack = new Stack<Character>();
for (char c : string.toCharArray()) {
revStack.push(c);
}
StringBuilder builder = new StringBuilder();
while(!revStack.isEmpty()){
builder.append(revStack.pop());
}
return builder.toString();
}
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Enter your sentence: ");
String in = input.nextLine();
System.out.println(reverse(in));
}
}

Why is my code only outputing that the string is balanced

I need the following code to have a default constructor of BalancedString that initializes str to the empty string and resets a counter to 0 The class's one arguement constructor passes a string s to str and resets counter to zero. The BalancedString class also provides a boolean method which is boolean balanced() that returns true if a string contains a balanced amount of parenthesis
import java.util.*;
public class BalancedString {
private static String str;
public BalancedString()
{
str = "";
}
public BalancedString(String s)
{
s = "";
str = s;
}
public boolean balanced(){
return true;
}
public static void main(String[] args) {
int n = 0;
CounterFancy.setCounter(n);
Scanner input = new Scanner(System.in);
System.out.println("Enter a string that has any number of Left and right Parenthesis");
String s = input.next();
if (s.indexOf('(') != -1)
CounterFancy.incCounter();
if (s.indexOf(')') != -1)
CounterFancy.decCounter();
int counterValue = CounterFancy.getCounter();
if (counterValue == 0)
System.out.println("The string is Balanced");
else
System.out.println("The string is NOT Balanced");
input.close();
}
public String getStr()
{
return str;
}
public String setStr(String s)
{
str = s;
return str;
}
}
AND the following is the other project that i got the CounterFancy classes from, but the problem is above^^ why is this only outputing that it is balanced
//Joe D'Angelo
//CSC 131-03
//Chapter 10 Programming Assignment 5a.
//Takes the user's input of whether they want the counter to be negative or positive and outputs
//10 values of the user's selected input, then restarts the counter at 0
import java.util.*;
public class CounterFancy { //I messed up the first time and had to change FancyCounter to CounterFancy that is why this is changed
private static int counter;
public CounterFancy()
{
counter = 0;
}
public CounterFancy(int n){
counter = n;
}
public static int incCounter() //inc stands for increment
{
counter++;
return counter;
}
public static int decCounter() //dec stands for decrement
{
counter--;
return counter;
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Press 1 for Possitive or Press 2 for Negative");
int reply = input.nextInt();
if (reply == 1)
{
for (int i = 1; i <=10; i ++)
System.out.println("counter: " + CounterFancy.incCounter());
CounterFancy.setCounter(5);
System.out.println("Counter: " + CounterFancy.getCounter());
}
if (reply == 2)
{
for (int i = 1; i <=10; i ++)
System.out.println("counter: " + CounterFancy.decCounter());
CounterFancy.setCounter(5);
System.out.println("Counter: " + CounterFancy.getCounter());
}
input.close();
}
public static int getCounter()
{
return counter;
}
public static void setCounter(int n)
{
counter = 0;
}
}
You are making a couple of mistakes in your BalancedString class definition. First, the str field should not be static. By making it static, all instances share the same str field.
Second, and perhaps more critical, you are not constructing your BalancedString properly. You are setting the argument back to the empty string every time!
public BalancedString(String s) {
s = ""; // THIS LINE SHOULD NOT BE HERE!
str = s;
}
Finally, your balanced() method is simply returning true regardless of the string. You need to implement some logic here.
Regarding the main program: you need to loop through all the characters, increment for each '(' and decrement for each ')' character. Instead of this:
if (s.indexOf('(') != -1)
CounterFancy.incCounter();
if (s.indexOf(')') != -1)
CounterFancy.decCounter();
You should have a loop like this:
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c == '(')
CounterFancy.incCounter();
else if (c == ')')
CounterFancy.decCounter();
}
There's a logic problem in this bit of code:
String s = input.next();
if (s.indexOf('(') != -1)
CounterFancy.incCounter();
if (s.indexOf(')') != -1)
CounterFancy.decCounter();
int counterValue = CounterFancy.getCounter();
if (counterValue == 0)
System.out.println("The string is Balanced");
else
System.out.println("The string is NOT Balanced");
You're only searching the string once for a ( and once for a ). If the string contains both a ( and a ) in any order, the counter will always count 1, then 0, and think that the parentheses are balanced.
You need to put the counting in a loop to check whether or not the parentheses are balanced. You should loop through each of the characters and check the count at each step. The parentheses are balanced if the count is non-negative at each step and ends at 0.

Categories