Why is my code only outputing that the string is balanced - java

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.

Related

Problem with infinitely looping text in a word generator

I'm making a Palindrome Generator. Basically the user inputs a word or sentence and the program outputs whether or not its a Palindrome, which is a word that is spelled the same forwards and backwards like "wow" or "racecar". My program works fine, however the output text will repeat itself like fifty times and I can't seem to figure out where the issue is without messing everything up. Help would be appreciated.
import javax.swing.JOptionPane;
public class palindromedectector {
public static void main(String[] args) {
String testStrings = "";
testStrings = JOptionPane.showInputDialog("Enter word: ");
for (int i = 0; i < testStrings.length(); i++)
{
System.out.print("\"" + testStrings + "\"");
if (isPalindrome(stripString(testStrings)))
System.out.println(" is a palindrome.");
else
System.out.println(" is not a palindrome.");
}
}
public static String stripString(String strip)
{
strip = strip.toUpperCase();
String stripped= "";
for (int i= 0; i< strip.length(); i++)
{
if (Character.isLetter(strip.charAt(i)))
stripped += strip.charAt(i);
}
return stripped;
}
public static boolean isPalindrome (String str)
{
boolean status = false;
if (str.length() <= 1)
status = true;
else if (str.charAt(0) == str.charAt(str.length()-1))
{
status = isPalindrome (str.substring(1, str.length()-1));
}
return status;
}
}
Main issue is that you run isPalindrome check for the same string in the loop, probably you wanted to run multiple checks
public static void main(String[] args) {
final int attempts = 5;
for (int i = 0; i < attempts; i++) {
String word = JOptionPane.showInputDialog("Enter word: ");
System.out.print("\"" + word + "\"");
if (isPalindrome(stripString(word))) {
System.out.println(" is a palindrome.");
} else {
System.out.println(" is not a palindrome.");
}
}
}
Also, the main functionality may be implemented in a shorter way:
// use regexp to get rid of non-letters
private static String stripString(String word) {
if (null == word || word.isEmpty()) {
return word;
}
return word.replaceAll("[^A-Za-z]", "").toUpperCase(); // remove all non-letters
}
// use Java Stream API to check letters using half of word length
private static boolean isPalindrome(String word) {
if (null == word) {
return false;
}
final int len = word.length();
if (len < 2) {
return true;
}
return IntStream.range(0, len/2)
.allMatch(i -> word.charAt(i) == word.charAt(len - 1 - i));
}
Basic problem: You are testing if the word is a palindrome testStrings.length() times, ie once for every letter in the word, rather than just once.
Remove the for loop in your main() method.

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.

Palindrome ... i think the error is in my if statement because it keeps putting the output as 'it's not'

most likely my error is in the if statement, i want that if the word is not a Palindrome it will display it's not.
package palindrome;
import java.util.Scanner;
/**
*
* #author
*/
public class Palindrome {
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
Integer length;
Integer lasttofirst = 0;
Integer firsttolast = 0;
Boolean result = true;
String palindrome = ("");
Scanner inputkey = new Scanner(System.in);
System.out.print("Enter a word: ");
palindrome = inputkey.nextLine();
char[] newWord = palindrome.toCharArray();
length = palindrome.length();
System.out.println("The length is: " + length);
if (newWord[firsttolast] == newWord[lasttofirst]) {
firsttolast = lasttofirst + 1;
}
if (firsttolast == lasttofirst) {
lasttofirst = firsttolast + 1;
// result = true;
}
if (newWord[lasttofirst] == newWord[firsttolast]) {
firsttolast = lasttofirst + 1;
System.out.println("It is a palindrome ");
} else {
System.out.println(" it's not");
}
}
}
You start with:
Integer lasttofirst = 0;
Integer firsttolast = 0;
and you check:
if (newWord[firsttolast] == newWord[lasttofirst])
which will always be true; so you then set:
firsttolast = lasttofirst + 1;
and check:
if (firsttolast == lasttofirst)
which will always be false (since 1 != 0) and finally you check if:
if (newWord[lasttofirst] == newWord[firsttolast])
which is the equivalent of:
if (newWord[0] == newWord[1])
so, it will be true if the first two characters are the same.
The conclusion is: you aren't checking if its a palindrome at all, all you are doing is checking the first two characters.
I would do something like:
import java.util.Scanner;
public class Palindrome {
public static boolean isPalindrome( final String string ){
if ( string == null )
return false;
for ( int i = 0, j = string.length() - 1; i < j; i++, j-- ){
if ( string.charAt(i) != string.charAt(j) )
return false;
}
return true;
}
public static void main( final String[] args ){
String input;
final Scanner scanner = new Scanner( System.in );
while ( (input = scanner.nextLine()).length() > 0 ){
System.out.println( isPalindrome( input ) );
}
}
}
Kenneth:
You need a loop to solve this problem.
Use int rather than Integer
Format your code to make it readable.
Use i++ to increment an integer and i-- to decrement.
Use camel case for variables lastToFirst. It is the Java way.
Good luck!
You could try using the StringBuilder class's reverse() method to reverse a Java String.
Then compare the two using String's equals();
String rPalindrome = new StringBuilder(palindrome).reverse().toString();
if(palindrome.equals(rPalindrome))
System.out.println("It is a palindrome ");
else
System.out.println(" it's not");
But with this you would still have issues with casing (uppercase and lowercase) and so you could use String's .toUpperCase() or .toLowerCase() methods to eliminate that problem.
For a sub-optimal, but elegant solution you can use recursion
public static boolean isPalindrome(String s) {
if (s == null)
return false;
if (s.length() < 2)
return true;
return s.charAt(0) == s.charAt(s.length() - 1) && isPalindrome(s.substring(1, s.length() - 1));
}

java.lang.NumberFormatException for input string

I'm creating a program which makes the given input string into number so that input will be coded. But I'm running into a NumberFormatException as soon as the input string gets too long. I can't see how I can fix this.
Note that I have to get substrings from the given string input, turn them into numericValues then get the sum of these two strings as an answer.
Code:
public class Puzzle {
private static char[] letters = {'a','b','c','d','e','f','g','h','i', 'j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z'};
private static String input;
private static String delimiters = "\\s+|\\+|//+|=";
public static void main(String[]args)
{
input = "youuu + are = gay"; //as soon as the substrings before = sign are
//longer than 5 characters the exception occurs
System.out.println(putValues(input));
}
//method to put numeric values for substring from input
#SuppressWarnings("static-access")
public static long putValues(String input)
{
Integer count = 0;
long answer = 0;
String first="";
String second = "";
StringBuffer sb = new StringBuffer(input);
int wordCounter = Countwords();
String[] words = countLetters();
System.out.println(input);
if(input.isEmpty())
{
System.out.println("Sisestage mingi s6na");
}
if(wordCounter == -1 ||countLetters().length < 1){
return -1;
}
for(Character s : input.toCharArray())
{
for(Character c : letters)
{
if(s.equals(c))
{
count = c.getNumericValue(c);
System.out.print(s.toUpperCase(s) +"="+ count + ", ");
}
}
if(words[0].contains(s.toString()))
{
count = count - 1;
count = s.getNumericValue(s);
//System.out.println(count);
first += count.toString();
}
if(words[3].contains(s.toString())){
count = s.getNumericValue(s);
second += count.toString();
}
}
try {
answer = Integer.parseInt(first) + Integer.parseInt(second);
} catch(NumberFormatException ex)
{
System.out.println(ex);
}
System.out.println("\n" + first + " + " + second + " = " + answer);
return answer;
}
public static int Countwords()
{
String[] countWords = input.split(" ");
int counter = countWords.length - 2;
if(counter == 0) {
System.out.println("Sisend puudu!");
return -1;
}
if(counter > 1 && counter < 3) {
System.out.println("3 sõna peab olema");
return -1;
}
if(counter > 3) {
System.out.println("3 sõna max!");
return -1;
}
return counter;
}
//method which splits input String and returns it as an Array so i can put numeric values after in the
//putValue method
public static String[] countLetters()
{
int counter = 0;
String[] words = input.split(delimiters);
for(int i = 0; i < words.length;i++) {
counter = words[i].length();
if(words[i].length() > 18) {
System.out.println("Yhe s6na maksimaalne pikkus on 18 t2hem2rki ");
}
}
return words;
}
Integers in Java (as in many languages) are limited by a minimum and maximum value.
More information on this can be found here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
You could give a meaningful error in the catch-block
You did not enter a valid 32-bit Integer value.
Or you could switch to something like a BigDecimal which can hold bigger values: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
(watch out: BigDecimal works very different from a normal int, so read the documentation wisely, and Google for examples if necessary)
EDIT: you can parse it to Long as well, if you want that: Long.parseLong(INPUT, 10);. That way you extend the limit to 64-bit.

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

Categories