Picking out parentheses out of a String in Java - java

I am new to Java and trying to finish a program that will read a statement by the user and and scan to see if the amount of LEFT parenthesis match the RIGHT. The person who started the program created a stack but never made any use of it so I left it alone since I'm not very good with stacks. However, I was able to create a loop to to go through every character in the String to find the parenthesis, compare them, then print out if they are even or not. However I am having trouble with the while loop that goes through the String to find all parentheses. It's not working for some reason and I don't understand why. Any explanation on how to make this work will be greatly appreciated.
import java.util.*
public class ParenMatch
{
public static void main (String[] args)
{
Stack s = new Stack();
String line; // the string of characters to be checked
Scanner scan = new Scanner(System.in);
System.out.println ("\nParenthesis Matching");
System.out.print ("Enter a parenthesized expression: ");
line = scan.nextLine();
char parenline[] = new char[line.length()];
int x;
while(x < parenline.length) {
parenline[x] = line.charAt(x);
x++;
}
int l,r,i,morel,morer = 0;
while (i > parenline.length) {
if (parenline[i] == "(" )
l++;
if (line.charAt(i) == ")")
r++;
i++;
}
if (l > r) {
morel = l-r;
System.out.println("There are " +morel+ " more left parentheses than right");
}
if (r > l) {
morer = r-l;
System.out.println("There are " +morer+ " more right parentheses then left");
}
if (r == l) {
System.out.println("The amount of left and right parentheses are even.");
}
}
}

You need to initialize x so for example.
int x = 0;
You cannot increment an uninitialized variable.
Also to define parenline instead of looping and adding the char at the locations in the string just using one of the strings native methods:
char parenline[] = line.toCharArray();
Sorry if i explained this badly.

You had following mistakes:
not initializing
using double quote instead of single quote
checking whether i is greather than parenline.length
This is the correct code block:
int x=0;
...
int l,r,i,morel,morer;
l=r=i=morel=morer= 0;
while (i < parenline.length) {
if (parenline[i] == '(' )
l++;
if (line.charAt(i) == ')')
r++;
i++;
}

I made some changes to your code, it works fine.
However, the approach using Stack is better because allows you not only see if the amout of parenthesis is equal, but to see if the expression is correct. For example, if you have something like that: (x+y))+(x-(y+x) then your program can't tell that this is an incorrect expression because the amount of opening and closing parenthesis is equal.
import java.util.*;
public class Stackpr {
public static void main (String[] args)
{
String line; // the string of characters to be checked
Scanner scan = new Scanner(System.in);
System.out.println ("\nParenthesis Matching");
System.out.print ("Enter a parenthesized expression: ");
line = scan.nextLine();
int l = 0;
int r = 0;
for (int i = 0; i < line.length(); i++){
if (line.charAt(i) == '(')
l++;
else if (line.charAt(i) == ')')
r++;
}
if (l > r)
System.out.println("There are " + (l-r) + " more left parentheses than right");
else if (l < r)
System.out.println("There are " + (r - l)+ " more right parentheses then left");
else
System.out.println("The amount of left and right parentheses are even.");
}
}

Related

Trying to find the numbers in a line of user input, and then save them to an array stack

For this problem, I am working on finding numbers within a formula (ex. 60 / 30) and save them to a stack. I am currently using the .isDigit method to determine whether a character is a digit or not, and then am checking each character after it to see if it is a multi-digit number or not (ex. 600 or 34). I use a substring method to cut each number from the formula and then a push method obviously to save it into the arraystack. I'm getting index out of bounds errors and don't know where I went wrong. here is the code:
public static void main (String[]args) {
System.out.println("input your formula ");
Scanner scan = new Scanner (System.in);
String input;
input = scan.nextLine();
scan.close();
System.out.println("input: " + input);
ArrayStack st = new ArrayStack();
for(int j = 0; j < input.length(); j++) {
if (Character.isDigit(input.charAt(j))) {
int cur = 0;
while (input.charAt(j + cur) != ' ') {
cur += 1;
String number = input.substring(j,cur);
st.push(number);
break;
}
}
}
while (!st.isEmpty())
{
System.out.println(st.peek());
st.pop();
}
}
}
I tried and expected to get the numbers out of the formula and put them into a stack, then print them out.

Java program keeps crashing

keeps crashing when i run it, its a palindrom tester ( if a word is the same spelt forwards and backwards) and i want it to remove any non word characters and become lower case. Can anyone spot the problem? or give some tips? im trying to avoid using any "try" "for" stuff etc.. just while and if statements for a project. here is my output:
Enter a possible palindrome :
p.oop
here it is : poop
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(Unknown Source)
at Driver.main(Driver.java:27)
import java.util.*;
public class Driver
{
public static void main(String[] args)
{
String str, another = "y";
int left, right;
Scanner scan = new Scanner(System.in);
while (another.equals("y"))
{
System.out.println("Enter a possible palindrome : ");
str = scan.nextLine();
String palindromToLowerCase = str.toLowerCase();
String finalPalindrom = palindromToLowerCase.replaceAll("\\W", "");
left = 0;
right = str.length() - 1;
System.out.println("here it is : " + finalPalindrom);
while (finalPalindrom.charAt(left) == finalPalindrom.charAt(right) && left < right)
{
str.toLowerCase();
left++;
right--;
}
System.out.println();
if (left < right)
{
System.out.println("that string is NOT a palindrom");
}
else
{
System.out.println("This string IS a palindrom");
}
}
}
}
change:
right = str.length() - 1;
to:
right = finalPalindrom.length() - 1;

Word counter Program In Java

While creating a word counter in java through collecting user input from a scanner I've been running into the error of having my program display that there was one extra word entered when there is a space entered in after the final word in the char. Is there a way to check the user input for a space and remove it before entering my word count loop?
Right after...
String userinput = wordcounter.nextLine();
... add this line:
userinput = userinput.trim();
It should fix the problem, since the function trim() gets rid of any blank spaces at the beginning or ending of the string.
Try something like this:
public static void main(String[] args) {
int word = 0;
System.out.println("Enter a string: ");
Scanner wordcounter = new Scanner(System.in);
while (wordcounter.hasNext()) {
wordcounter.next();
word++;
}
System.out.println("You hav entered " + word + " words.");
}
Moreover there are many functions in Java that you can use here to do this very easily like using string tokenizer, etc. But if you want to make changes in the above program, you could simply do a simple check statement before the main if condition that if the I == length-1, because this means that you are at the last character and there is nothing after this, for this case you could just continue or break. Hopefully I solved your query, do tell in case you need more clarification...
One possible way: use regex after you trim your input.
String text = "I turned myself into a pickle Morty! :)";
String[] words = text.split("([\\W\\s]+)");
int count = 0;
for (String word: words) {
count++;
}
System.out.println("You have entered " + count + " words!");
Scanner in = new Scanner (System.in);
System.out.println("Write something");
String x = in.nextLine();
char y;
char z;
int n =1;
boolean t = true;
boolean f = false;
boolean o = false;
for (int i = 0; i<x.length();i++){
y = x.charAt(i);
if(t){
if(' ' == y){n--;}
else if(y != ' '){ t=false; f = true;}
}
if(' ' == y){n++;}
if(o){
z = x.charAt(i-1);
if(' ' == y && ' '== z){n--;}
}
if (o){
if(' ' == y && i == x.length()-1){n--;}
}
if(f){o = true;}
}
System.out.println(n);
This actually works lol

"Exception in thread" and more

import java.util.Scanner;
public class Power1Eng {
public static void main(String[] args) {
double x, prod = 1;
int n;
String s;
Scanner input = new Scanner(System.in);
System.out.print("This program prints x(x is a real number) raised to the power of n(n is an integer).\n");
outer_loop:
while (true) {
System.out.print("Input x and n: ");
x = input.nextDouble();
n = input.nextInt();
for (int i = 1; i <= n; i++) {
prod *= x;
}
System.out.printf("%.1f raised to the power of %d is %.4f. Do you want to continue?(Y/N) ", x, n, prod);
s = input.nextLine();
if (s.charAt(0) == 'Y')
continue;
else if (s.charAt(0) == 'N')
break;
else {
inner_loop:
while (true) {
System.out.print("Wrong input. Do you want to continue?(Y/N) ");
s = input.nextLine();
if (s.charAt(0) == 'Y')
continue outer_loop;
else if (s.charAt(0) == 'N')
break outer_loop;
else
continue inner_loop;
}
}
}
}
}
There was only trivial logical error when I used just next() method, but when I changed
next() method to nextLine() method, this error shows.
How can I fix this problem?
There are two problems. The first is that your string could be empty, and then fetching the first character will give an exception.
if (s.charAt(0) == 'Y') // This will throw if is empty.
Either test the length of the string to see if there is at least one character, or just use String.startsWith instead of charAt:
if (s.startsWith('Y'))
The second problem is that you entered a new line after your first input, and nextLine reads up to the next new line character only.
You could check for an initial character count, to make sure there are the correct number of characters that you expect. i.e:
while (true)
{
// ... some code ...
if (s.length() < 1)
{
continue;
}
// ... some code ...
}
This way, you wouldn't even have to continue running the rest of the code, which if the code base were larger, would help to optimize performance.
The "red text" that you see in the console is an indication of text being sent to standard error. In this case, it is an indication that your program has crashed.
The main problem you are encountering is with this logic:
System.out.print("Input x and n: ");
x = input.nextDouble();
n = input.nextInt();
for (int i = 1; i <= n; i++) {
prod *= x;
}
System.out.printf("%.1f raised to the power of %d is %.4f. Do you want to continue?(Y/N) ", x, n, prod);
s = input.nextLine();
Suppose the user input is:
2.1 4(enter)
input.nextDouble() will take 2.1, leaving 4(enter) on the standard input stream.
input.nextInt() will take 4, leaving (enter) on the standard input stream.
input.nextLine() will take "" (empty string), finally clearing the (enter) from the initial user input of x and n.

Palindrome tester with Java, ignoring spaces and punctuation

I have the program made up until the point where it has to ignore and punctuations and spaces in the thread and I was wondering if anyone could help me with the coding for that? What I've been trying out doesn't seem to be working. Here is what I have so far:
import java.util.Scanner;
public class PalindromeTester
{
public static void main (String[] args)
{
String str, another = "y";
int left, right;
char charLeft, charRight;
Scanner scan = new Scanner (System.in);
while (another.equalsIgnoreCase("y")) // allows y or Y
{
System.out.println ("Enter a potential palindrome: ");
str = scan.nextLine();
left = 0;
right = str.length() - 1;
while (left < right)
{
charLeft = str.charAt(left);
charRight = str.charAt(right);
if (charLeft == charRight)
{
left++;
right--;
}
else if (charLeft == ',' || charLeft == '.' ||
charLeft == '-' || charLeft == ':' ||
charLeft == ';' || charLeft == ' ')
left++;
else if (charRight == ',' || charRight == '.' ||
charRight == '-' || charRight == ':' ||
charRight == ';' || charRight == ' ')
right--;
else
break;
}
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)? ");
another = scan.nextLine();
}
}
}
Just to clarify what Jim Garrison said, the regex you need is the following
String m = "Madam, I'm'',.,.'' Adam";
m = m.toLowerCase().replaceAll("\\W", "");
This will leave only letters and digits and remove whitespace and punctuation, i.e. m will become "madamimadam" and you can run you regular palindrome test on that string.
You can learn more about regular expressions here
This looks like a really old post but I think I stumbled upon a simpler solution for a palindrome test. This checks the first and last characters and moves inwards and exits the program as soon as the characters do not match.
public class CharTest {
public static void main(String[] args) {
//converts string to lowercase and replaces everything except numbers
// and alphabets
String s = "Niagara. O roar again!".toLowerCase().replaceAll("\\W", "");
int j=0;
int k = s.length() - 1;
while(j < s.length() / 2) { //loops until half the length of the string if
//even and floor value if odd.
if (s.charAt(j++) != s.charAt(k--)){//check for first and last chars
//and go inwards. if char do not match print 'Not a Palindrome' and exit
System.out.println("Not a Palindrome");
System.exit(0);}
}
System.out.println("Palindrome"); //if every chars match print "Palindrome"
}
}
This code for determine if a word is a palindrome can be much more simplified. Find updated Code
String word;
int z;
int y = 0;
int i = 0;
char letter;
Scanner input = new Scanner(System.in);
System.out.print("Enter a word: ");
word = input.nextLine();
word = word.replaceAll("\\s+", "");
word = word.toLowerCase();
z = word.length()-1;
while (i <= z){
if ((letter = word.charAt(i)) == (letter = word.charAt(z-i))){
y += 1;
}
i += 1;
}
if (y == (z+1)){
System.out.println("The word IS a palindrome");
}
else{
System.out.println("The word is NOT a palindrome");
}
}
}
You could simplify the code significantly by removing all the spaces and punctuation before you start. Look at String.replaceAll(regex,replacement). You would write a regular expression to match blanks and punctuation, and provide an empty string ("") as the replacement. This will return a new string containing the original minus the characters you want to ignore.
This is the programming assignment from the Java Software Solutions (PP3.11) that I assign my students. Ironically the teacher solution uses Character.isLetterOrDigit(___) (which is never mentioned in the book) and uses methods to get rid of spaces and punctuation (having not even taught methods at that point in the book), and char is not an official part of the AP CS subset. Silly publishers.
Look at char's documentation entry. Specifically the isLetterOrDigit method. If that method returns false, then it's punctuation or a space. There are other methods in there as well that can help with that.
Your Problem: You are not ignoring the case of the letters. So if you try Able was I, ere I saw Elba, it will not come back correctly, although it is a true palindrome.

Categories

Resources