String index out of range in jva - java

A string is a palindrome if it is spelled the same way backward and
forward.
Examples of palindromes include “Radar” and “Dammit, I’m mad!”.
Write a java program, PalindromeTester, that asks the user to enter a
word or sentence and then checks whether the entered string is a
palindrome or not.
Spaces, nonalphabetics (.,!:?-()\";), and case within the string have
to be ignored e.g., "Drab as a fool, aloof as a bard." is a
palindrome.
Your implementation should define and use the method isPalindrome to
test if a certain string is a palindrome. The signature of the
isPalindrome method is as follows:
boolean isPalindrome(String)
Following is a sample run of the program. The user’s input is shown in bold.
java PalindromeTester
Introduction to Computer Programming (CMPS 200)
Spring 2015-16 2 of 3
Enter a string: I love CMPS 200
The string "I love CMPS 200" is NOT a palindrome.
This is the code I made, it keeps giving me an error.
I would like to know what my error is and whether there's a faster easier way of writing this code
import java.util.Scanner;
public class PalindromeTester {
public static void main (String args []) {
Scanner console = new Scanner(System.in);
System.out.println("Enter a string: ");
String palindrome = console.next();
if (isPalindrome (palindrome)) {
System.out.print("The string \""+palindrome+" is a palindrome.");
} else {
System.out.print("The string \""+palindrome+" is NOT a palindrome.");
}
}
public static boolean isPalindrome (String palindrome) {
int constant = 1;
for (int i = 0 ; i <= (palindrome.length()-1) ; i++) {
for (int z= (palindrome.length()-1);i >= 0; i--) {
if (palindrome.charAt(i) <'#'||'Z'<palindrome.charAt(i)&&palindrome.charAt(i)<'`'||'['<palindrome.charAt(i)&&palindrome.charAt(i)<'{') {
i=i+1;
}
if (palindrome.charAt(z)<'#'||'Z'<palindrome.charAt(z)&&palindrome.charAt(z)<'`'||'['<palindrome.charAt(z)&&palindrome.charAt(z)<'{') {
z=z+1;
}
if (palindrome.charAt(i)==(palindrome.charAt(z))) {
constant = constant * 1;
} else {
constant = constant * 0;
}
}
}
if (constant == 0 ) {
return false;
} else {
return true;
}
}
}

One approach would be to strip the non alpha characters out of the string. Then check if the string is the same as itself reversed (while upper case):
public static boolean isPalindrome(String palindrome) {
StringBuilder sanitisedString = new StringBuilder();
for(char c : palindrome.toCharArray()) {
if(Character.isLetter(c)) {
sanitisedString.append(c);
}
}
return sanitisedString.toString().toUpperCase().equals(sanitisedString.reverse().toString().toUpperCase());
}

Index out of range is caused by palindrome.charAt(z)) after z = z + 1;
Keep simple :
public static boolean isPalindrome(String palindrome)
{
palindrome = palindrome.replaceAll("\\W", ""); // remove all non word character
palindrome = palindrome.toLowerCase();
int size = palindrome.length();
int halfSize = size / 2;
for (int i = 0; i < halfSize; i++)
{
if(palindrome.charAt(i) != palindrome.charAt(size - i - 1))
return false;
}
return true;
}

Why not just make a new String and save the reversed source(String) in it.
public static boolean readstring(String s)
{
String b = "";
for (int i= s.length() -1; i >=0 ;i--)
{
b = b + s.charAt(i);
}
System.out.print(b +" and "+ s +" ");
return b == s || b.Equals(s);
}
EDIT: Hopefully this meets the requirements, by the way dont use the word "ignore" but "allow"

public boolean isPalindrome(String word) {
int backward = word.length() - 1;
for (int x = 0; x < word.length(); x++) {
if (word.charAt(x)!= word.charAt(backward--)) {
return false;
}
}
return true;
}

Related

Palindrome in java

Here what I tried
sample input is "aabaa"
eg: in if condition val[0] = a[4]
if it is equal i stored it in counter variable if it is half of the length it original string it is palindrome
if it is not it is not a palindrome
I tried with my basic knowledge in java if there is any errors let me know
boolean solution(String inputString) {
int val = inputString.length();
int count = 0;
for (int i = 0; i<inputString.length(); i++) {
if(inputString.charAt(i) == inputString.charAt(val-i)) {
count = count++;
if (count>0) {
return true;
}
}
}
return true;
}
How about
public boolean isPalindrome(String text) {
String clean = text.replaceAll("\\s+", "").toLowerCase();
int length = clean.length();
int forward = 0;
int backward = length - 1;
while (backward > forward) {
char forwardChar = clean.charAt(forward++);
char backwardChar = clean.charAt(backward--);
if (forwardChar != backwardChar)
return false;
}
return true;
}
From here
In your version you compare first element with last, second with second last etc.
last element in this case is inputString.length()-1(so need to use 'inputString.charAt(val-i-1)' . If you iterate till end, then the count should be equal to length of the string.
for(int i = 0; i<inputString.length(); i++){
if(inputString.charAt(i) == inputString.charAt(val-i-1)){
count ++;
}
}
return (count==val); //true when count=val
Or alternatlively iterate till the mid point of the array, then count value is val/2.
for(int i = 0; i<inputString.length()/2; i++){
if(inputString.charAt(i) == inputString.charAt(val-i-1)){
count ++;
}
}
return (count==val/2); //true when count=val/2
There's no constraints in the question so let me throw in a more cheesy solution.
boolean isPalindrome(String in)
final String inl = in.toLowerCase();
return new StringBuilder(inl).reverse().toString().equals(inl);
}
A palindrome is a word, sentence, verse, or even a number that reads the same forward and backward. In this java solution, we’ll see how to figure out whether the number or the string is palindrome in nature or not.
Method - 1
class Main {
public static void main(String[] args) {
String str = "Nitin", revStr = "";
int strLen = str.length();
for (int i = (strLen - 1); i >=0; --i) {
revStr = revStr + str.charAt(i);
}
if (str.toLowerCase().equals(revStr.toLowerCase())) {
System.out.println(str + " is a Palindrome String.");
}
else {
System.out.println(str + " is not a Palindrome String.");
}
Method - 2
class Main {
public static void main(String[] args) {
int n = 3553, revNum = 0, rem;
// store the number to the original number
int orgNum = n;
/* get the reverse of original number
store it in variable */
while (n != 0) {
remainder = n % 10;
revNum = revNum * 10 + rem;
n /= 10;
}
// check if reversed number and original number are equal
if (orgNum == revNum) {
System.out.println(orgNum + " is Palindrome.");
}
else {
System.out.println(orgNum + " is not Palindrome.");
}

find a substring which is palindrome in given string

input is :levelmm
output is: the given string is palindrome because the given string contains level is a palindrome remain character like mm is neglected.
package example;
import java.util.Scanner;
public class exp2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("enter the string");
Scanner scan=new Scanner(System.in);
String s=scan.nextLine();
String t="";
String s1=s.substring(0, s.length()-1);
for(int i=s1.length()-1;i>=0;i--)
{
t=t+s.charAt(i);
}
if(t.equalsIgnoreCase(s1))
{
int count=t.length();
System.out.println("is palindrome"+(count-1));
}else
{
System.out.println("not a palindrome");
}
}
}
but its not working completely..
First of all, the line String s1 = s.substring(0, s.length() - 1); removes one character from your word, which is not something that looks like it's supposed to happen.
What it looks like is that you want to create every possible substring of an input and see if that is a palindrome. To see whether something is a palindrome I propose this:
private static boolean isPalindrome(String word) {
String reverseWord = "";
for (int i = word.length() - 1; i > -1; i--) {
reverseWord += word.toCharArray()[i];
}
return reverseWord.equalsIgnoreCase(word);
}
Getting every single substring is more difficult, but can be done like this:
private static String[] allSubstrings(String word) {
int amount = 0;
for (int i = 0; i < word.length() + 1; i++) {
amount += i;
}
String[] res = new String[amount];
int index = 0;
for (int i = 0; i < word.length(); i++) {
for (int j = i + 1; j < word.length() + 1; j++) {
res[index] = word.substring(i, j);
index++;
}
}
return res;
}
Now, since every word that is 1 long is a palindrome, we don't want that, so in the main method we can say a word has to be more than 1 long. This results in a main method like this:
public static void main(String[] args) {
System.out.println("enter the string");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
boolean isPal = false;
for (String word : allSubstrings(s)) {
if (word.length() > 1 && isPalindrome(word)) {
isPal = true;
}
}
if (isPal) {
System.out.println("Is palindrome");
} else {
System.out.println("Is not palindrome");
}
}
I hope this answers your question and I wish you happy coding.

Counting words in a string using methods

I have a project to make a program that takes a string as input and then prints the number of words in the string as output. We are supposed to use 3 methods in this, one to read input, one to print the output, and one to count the words.
I know I am missing something basic but I have spent hours on this and cannot figure out why the program wont run as it should. I need to keep the program pretty simple so I dont want to edit it too much, just find the issue and fix it so it will run correctly.
Example: Enter a string of text: The quick brown fox jumped over the lazy dog. 9 words
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter text: ");
String words = wordInput(in);
int count = wordCount(words);
System.out.println(words);
System.out.println(count);
printLine(count);
}
private static String wordInput(Scanner in)
{
String words = in.nextLine();
return words;
}
private static int wordCount(String words)
{
int length = words.length();
int ctr = 0;
int spot = 0;
int stop = 1;
char space = ' ';
char end = '.';
char com = ',';
char yes = '!';
char question = '?';
while (length > 0 && stop > 0)
{
if (words.charAt(spot) == space)
{
ctr++;
spot++;
}
else if (words.charAt(spot) == com)
{
spot++;
}
else if (words.charAt(spot) == yes || words.charAt(spot) == end || words.charAt(spot) == question)
{
stop = -1;
}
else if (spot > length)
{
stop = -1;
}
else
spot++;
}
return ctr + 1;
}
private static void printLine(int ctr)
{
System.out.println(ctr + " words");
}
Here is a rewritten wordCount that does as you request, minimal changes to the code. However, I am not sure it produces the answers you expect.
private static int wordCount(String words)
{
int length = words.length();
int ctr = 0;
int spot = 0;
char space = ' ';
char end = '.';
char com = ',';
char yes = '!';
char question = '?';
while (spot < length)
{
if (words.charAt(spot) == space)
{
ctr++;
spot++;
}
else if (words.charAt(spot) == com)
{
spot++;
}
else if (words.charAt(spot) == yes || words.charAt(spot) == end || words.charAt(spot) == question)
{
break;
}
else
spot++;
}
return ctr + 1;
}
However, fundamentally you are trying to count words in a string, and that is a known art. A few options and further reading:
http://www.quickprogrammingtips.com/java/find-number-of-words-in-a-string-in-java.html
Count words in a string method?
Which leads to a simpler result of:
private static int wordCount(String words) {
return words.split("\\s+").length;
}
Going on the assumption that whoever enters the string is not going to make a grammar error, try split the string at all spaces and set it equal to a string[]. Here is an example:
String temp = JOptionPane.showInputDialog(null, "Enter some text here");
String[] words = temp.split(" ");
JOptionPane.showMessage(null, String.format("Words used %d", words.length));

Palindrome detector returns true even when it's not a palindrome

I need to make sure that on every assignment that I do, I have to write my own original code and not copy someone else's. It seems harder than you would expect. I'm trying to write a palindrome detector as part of an assignment. The code is good, except for one problem. The output says it's true, even when it's not a palindrome and it begins and ends with the same character. May you please help me. Here is my code:
public static boolean isPalindrome_nr(String word){
int beginning = 0;
int end = word.length() - 1;
boolean pd = true;
for (int i = end; i>0; i--){
if(word.charAt(0) == word.charAt(word.length()-1)){
pd = true;
}
else if (word.charAt(0) != word.charAt(word.length()-i)){
pd = false;
}
}
return pd;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
System.out.println("Is the string a palindrome or not? ");
String test = scan.nextLine();
System.out.println("Answer: " + isPalindrome_nr(test));
}
The goal is to get the word test, which is not a palindrome, registered as false, abba, which is a palindrome, registered as true, and application, which is not a palindrome, registered as false.
You are only comparing the first and last characters. That's not nearly enough to determine if a String is a palindrome.
You need something like this :
pd = true;
for (int i = end; i>=0; i--){
if(word.charAt(i) != word.charAt(end-i)){
pd = false;
break;
}
}
This can be further improved, since this loop would test all the pairs twice, so it's probably enough that i ends at end/2 or (end/2)+1.
You're only checking the first and last characters. The method should look like this so that your for-loop actually does what it's supposed to:
public static boolean isPalindrome_nr(String word) {
int beginning = 0;
int end = word.length() - 1;
boolean pd = true;
for (int i = end; i > 0; i--) {
// notice the use of i in here so that it will check all opposite chars
if(word.charAt(i) == word.charAt(word.length() - 1 - i)) {
pd = true;
}
else { // don't need the else-if
pd = false;
}
}
return pd;
}
Just as an extra note, there is another way to test if a string is a palindrome or not: reverse it and test if the reversed string is equal to the original string. Like this (it's a one-liner):
public static boolean isPalindrome(String s) {
return new StringBuilder(s).reverse().toString().equals(s);
}
Or the longer way (reversing the string with a for-loop instead of using the StringBuilder#reverse() method
public static boolean isPalindrome(String s) {
StringBuilder reverseString = new StringBuilder();
// reverse the string
for (int i = s.length() - 1; i > -1; i--) {
reverseString.append(s.charAt(i));
}
// return whether or not the reversed string is equal to the original string
return reverseString.toString().equals(s);
}

How to search via character matching with a skip distance?

As the title says, I'm working on a project in which I'm searching a given text, moby dick in this case, for a key word. However instead of the word being linear, we are trying to find it via a skip distance ( instead of cat, looking for c---a---t).
I've tried multiple ways, yet can't seem to get it to actually finish one skip distance, have it not work, and call the next allowed distance (incrementing by 1 until a preset limit is reached)
The following is the current method in which this search is done, perhaps this is just something silly that I'm missing?
private int[] search()
throws IOException
{
/*
tlength is the text file length,
plength is the length of the
pattern word (cat in the original post),
text[] is a character array of the text file.
*/
int i=0, j;
int match[] = new int[2];
int skipDist = 2;
while(skipDist <= 100)
{
while(i<=tlength-(plength * skipDist))
{
j=plength-1;
while(j>=0 && pattern[j]==text[i+(j * skipDist)])j--;
if (j<0)
{
match[0] = skipDist;
match[1] = i;
return match;
}
else
{
i++;
}
}
skipDist = skipDist + 1;
}
System.out.println("There was no match!");
System.exit(0);
return match;
}
I do not know about the method you posted, but you can use this instead. I've used string and char array for this:
public boolean checkString (String s)
{
char[] check = {'c','a','t'};
int skipDistance = 2;
for(int i = 0; i< (s.length() - (skipDistance*(check.length-1))); i++)
{
boolean checkValid = true;
for(int j = 0; j<check.length; j++)
{
if(!(s.charAt(i + (j*skipDistance))==check[j]))
{
checkValid = false;
}
}
if(checkValid)
return true;
}
return false;
}
Feed the pattern to match in the char array 'check'.
String "adecrayt" evaluates true. String "cat" evaluates false.
Hope this helps.
[This part was for fixed skip distance]
+++++++++++++++++++++++++++
Now for any skip distance between 2 and 100:
public boolean checkString (String s)
{
char[] check = {'c','a','t'};
int index = 0;
int[] arr = new int[check.length];
for(int i = 0; i< (s.length()); i++)
{
if(check[index]==s.charAt(i))
{
arr[index++] = i;
}
}
boolean flag = true;
if(index==(check.length))
{
for(int i = 0; i<arr.length-1; i++)
{
int skip = arr[i+1]-arr[i];
if(!((skip>2)&&(skip<100)))
{
flag = false;
}
else
{
System.out.println("Skip Distance : "+skip);
}
}
}
else
{
flag = false;
}
return flag;
}
If you pass in a String, you only need one line:
public static String search(String s, int skipDist) {
return s.replaceAll(".*(c.{2," + skipDist + "}a.{2," + skipDist + "}t)?.*", "$1");
}
If no match found, a blank will be returned.

Categories

Resources