Java Palindrome program (1 error) - java

I asked a question yesterday about palindromes and Java:
Java Palindrome Program (am I on track)?
I've made some progress so far with all your help (thank you very much again). I just need help with one more thing before I can test the code out. I'm using Eclipse and I'm getting an error on one line (I'll also include the error as a comment in the code below). I keep getting a "Cannot invoke charAt(int) on the array type String[]".
Anyone know what is going on here? It's been a while since I used Java. Used it in C.S. One about 12 months ago, then I moved on to C++ in Data Structures, then Machine Code and Assembly Language in the next course. Here's the code (I've also included the error in a comment in the code). Thanks a lot:
public class Palindrome
{
public boolean isPalindrome( String theWord )
{
for ( int i = 0; i < theWord.length( ); i++ ) {
if ( theWord.charAt(i) != theWord.charAt (theWord.length() - i - 1) ) {
return false;
}
}
return true;
}
public static void main( String [] theWord )
{
int leftPointer = 0;
int rightPointer = theWord.length - 1;
for ( int i = 0; i < theWord.length / 2; i++ ) {
while (leftPointer >= rightPointer) {
if ( theWord.charAt(i) == theWord.charAt (theWord.length - i - 1) ) { // Error: Cannot invoke charAt(int) on the array type String[]
leftPointer++;
rightPointer--;
}
System.out.println(theWord);
}
}
}
}

You are trying to access a charAt() on an String[] (A String array of the arguments passed to your program), but you need to access it on a String. I world suggest something like:
if ( theWord[i].charAt(0) == theWord[theWord.length - i - 1].charAt (0) ) {
That might help you.

charAt(int index) is applied for a String, not a String array. Your program want to decide whether a string is a palindrome, like "abcba". Instead of check whether an array of Strings are all palindrome, right? For example {"abcba", "bbc", "aba"}.

In Java (as in C++) the program received parameter list, which is the array of Strings. Thus your class should looks like below:
public class Palindrome
{
public static boolean isPalindrome( String theWord )
{
for ( int i = 0; i < theWord.length( ); i++ ) {
if ( theWord.charAt(i) != theWord.charAt (theWord.length() - i - 1) ) {
return false;
}
}
return true;
}
public static void main( String [] args )
{
String theWord = args[0]; // first word passed to the program
boolean isPalindrom = Palindrome.isPalindrome(theWord);
System.out.println(theWord + " is" + ( isPalindrom ? "" : " NOT " ) + " a Palindrome." );
}
}

You forgot the () after invoking the method .length()

public static boolean isPalindrom(String value) {
if (value == null || value.length()==0 || value.length()==1) {
return true;
}
if(value.charAt(0)!=value.charAt(value.length()-1)) {
return false;
}
StringBuilder newValue =new StringBuilder(value);
newValue = new StringBuilder(newValue.substring(1, newValue.length()));
newValue = new StringBuilder(newValue.substring(0, newValue.length()-1));
return isPalindrom(newValue.toString());
}
try this simple recursive method.

import java.util.*;
public class MyClass {
public static void main(String args[]) {
String str = "pappap";
String sp = str.toLowerCase();
char[] ch = sp.toCharArray();
int len = ch.length;
int lastIndex = ch.length-1;
int count = 1;
int first = 0;
int last = sp.length()-1;
for(; first < last ;){
if(ch[first] == ch[last] ){
first= first+1;
last= last-1;
}
else{
count = 0;
break;
}
}
String result = (count == 1) ? "Palindrome" : "Not a palindrome " ;
System.out.println(result);
}
}

Related

How to remove duplicate words in string without using array?

Is there any way we can remove duplicate words from a String without using Arrays?
For example, I have this sentence "this is java programming program",
and the output have to be "this java programming".
I see similar remove duplicate problems but all of them are using arrays.
well, in Java, Strings are actually objects wrappers for character arrays which primarily add immutability.
so, there is no actual way to not use arrays for your task.
even if you wrap your head around a solution which doesn't use any direct array creation in the code implementation, you will still be using arrays behind the scenes (if you want your solution to be optimal).
Remove duplicate words from a given string using simple way
package inffrd;
public class Q001
{
public static void removeduplicate(String input)
{
//convert the string to array by splitting it in words where space comes
String[] words=input.split(" ");
//put a for loop for outer comparison where words will start from "i" string
for(int i=0;i<words.length;i++)
{
//check if already duplicate word is replaced with null
if(words[i]!=null)
{
//put a for loop to compare outer words at i with inner word at j
for(int j =i+1;j<words.length;j++)
{
//if there is any duplicate word then make is Null
if(words[i].equals(words[j]))
{
words[j]=null;
}
}
}
}
//Print the output string where duplicate has been replaced with null
for(int k=0;k<words.length;k++)
{
//check if word is a null then don't print it
if(words[k]!=null)
{
System.out.print(words[k]+" ");
}
}
}
public static void main(String[] args)
{
String s1="i am dinesh i am kumar";
Q001.removeduplicate(s1);
}
}
Below is the updated code #Han
public class RemDup
{
public static void main ( String[] args )
{
String sentence = "this is java programming program progress";
int max_word_length = sentence.length()/2;
int min_word_length = 2;
while(max_word_length>=min_word_length)
{
int si = 0;
int ei = max_word_length;
while ( ei<sentence.length() )
{
int e=ei;
while ( e<sentence.length() )
{
int ind = sentence.indexOf ( sentence.substring ( si, ei ),e );
if ( ind!=-1 )
{
if(
sentence.substring(ind-1,ind).equals(" ")
&((ind+max_word_length)>=sentence.length()||
sentence.substring(ind+max_word_length,ind+max_word_length+1).equals(" "))
)
{
sentence = sentence.substring ( 0,ind ) +sentence.substring ( ind+max_word_length,sentence.length() );
}
e=ind+max_word_length;
}
else break;
}
si+=1;
ei+=1;
}
max_word_length--;
}
System.out.println(sentence);
}
}
Below code will help you :)
public class RemDup
{
public static void main ( String[] args )
{
String sentence = "this is java programming program";
int max_word_length = sentence.length()/2;
int min_word_length = 2;
while(max_word_length>=min_word_length)
{
int si = 0;
int ei = max_word_length;
while ( ei<sentence.length() )
{
int e=ei;
while ( e<sentence.length() )
{
int ind = sentence.indexOf ( sentence.substring ( si, ei ),e );
if ( ind!=-1 )
{
sentence = sentence.substring ( 0,ind ) +sentence.substring ( ind+max_word_length,sentence.length() );
e=ind+max_word_length;
}
else break;
}
si+=1;
ei+=1;
}
max_word_length--;
}
System.out.println(sentence);
}
}

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

Count Character Consecutively in Java

I'm trying to write a method that returns the number of times char c first appears consecutively in s, even if it's a single occurrence of the character. Even spaces break the consecutive count. So the string "I'm bad at programming." should only return 1, if char c was 'a'.
The code below compiles but doesn't print the correct answers. Just something to show my general logic when it comes to approaching this problem.
public class WordCount
{
public int countRun( String s, char c )
{
int counter = 0;
for( int i = 0; i < s.length(); i++)
/*There should be other conditions here that checks for first
appearance consecutively. I've tried my fair share, but no
luck on getting correct results.*/
{
if( s.charAt(i) == c )
{
counter += 1;
}
}
return counter;
}
public static void main( String args[] )
{
WordCount x = new WordCount();
System.out.println( x.countRun( "Add dog", 'd' ) ); //should return 2
System.out.println( x.countRun( "Add dog", 'D' ) ); //should return 0
System.out.println( x.countRun( "Hope you're happy", 'p' )); //should return 1
System.out.println( x.countRun( "CCCCCcccC", 'C' )); //should return 5
}
}
I just need a few pointers (logic-wise or code). Maybe there's a method for Strings that I've never seen before that could make my program much simpler. I have very limited knowledge in programming and in Java.
EDIT: For anyone wondering if this is part of some homework assignment or whatnot, this was a question from a very old midterm. I got it wrong but for some reason but never bothered to ask for the correct answer at the time. I looked at it today and wanted to see if I knew the answer. Looks like I don't.
You could do it in one line:
int result = s.replaceFirst(".*?(" + c + "+).*", "$1").length();
This code uses regex to essentially extract the part of s that is the first contiguous occurrences of c, then gets the length of that.
This will also work for no occurrences, yielding zero.
See live demo.
Add a flag, and break out of the loop when you have found one matching character, then find "anything else". Maybe not the most compact or elegant, but true to the original code. Tested, and produces 2,0,1,5 as expected.
public int countRun( String s, char c )
{
int counter = 0;
boolean foundOne = false;
for( int i = 0; i < s.length(); i++)
{
if( s.charAt(i) == c )
{
counter += 1;
foundOne = true;
}
else {
if(foundOne) break;
}
}
return counter;
}
It occurs to me that counter>0 is an equivalent condition to foundOne==true; that would allow you to simplify the code to:
public int countRun( String s, char c )
{
int counter = 0;
for( int i = 0; i < s.length(); i++)
{
if( s.charAt(i) == c ) counter++;
else if(counter>0) break;
}
return counter;
}
The logic is a tiny bit harder to follow this way, as the variable name foundOne is self-documenting. But per other posts, "small is beautiful" too...
Using assci array counter
public static int countRun(String s, char c) {
int[] counts = new int[256];
int count = 0;
char currChar;
for (int i = 0; i < s.length(); i++) {
currChar = s.charAt(i);
if (currChar == c) {// match
counts[c]++;
} else if (Character.isSpaceChar(currChar)) {
counts[c] = 0;// reset counter for c
} else {// no match
if (counts[c] > 0) {// return accumulated counts if you have
count = counts[c];
return count;
}
}
}
return count;
}
public class A3B2C1 {
public static void main(String[] args) {
String s = "AAABBC";
s = s + '#';//dummy char to consider the last char 'C' in the string
//without using charAt()
int count = 1;
String n="";
int i=0;
StringBuffer bf = new StringBuffer();
char c[] = s.toCharArray();
for(i=0;i< c.length-1;i++)
{
if(c[i] == c[i+1])
{
count++;
}
else
{
n = c[i] +""+count;
bf.append(n);
count=1;
}
}
System.out.println("Output: "+bf);//prints-->> Output: A3B2C1
}
}

Java equivalent for .charCodeAt()

In JavaScript, .charCodeAt() returns a Unicode value at a certain point in the string which you pass to a function. If I only had one character, I could use the code below to get the Unicode value in Java.
public int charCodeAt(char c) {
int x;
return x = (int) c;
}
If I had a string in Java, how would I get the Unicode value of one individual character within the string, like the .charCodeAt() function does for JavaScript?
Java has the same method: Character.codePointAt(CharSequence seq, int index);
String str = "Hello World";
int codePointAt0 = Character.codePointAt(str, 0);
Try this:
public int charCodeAt(String string, int index) {
return (int) string.charAt(index);
}
There is the way to filter the special characters you need. Just check the ASCII Table
Hope it helps
public class main {
public static void main(String args[]) {
String str = args[0];
String bstr = "";
String[] codePointAt = new String[str.length()];
if (str != "")
{
for (int j = 0; j < str.length(); j++)
{
int charactercode=Character.codePointAt(str, j);
//CHECK on ASCII TABLE THE SPECIAL CHARS YOU NEED
if( (charactercode>31 && charactercode<48) ||
(charactercode>57 && charactercode<65) ||
(charactercode>90 && charactercode<97) ||
(charactercode>127)
)
{
codePointAt[ j] ="&"+String.valueOf(charactercode)+";";
}
else
{
codePointAt[ j] = String.valueOf( str.charAt(j) );
}
}
for (int j = 0; j < codePointAt.length; j++)
{
System.out.println("CODE "+j+" ->"+ codePointAt[j]);
}
}
}
}
OUTPUT
call with ("TRY./&asda")
CODE 0 ->T
CODE 1 ->R
CODE 2 ->Y
CODE 3 ->&46;
CODE 4 ->&47;
CODE 5 ->&38;
CODE 6 ->a
CODE 7 ->s
CODE 8 ->d
CODE 9 ->a
short unicode = string.charAt(index);

Parameter passing in Java problems

I am new to java, and have been writing a program to check if a given string is periodic or not.A string is not periodic if it cannot be represented as a smaller string concatenated some number of times. Example "1010" is periodic but "1011" is not. Here is my code. It compiles, but the problem is that it tells every string is not periodic. I guess the problem is with the for loop in the isPeriodic function. Please help me get it correct.
import java.io.*;
import java.util.*;
public class Test {
/**
* #param args
*/
public static void main(String[] args) throws java.lang.Exception {
java.io.BufferedReader R = new java.io.BufferedReader
(new java.io.InputStreamReader(System.in));
//String st = R.readLine();
String st = "10101010";
if (isPeriodic(st) == false) {
System.out.println(" Non Periodic");
}
else {
System.out.println("Periodic");
}
}
private static boolean isPeriodic(String s)
{
String temp = s;
int i;
boolean pflag = false;
for ( i = 1; i <= (s.length()/2); i++) {
s = rotateNltr(s,i);
if (s == temp) {
pflag = true;
break;
}
}
return pflag;
}
private static String rotateNltr(String s, int n) {
if( n > s.length()) {
return null;
}
for ( int i = 0; i < n; i++) {
s = leftRotatebyOne(s);
}
//System.out.println(s);
return s;
}
private static String leftRotatebyOne(String s) {
char[] temp = s.toCharArray();
char t = temp[0];
for ( int i = 0 ; i < s.length()-1 ;i++ ) {
temp[i] = temp [i+1];
}
temp[s.length()-1] = t;
String r = new String(temp);
//System.out.println(r);
return r;
}
}
You can't compare objects (and that includes String's) with ==. You have to use the equals method.
Unlike C++ (which I assume is your language of preference) Java doesn't allow comparing String objects with the == operator. Use the equals method to compare the strings.
if (s.equals(temp)) {
pflag = true;
break;
}
In your isPeriodic() the check you are doing is wrong. Do it as below:
if (s.equals(temp)) {
pflag = true;
break;
}
s.equal(temp) alone wont solve the problem, yes it will make the code execute correctly for the input as given in Main method but for 1010, 1011 it wont.
Try using this method :
private static boolean isPeriodic(String s) {
String temp = s;
int i;
boolean pflag = false;
for (i = 1; i <= (s.length() / 2); i++) {
s = leftRotatebyOne(s);
if (s.equals(temp)) {
pflag = true;
break;
}
}
return pflag;
}
This will ensure that for all combination this program works.

Categories