How do I make the method indexOfVowel to return 1 for strings such as translate? I need it to find all the consonant that is before a vowel to be moved to the end. If I changed "notVowel" to 2 the word "translate" should be "anslatetray" but it returns ranslatetay. It only checks the first letter but not the rest of the word.
private String translateWord(String word) {
String translated = "";
int vowel = 0;
int notVowel = 1;
if (vowel == indexOfVowel(word)) {
return (word + "way ");
}
if (notVowel == indexOfVowel(word)) {
return (word.substring(1) + word.substring(vowel, 1) + "ay ");
}
return translated;
}
private static int indexOfVowel(String word) {
int index = 0;
for (int i = 0; i < word.length(); i++) {
if (isVowel(word.charAt(i))) {
return i;
}
}
return word.length();
}
private static boolean isVowel(char ch) {
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
default:
return false;
}
}
}
I don't think you want indexOfVowel to return 1 specifically under any case. You want it to do what it sounds like it will do...return the index of the first vowel in the word passed to it. If the first vowel happens to be at the beginning of the word, it will return 0, otherwise it will return a non-0 value indicating the location of the first vowel. You need that location to do the right thing elsewhere. So indexOfVowel is correct as you have it.
Your problem is your use of the substring method...understanding how to use it to pick out the right portions of the target word.
Here's a modified version of your code that does the right thing, with comments to explain the two uses of substring:
public class Test {
private static String translateWord(String word) {
int i = indexOfVowel(word);
if (i == 0) { // if word starts with vowel
return (word + "way ");
}
else { // word doesn't start with a vowel
// 'i' is the position of the first vowel
// word.substring(i) = from position of first vowel to end of word
// word.substring(0, i) = from start of word to char before first vowel
return (word.substring(i) + word.substring(0, i) + "ay ");
}
}
private static int indexOfVowel(String word) {
for (int i = 0; i < word.length(); i++) {
if (isVowel(word.charAt(i))) {
return i;
}
}
return word.length();
}
private static boolean isVowel(char ch) {
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
default:
return false;
}
}
public static void main(String[] args) {
System.out.println(translateWord("action"));
System.out.println(translateWord("translate"));
System.out.println(translateWord("parachute"));
System.out.println(translateWord("scrap"));
}
}
Result:
actionway
anslatetray
arachutepay
apscray
Related
This is part of my Pig Latin. It is a method, I need to return the first vowel of the word. If there are no vowels I want to return the word length. But I have an error when I return the length of the word. The error is in "else" when returning isVowel.
private static int indexOfVowel(String word) {
int index = 0;
for (int i = 0; i < word.length(); i++)
if (isVowel(word.toLowerCase().charAt(i))) {
return index;
} else {
return isVowel(word.length());
}
}
private static boolean isVowel(char ch) {
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
return true;
default: return false;
}
}
}
You cannot pass an integer to a method that expects a character. I think what you wanted is if you didn't find a vowel anywhere in the word, you want to return the length of the word.
Therefore you need to return word.length() after the for loop is done i.e. you looked at all characters in the word and didn't find a vowel. The method needs to be written as :
private static int indexOfVowel(String word) {
int index = 0;
for (int i = 0; i < word.length(); i++)
if (isVowel(word.toLowerCase().charAt(i)))
return index;
return word.length();
}
I have two classes that do two different things. I am trying to get my FileAccess class to use my encryption class to to encode a set number of phrases in a text file. The first 10 numbers in the file give the program the key value and that should be stored as a int and what comes after the file should be stored as a array of char and those need to be called by the encryption class to code the phrase. I do not know why I can't call my encryption class and I am stumped.
Sorry for being unclear I am trying to design an code that will accept a number of phrases as input and allow the user to encrypt it through the use of an encryption key. This key should be made up of an integer number between-2000000 and +2000000.The encryption algorithm uses the key to shift the letters of the alphabet to the right or left.For example A encoded with a key of 3 would produce D three letters to its right in the alphabet. If the key is so large that the new letter goes past the end of the alphabet, the program should wrap around to a letter near the beginning of the alphabet.
The FileAccess class – This class should read several phrases from a file. The first line of the file should contain an integer indicating the number of phrases in the file. The first 10 characters of each phrase in the file should contain the encryption key to be used in the encryption and decryption process for that phrase. This class should provide a way to access this information by other classes. Finally, this class should have a second method to allow phrases to be saved into a new file. I tried to be as clear as i can now. My problem is I cant call my encode method in my encryption class
Here is the code for the File Access.
public class FileAccess {
public static String[] load(String fileName) throws IOException {
FileReader file = new FileReader(fileName); //open file for reading
BufferedReader input = new BufferedReader(file);
int sizeF = Integer.parseInt(input.readLine()); // variable for the size of the array
String infoInFile[] = new String[sizeF]; // declare and create a string array
for (int i = 0; i < sizeF; i++) { // loop to read the file into the array
infoInFile[i] = input.readLine();
}
input.close();//close the file
return infoInFile;
}
public static int[] key(String finalKey[]) {
int finaloutput[] = new int[5];
String temp;
for (int i = 0; i < finalKey.length; i++) {
temp = finalKey[i].substring(0, 11);
finaloutput[i] = Integer.parseInt(temp);
System.out.println(finaloutput[i]);
}
return finaloutput;
}
public static char[] phrase(String EndOfPhrase[]) {
char letter[] = new char[5];
for (int j = 0; j < EndOfPhrase.length; j++) {
String phrase;
phrase = EndOfPhrase[j].substring(11);
char temp = phrase.charAt(1);
letter = phrase.toCharArray();
System.out.println(letter);
}
return letter;
}
public static void main(String[] args) throws IOException {
String output[]; // call the loader
int[] keyTest;
char[] phraseTest;
String display;
output = FileAccess.load("phrase.txt");
keyTest = key(output);
phraseTest = phrase(output);
for (int i = 0; i < output.length; i++) {
}
}
}
I am not sure if I should have that for loop, but scice the encryption encode method only takes in 1 char at a time and codes I think I need a for loop to keep calling it
HERE IS THE CODE FOR THE encryption code
public class Encryption {
public static boolean isNotALetter(char character) { // returns false if the character is a letter
boolean yorn = false;
return yorn;
}
public static char encode(char letter, int key) { // returns an encrypted character
char encryptedcharacter = 0;
int truevalueofkey = 0;
int valueofletter;
int newvalueofletter;
valueofletter = Encryption.lettertovalue(letter);
truevalueofkey = key % 26;
newvalueofletter = (valueofletter + truevalueofkey)%26;
encryptedcharacter = Encryption.valueToLetter(newvalueofletter);
// add truevalueofkey to key to get
return encryptedcharacter;
}
public static char decode(char letter, int key) { // returns a decrypted character
char decodedcharacter = 0;
int dtruevalueofkey = 0;
int dvalueofletter;
int dnewvalueofletter;
dvalueofletter = Encryption.lettertovalue(letter);
dtruevalueofkey = key % 26;
dnewvalueofletter = (dvalueofletter - dtruevalueofkey)%26;
decodedcharacter = Encryption.valueToLetter(dnewvalueofletter);
return decodedcharacter;
}
public static int lettertovalue(char letter) { // get value of each letter ex A = 1
int value = 0;
// convert to string based on char
switch (letter) {
case 'a': {
value = 1;
break;
}
case 'b': {
value = 2;
break;
}
case 'c': {
value = 3;
break;
}
case 'd': {
value = 4;
break;
}
case 'e': {
value = 5;
break;
}
case 'f': {
value = 6;
break;
}
case 'g': {
value = 7;
break;
}
case 'h': {
value = 8;
break;
}
case 'i': {
value = 9;
break;
}
case 'j': {
value = 10;
break;
}
case 'k': {
value = 11;
break;
}
case 'l': {
value = 12;
break;
}
case 'm': {
value = 13;
break;
}
case 'n': {
value = 14;
break;
}
case 'o': {
value = 15;
break;
}
case 'p': {
value = 16;
break;
}
case 'q': {
value = 17;
break;
}
case 'r': {
value = 18;
break;
}
case 's': {
value = 19;
break;
}
case 't': {
value = 20;
break;
}
case 'u': {
value = 21;
break;
}
case 'v': {
value = 22;
break;
}
case 'w': {
value = 23;
break;
}
case 'x': {
value = 24;
break;
}
case 'y': {
value = 25;
break;
}
case 'z': {
value = 26;
break;
}
}
return value;
}
public static char valueToLetter(int value) {
char letter = 0;
if (value == 1) {
letter = 'a';
}
if (value == 2) {
letter = 'b';
}
if (value == 3) {
letter = 'c';
}
if (value == 4) {
letter = 'd';
}
if (value == 5) {
letter = 'e';
}
if (value == 6) {
letter = 'f';
}
if (value == 7) {
letter = 'g';
}
if (value == 8) {
letter = 'h';
}
if (value == 9) {
letter = 'i';
}
if (value == 10) {
letter = 'j';
}
if (value == 11) {
letter = 'k';
}
if (value == 12) {
letter = 'l';
}
if (value == 13) {
letter = 'm';
}
if (value == 14) {
letter = 'n';
}
if (value == 15) {
letter = 'o';
}
if (value == 16) {
letter = 'p';
}
if (value == 17) {
letter = 'q';
}
if (value == 18) {
letter = 'r';
}
if (value == 19) {
letter = 's';
}
if (value == 20) {
letter = 't';
}
if (value == 21) {
letter = 'u';
}
if (value == 22) {
letter = 'v';
}
if (value == 23) {
letter = 'w';
}
if (value == 24) {
letter = 'x';
}
if (value == 25) {
letter = 'w';
}
if (value == 26) {
letter = 'z';
}
return letter;
}
public static void main(String[] args) {
String yrn = "y";
while (yrn == "y") {
String alsdjkf = JOptionPane.showInputDialog(null, "Enter the letter");
char enchar = alsdjkf.charAt(0);
int keyr = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the key"));
char newchar = Encryption.decode(enchar, keyr);
JOptionPane.showMessageDialog(null, newchar);
yrn = JOptionPane.showInputDialog(null, "yes or no");
}
}
}
This is what is in the text file:
2
00000000003 The cook worked 12 hours in the darkened kitchen!
00000000025 Did Fred look well? That’s it!
Unfortunately it's quite hard to tell from your question what you are trying to do. I think you want each line to be interpreted as 10 digits and then a phrase to be encoded by the key represented by the digits. Assuming that's correct, I have several suggestions for changes to your code. I recommend you try these and then come back if they don't solve your problem.
FileAccess.load is unnecessary. You can use Files.lines to get all lines in a file in a single statement (use Stream.toArray if you really need it to be in an array).
The massive switch statements to just turn char to int are not needed. You can do math on char values such as letter - 'a' to simplify these.
Use a regular expression rather than decoding each line yourself. "(\\d{10}) (.*)" will read the key and phrase in a single statement.
Once you have the key and phrase you can call your "encryption" code for each line.
And just a warning: if you come back and say "I'm not allowed to use X or Y in my answer" then my comment will be "that would have been useful to know before I put time into trying to help you"!
I have written a java code to test if an expression is balanced or not, that is, this program checks if the characters '(', '{' and '[' have a corresponding delimiter or not. However I am unable to get the required answer. There is something wrong and I am unable to figure it out and hence would need your help. Here is the code.
package z_Stack_InfixToPostfix;
import java.util.Stack;
public class Driver_InfixToPostfix {
public static void main(String[] args) {
String s="(a+b)";
System.out.println(checkBalance(s));
}
public static boolean checkBalance(String expression){
boolean isBalanced=true;
Stack<Character> myStack=new Stack<Character>();
int length=expression.length();
int i=0;
while(isBalanced && i<length){
switch(expression.charAt(i)){
case '(': case '{': case '[' :
myStack.push(expression.charAt(i));
break;
case ')': case '}': case ']':
if(myStack.isEmpty()){
isBalanced=false;
}
else{
char opendelimiter=myStack.pop();
if(opendelimiter!=expression.charAt(i)){
isBalanced=false;
}
}
break;
}
i++;
}
if(!myStack.isEmpty()){
isBalanced=false;
}
return isBalanced;
}
}
char opendelimiter=myStack.pop();
if(opendelimiter!=expression.charAt(i)){
isBalanced=false;
}
Here you should check
if(openedDeimilter == '('){
if(expression.charAt(i)!=')'){
isBalanced=false;
//break;
}
}else if(openedDeimilter == '['){
if(expression.charAt(i)!=']'){
isBalanced=false;
//break;
}
}else {
if(expression.charAt(i)!='}'){
isBalanced=false;
//break;
}
}
Also once isBalanced is set to false you can skip iterating the remaining string, if it suits you.
What about a different approach using only the length of your expression without each parentheses? This will let you not use the Stack class and should be more efficient for longer expression
public static boolean checkBalance(String expression) {
String[] parentheses = new String[]{"\\(|\\)","\\[|\\]","\\{|\\}"};
int length = expression.length();
for(int i=0; i<parentheses.length; i++) {
int newLength = expression.replaceAll(parentheses[i], "").length();
int diff = length - newLength;
if(diff % 2 != 0) {
return false;
}
}
return true;
}
The double backslash are used to escape each parentheses because they are special characters
This part is wrong:
if(opendelimiter!=expression.charAt(i)){
isBalanced=false;
}
You check if two chars are equal, but the correct check should match the 2 corresponding chars: [ - ], ( - ) and { - }
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char exp[1028];
char ext[1028];
int top = -1;
//-----------------------------------------------------------------------------
push(char x){
top++;
ext[top]=x;
}
//-----------------------------------------------------------------------------------------
void pop(){
top--;
}
//--------------------------------------------------------------------------------------
main()
{
int ans;
char in='{';
char it='[';
char ie='(';
char an;'}';
char at=']';
char ae=')';
printf("\nenter your expression\n");
gets(exp);
int j=strlen(exp);
int i;
for(i=0;i<=j;i++){
if(exp[i] == in || exp[i] == it || exp[i]==ie){
push(exp[i]);
}
if(exp[i] == an ||exp[i]== at || exp[i]==ae){
pop();
}
}
if(top == -1){
printf("\nexp is balanced\n");
}
else{
printf("\nexp is unbalanced");
}
}
This question already has answers here:
How to convert a char array back to a string?
(14 answers)
Closed 9 years ago.
i am doing a porter stemmer.....the code gives me output in char array....but i need to convert that into string to proceed with futher work.....in the code i have given 2 words "looking" and "walks"....that is returned as look and walk(but in char array)...the output is printed in stem() function
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package file;
import java.util.Vector;
/**
*
* #author sky
*/
public class stemmer {
public static String line1;
private char[] b;
private int i, /* offset into b */
i_end, /* offset to end of stemmed word */
j, k;
private static final int INC = 50;
/* unit of size whereby b is increased */
public stemmer()
{
//b = new char[INC];
i = 0;
i_end = 0;
}
/**
* Add a character to the word being stemmed. When you are finished
* adding characters, you can call stem(void) to stem the word.
*/
public void add(char ch)
{
System.out.println("in add() function");
if (i == b.length)
{
char[] new_b = new char[i+INC];
for (int c = 0; c < i; c++)
new_b[c] = b[c];
b = new_b;
}
b[i++] = ch;
}
/** Adds wLen characters to the word being stemmed contained in a portion
* of a char[] array. This is like repeated calls of add(char ch), but
* faster.
*/
public void add(char[] w, int wLen)
{ if (i+wLen >= b.length)
{
char[] new_b = new char[i+wLen+INC];
for (int c = 0; c < i; c++)
new_b[c] = b[c];
b = new_b;
}
for (int c = 0; c < wLen; c++)
b[i++] = w[c];
}
public void addstring(String s1)
{
b=new char[s1.length()];
for(int k=0;k<s1.length();k++)
{
b[k] = s1.charAt(k);
System.out.println(b[k]);
}
i=s1.length();
}
/**
* After a word has been stemmed, it can be retrieved by toString(),
* or a reference to the internal buffer can be retrieved by getResultBuffer
* and getResultLength (which is generally more efficient.)
*/
public String toString() { return new String(b,0,i_end); }
/**
* Returns the length of the word resulting from the stemming process.
*/
public int getResultLength() { return i_end; }
/**
* Returns a reference to a character buffer containing the results of
* the stemming process. You also need to consult getResultLength()
* to determine the length of the result.
*/
public char[] getResultBuffer() { return b; }
/* cons(i) is true <=> b[i] is a consonant. */
private final boolean cons(int i)
{ switch (b[i])
{ case 'a': case 'e': case 'i': case 'o': case 'u': return false;
case 'y': return (i==0) ? true : !cons(i-1);
default: return true;
}
}
/* m() measures the number of consonant sequences between 0 and j. if c is
a consonant sequence and v a vowel sequence, and <..> indicates arbitrary
presence,
<c><v> gives 0
<c>vc<v> gives 1
<c>vcvc<v> gives 2
<c>vcvcvc<v> gives 3
....
*/
private final int m()
{ int n = 0;
int i = 0;
while(true)
{ if (i > j) return n;
if (! cons(i)) break; i++;
}
i++;
while(true)
{ while(true)
{ if (i > j) return n;
if (cons(i)) break;
i++;
}
i++;
n++;
while(true)
{ if (i > j) return n;
if (! cons(i)) break;
i++;
}
i++;
}
}
/* vowelinstem() is true <=> 0,...j contains a vowel */
private final boolean vowelinstem()
{ int i; for (i = 0; i <= j; i++) if (! cons(i)) return true;
return false;
}
/* doublec(j) is true <=> j,(j-1) contain a double consonant. */
private final boolean doublec(int j)
{ if (j < 1) return false;
if (b[j] != b[j-1]) return false;
return cons(j);
}
/* cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short word. e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray.
*/
private final boolean cvc(int i)
{ if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false;
{ int ch = b[i];
if (ch == 'w' || ch == 'x' || ch == 'y') return false;
}
return true;
}
private final boolean ends(String s)
{
int l = s.length();
int o = k-l+1;
if (o < 0)
return false;
for (int i = 0; i < l; i++)
if (b[o+i] != s.charAt(i))
return false;
j = k-l;
return true;
}
/* setto(s) sets (j+1),...k to the characters in the string s, readjusting
k. */
private final void setto(String s)
{ int l = s.length();
int o = j+1;
for (int i = 0; i < l; i++)
b[o+i] = s.charAt(i);
k = j+l;
}
/* r(s) is used further down. */
private final void r(String s) { if (m() > 0) setto(s); }
/* step1() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> disable
matting -> mat
mating -> mate
meeting -> meet
milling -> mill
messing -> mess
meetings -> meet
*/
private final void step1()
{
if (b[k] == 's')
{ if (ends("sses")) k -= 2; else
if (ends("ies")) setto("i"); else
if (b[k-1] != 's') k--;
}
if (ends("eed")) { if (m() > 0) k--; } else
if ((ends("ed") || ends("ing")) && vowelinstem())
{ k = j;
if (ends("at")) setto("ate"); else
if (ends("bl")) setto("ble"); else
if (ends("iz")) setto("ize"); else
if (doublec(k))
{ k--;
{ int ch = b[k];
if (ch == 'l' || ch == 's' || ch == 'z') k++;
}
}
else if (m() == 1 && cvc(k)) setto("e");
}
}
/* step2() turns terminal y to i when there is another vowel in the stem. */
private final void step2() { if (ends("y") && vowelinstem()) b[k] = 'i'; }
/* step3() maps double suffices to single ones. so -ization ( = -ize plus
-ation) maps to -ize etc. note that the string before the suffix must give
m() > 0. */
private final void step3() { if (k == 0) return; /* For Bug 1 */ switch (b[k-1])
{
case 'a': if (ends("ational")) { r("ate"); break; }
if (ends("tional")) { r("tion"); break; }
break;
case 'c': if (ends("enci")) { r("ence"); break; }
if (ends("anci")) { r("ance"); break; }
break;
case 'e': if (ends("izer")) { r("ize"); break; }
break;
case 'l': if (ends("bli")) { r("ble"); break; }
if (ends("alli")) { r("al"); break; }
if (ends("entli")) { r("ent"); break; }
if (ends("eli")) { r("e"); break; }
if (ends("ousli")) { r("ous"); break; }
break;
case 'o': if (ends("ization")) { r("ize"); break; }
if (ends("ation")) { r("ate"); break; }
if (ends("ator")) { r("ate"); break; }
break;
case 's': if (ends("alism")) { r("al"); break; }
if (ends("iveness")) { r("ive"); break; }
if (ends("fulness")) { r("ful"); break; }
if (ends("ousness")) { r("ous"); break; }
break;
case 't': if (ends("aliti")) { r("al"); break; }
if (ends("iviti")) { r("ive"); break; }
if (ends("biliti")) { r("ble"); break; }
break;
case 'g': if (ends("logi")) { r("log"); break; }
} }
/* step4() deals with -ic-, -full, -ness etc. similar strategy to step3. */
private final void step4() { switch (b[k])
{
case 'e': if (ends("icate")) { r("ic"); break; }
if (ends("ative")) { r(""); break; }
if (ends("alize")) { r("al"); break; }
break;
case 'i': if (ends("iciti")) { r("ic"); break; }
break;
case 'l': if (ends("ical")) { r("ic"); break; }
if (ends("ful")) { r(""); break; }
break;
case 's': if (ends("ness")) { r(""); break; }
break;
} }
/* step5() takes off -ant, -ence etc., in context <c>vcvc<v>. */
private final void step5()
{ if (k == 0) return; /* for Bug 1 */ switch (b[k-1])
{ case 'a': if (ends("al")) break; return;
case 'c': if (ends("ance")) break;
if (ends("ence")) break; return;
case 'e': if (ends("er")) break; return;
case 'i': if (ends("ic")) break; return;
case 'l': if (ends("able")) break;
if (ends("ible")) break; return;
case 'n': if (ends("ant")) break;
if (ends("ement")) break;
if (ends("ment")) break;
/* element etc. not stripped before the m */
if (ends("ent")) break; return;
case 'o': if (ends("ion") && j >= 0 && (b[j] == 's' || b[j] == 't')) break;
/* j >= 0 fixes Bug 2 */
if (ends("ou")) break; return;
/* takes care of -ous */
case 's': if (ends("ism")) break; return;
case 't': if (ends("ate")) break;
if (ends("iti")) break; return;
case 'u': if (ends("ous")) break; return;
case 'v': if (ends("ive")) break; return;
case 'z': if (ends("ize")) break; return;
default: return;
}
if (m() > 1) k = j;
}
/* step6() removes a final -e if m() > 1. */
private final void step6()
{ j = k;
if (b[k] == 'e')
{ int a = m();
if (a > 1 || a == 1 && !cvc(k-1)) k--;
}
if (b[k] == 'l' && doublec(k) && m() > 1) k--;
}
/** Stem the word placed into the Stemmer buffer through calls to add().
* Returns true if the stemming process resulted in a word different
* from the input. You can retrieve the result with
* getResultLength()/getResultBuffer() or toString().
*/
public void stem()
{
// step1();
// System.out.println("hello in stem");
// step2();
// step3();
// step4();
// step5();
// step6();
//
// i_end = k+1;
// i = 0;
System.out.println(i);
k = i - 1;
if (k > 1)
{
step1();
step2();
step3();
step4();
step5();
step6();
}
for(int c=0;c<=k;c++)
System.out.println(b[c]);
i_end = k+1; i = 0;
}
public static void main(String[] args)
{
stemmer s = new stemmer();
s.addstring("looking");
s.stem();
s.addstring("walks");
s.stem();
//System.out.println("Output " +s.b);
}
}
- Use Character class method toString();
Eg:
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
char c = 'a';
String s = Character.toString(c);
System.out.println(s);
}
}
- Now use this above explained method to convert all the character array items into String.
char[] data = new char[10];
String text = String.valueOf(data);
to convert a char[] to string use this way
String x=new String(char[])
example
char x[]={'a','m'};
String z=new String(x);
System.out.println(z);
output
am
char[] a = new char[10];
for(int i=0;i<10;i++)
{
a[i] = 's';
}
System.out.println(new String(a));
or
System.out.println(String.copyValueOf(a));
I am trying to check if a string is a palindrome, but it seems it does not work, because when I send a string that I know is not a palindrome, it returns that it is a palindrome, can anyone help? It also won't add to the variable counter.
package UnaryStack.RubCol1183;
public class CheckPalindrome {
static int counter = 0;
/** Decides whether the parentheses, brackets, and braces
in a string occur in left/right pairs.
#param expression a string to be checked
#return true if the delimiters are paired correctly */
public static boolean checkBalance(String expression)
{
StackInterface<Character> temporaryStack = new LinkedStack<Character>();
StackInterface<Character> reverseStack = new LinkedStack<Character>();
StackInterface<Character> originalStack = new LinkedStack<Character>();
int characterCount = expression.length();
boolean isBalanced = true;
int index = 0;
char nextCharacter = ' ';
for (;(index < characterCount); index++)
{
nextCharacter = expression.charAt(index);
switch (nextCharacter)
{
case '.': case '?': case '!': case '\'': case ' ': case ',':
break;
default:
{
{
reverseStack.push(nextCharacter);
temporaryStack.push(nextCharacter);
originalStack.push(temporaryStack.pop());
}
{
char letter1 = Character.toLowerCase(originalStack.pop());
char letter2 = Character.toLowerCase(reverseStack.pop());
isBalanced = isPaired(letter1, letter2);
if(isBalanced == false){
counter++;
}
}
break;
}
} // end switch
} // end for
return isBalanced;
} // end checkBalance
// Returns true if the given characters, open and close, form a pair
// of parentheses, brackets, or braces.
private static boolean isPaired(char open, char close)
{
return (open == close);
} // end isPaired
public static int counter(){
return counter;
}
}//end class
Your implementation seems way more complex than it needs to be.
//Check for invalid characters first if needed.
StackInterface<Character> stack = new LinkedStack<Character>();
for (char ch: expression.toCharArray()) {
Character curr = new Character(ch);
Character peek = (Character)(stack.peek());
if(!stack.isEmpty() && peek.equals(curr)) {
stack.pop();
} else {
stack.push(curr)
}
}
return stack.isEmpty();
Honestly using a stack is over kill here. I would use the following method.
int i = 0;
int j = expression.length() - 1;
while(j > i) {
if(expression.charAt(i++) != expression.charAt(j--)) return false;
}
return true;
You put exaclty the same elemets in reverseStack and originalStack, because everything you push into the temporaryStack will be immediately pushed into originalStack. This does not make sense.
reverseStack.push(nextCharacter);
temporaryStack.push(nextCharacter);
originalStack.push(temporaryStack.pop());
Therefore the expression
isBalanced = isPaired(letter1, letter2);
will always return true.
I found the errors in logic that were found inside the method checkBalace() and finished the code into a full working one. Here is what my finished code looks like:
public class CheckPalindrome {
static int counter;
/** Decides whether the parentheses, brackets, and braces
in a string occur in left/right pairs.
#param expression a string to be checked
#return true if the delimiters are paired correctly */
public static boolean checkBalance(String expression)
{
counter = 0;
StackInterface<Character> temporaryStack = new LinkedStack<Character>();
StackInterface<Character> reverseStack = new LinkedStack<Character>();
StackInterface<Character> originalStack = new LinkedStack<Character>();
boolean isBalanced = true;
int characterCount = expression.length();
int index = 0;
char nextCharacter = ' ';
for (;(index < characterCount); index++)
{
nextCharacter = expression.charAt(index);
switch (nextCharacter)
{
case '.': case '?': case '!': case '\'': case ' ': case ',':
break;
default:
{
{
reverseStack.push(nextCharacter);
temporaryStack.push(nextCharacter);
}
break;
}
} // end switch
} // end for
while(!temporaryStack.isEmpty()){
originalStack.push(temporaryStack.pop());
}
while(!originalStack.isEmpty()){
char letter1 = Character.toLowerCase(originalStack.pop());
char letter2 = Character.toLowerCase(reverseStack.pop());
isBalanced = isPaired(letter1, letter2);
if(isBalanced == false){
counter++;
}
}
return isBalanced;
} // end checkBalance
// Returns true if the given characters, open and close, form a pair
// of parentheses, brackets, or braces.
private static boolean isPaired(char open, char close)
{
return (open == close);
} // end isPaired
public static int counter(){
return counter;
}
}
I used 2 while methods outside of the for thus fixing the logic errors pointed out. I also assigned the value 0 to counter inside the method to fix a small problem I encountered. Feel free to revise the code if I still have errors, but I think I made no errors, then again, I'm a beginner.