getting an error in my palindrome java program - java

I have created a palindorme java program which is getting an error.the error is saying int cannot be converted to boolean.
import java.util.Scanner;
public class palindrome
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int l,i;
String s,s1;
System.out.println("Enter your string");
s = sc.nextLine();
l = s.length();
for(i=0;l-i-1;i++)
{
s1 = s + s.charAt(i);
}
if(s1==s)
System.out.println("This is Palindrome");
else
System.out.println("This is not a Palindrome");
}
}

For loop condition seems wrong.
for(initial counter; condition to terminate; increase counter) {}
for(i=0; i<l; i++) {}

Along with the answer above you can try a different approach. You don't need to go all the string length to check a palindrome. A palindrome can be checked iterating half of the array length like this -
public void checkPalindrome(String strToCheck){
char[] arr = strToCheck.toCharArray();
int size = arr.length;
char [] original = Arrays.copyOf(arr,arr.length);
for (int i = 0; i < size / 2; i++) {
char temp = arr[i];
arr[i] = arr[size-i-1];
arr[size-i-1] = temp;
}
if(Arrays.equals(arr, original)) {
System.out.println("Palindrome");
} else {
System.out.println("Not a palindrome");
}
}
What are done here:
reversing the string first iterating the halfway
comparing the reversed string with the original using Arrays.equals() method.

There are quite a few things off here, first here is the fixed code:
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
int l,i;
String s = "",s1 = "";
System.out.println("Enter your string");
s = sc.nextLine();
l = s.length();
for(i = l - 1; i >= 0; i--)
{
s1 = s1 + s.charAt(i);
}
if(s1.equals(s))
System.out.println("This is Palindrome");
else
System.out.println("This is not a Palindrome");
}
The first thing to fix was your for loop, as you saw you were getting an error. This was fixed by setting the initial i to the length minus 1, changing the loop condition to i >= 0, and using i-- to subtract 1 from i each loop.
These changes to the loop were made so that the character starting from the last position in the String is the first one being return by s.charAt(i) so you can reverse the String. I think you were attempting to do something along these lines to add the characters starting from the end to a String.
I also changed s1 = s + s.charAt(i) to s1 = s1 + s.charAt() so the correct String is being appended. (This should probably be StringBuilder however).
s and s1 now have the initial condition of "" instead of nothing.
And finally you cannot compare String equality with ==, it must be s1.equals(s).
Test Run:
Enter your string
racecar
This is Palindrome

Related

Starting with the last character and iterating backwards by 3

I am trying to create a code that takes any string and relays it back to me backwards missing every 3rd character and including the very last character.
EX: "123456789" should return "963" &
"Hello, World!" should return "!r lH"
import java.util.Scanner;
public class cypher {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String reverse = "";
System.out.println(str.length());
for (int i = str.length() - 1; i >= 0; --i) {
reverse = reverse + str.charAt(i - 3);
}
System.out.println(reverse);
}
}
The code above is what I have so far. However when I run this code I get this error message: "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1"
I don't understand because the string length is 10 so why is it not able to do this? Could someone explain this to me and give me a suggestion on how to fix this?
I suggest just iterating the characters in the string, starting from the last position, and moving backwards in increments of 3:
Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String reverse = "";
for (int i=str.length()-1; i >= 0; i=i-3) {
reverse += str.charAt(i);
}
System.out.println(reverse);
Your current approach is failing because the loop just takes single, not triple steps. Also note that you might want to use StringBuilder instead of String to build the reverse string. This might be more efficient (though the JVM itself might substitute StringBuilder on its own).
You current logic is str.charAt(i - 3) and continue while i >= 0. The str.charAt(i - 3) statement will generate java.lang.StringIndexOutOfBoundsException when i is less than 3, thus you should change your code to this.
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String reverse = "";
System.out.println(str.length());
for (int i = str.length() - 1; i >= 0; i = i - 3) {
reverse = reverse + str.charAt(i);
}
System.out.println(reverse);
}
According to your current logic str.charAt(i - 3) here when value of i becomes less than 3, your code will try to access and index that is a -ve number and thus throws this exception.
You'll have to check if i - 3 >= 0 before using str.charAt(i - 3) else break out of the loop.
I tried this code in my system and it works fine. Try this:
import java.util.Scanner;
public class cypher {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String reverse = "";
System.out.println(str.length());
for (int i = str.length() - 1; i>= 0; i-=3) {
reverse = reverse + str.charAt(i);
}
System.out.println(reverse);
}}
Changed your code a little and this works fine now.
You were getting the java.lang.StringIndexOutOfBoundsException because your for loop decremented by a single step every time instead of the required step of 3. As a result when the string has less than 3 characters left the value of variable i becomes negative and an exception is thrown when the charAt(i) function is called with a negative value.
import java.util.Scanner;
public class cypher {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String reverse = "";
System.out.println(str.length());
int i = str.length() - 1;
while(i >= 0)
{
reverse = reverse + str.charAt(i);
i-=3;
}
System.out.println(reverse);
}
}

only checks first and last character

I am new to java and am trying to create a palindrome word program, to check if the word backwards is the same.
public static void isPalindromeWord(){
Scanner input = new Scanner (System.in);
System.out.print("Enter a word to check: ");
String word = input.next().toLowerCase();
String reversed = new StringBuffer(word).reverse().toString();
int len = word.length();
for(int x = 0; x < len ; x++){
if(word.charAt(x) == reversed.charAt(x)){
System.out.println("True");
}else{
System.out.println("False");
}
}
}
Please excuse if I've done anything wrong, I have only started learning today.
My problem is :
With the current it outputs True for something such as "otto" which is a palindrome. But it also does True for "oplko" which isn't. So I know that it only checks the first and last letters but I thought that with the for loop it will go through each letter?
Can someone be kind enough to explain where I am going wrong and suggest how to fix it? The reason I am using a for loop is because the task is requiring me to do so.
You are very close to the solution. Since you have already reversed the string you can check if they are equal
new StringBuffer(word).reverse().equals(word);
Edit: Added one more solution for using loop
What you are doing in the loop is mostly correct. You are getting True for oplko is because you are not exiting the loop when the word.charAt(x) == reversed.charAt(x) condition fails. This can be fixed by
public static void isPalindromeWord() {
Scanner input = new Scanner(System.in);
System.out.print("Enter a word to check: ");
String word = input.next().toLowerCase();
String reversed = new StringBuffer(word).reverse().toString();
int len = word.length();
for (int x = 0; x < len; x++) {
if (word.charAt(x) != reversed.charAt(x)) {
System.out.println("False");
return;
}
}
System.out.println("True");
}
there are a lot of ways to do what you want (including Anthony C's very elegant answer), but here is a simple fix to make yours work :
public static void isPalindromeWord(){
Scanner input = new Scanner (System.in);
System.out.print("Enter a word to check: ");
String word = input.next().toLowerCase();
//you don't really need to get a reverse here
//String reversed = new StringBuffer(word).reverse().toString();
int len = (int)(word.length() / 2);//only check half (and not evnt the middle one for odd numbers
boolean isPalindrom = true;
for(int x = 0; x < len ; x++){
if(word.charAt(x) != word.charAt(word.length() - 1 - x)){
isPalindrom = false;
//at least one difference, this is not a palindrome
break;
}
}
if(isPalindrom)
System.out.println("True");//the for wasn't broken
else
System.out.println("False");
}
public static void isPalindromeWord(){
Scanner input = new Scanner (System.in);
System.out.print("Enter a word to check: ");
String word = input.next();
String reversed = input.next();
char c[]=word.toLowerCase().toCharArray();
char d[]=reversed.toLowerCase().toCharArray();
if(word.length() != reversed.length()) System.out.print("False ");
Arrays.sort(c);
Arrays.sort(d);
if(Arrays.equals(c,d)) System.out.print("True ");
else System.out.print("False ");
}
Just to describe where you have a mistake. You are writing in console on every step of loop, doesn't matter which result of comparing do you have.
boolean isPolindrom = true;
for(int x = 0; x < len ; x++){
isPolindrom = (word.charAt(x) == reversed.charAt(x)); //compare chars and store result into variable
if (!isPolindrom) { //if chars are different break a loop, because word is already not a polindrom
break;
}
}
System.out.println(isPolindrom); //output result
Solution from #AnthonyC is really better

Unable to accept two strings in first iteration but works fine during successive iterations

I'm scanning 2 strings during each iteration and storing it in s and t. Only during the first iteration, the first string that I scan is getting stored in t and not in s (I got to know this by debugging in eclipse). During successive iterations the piece of code works fine. I'm not able to understand what is going on during the first iteration. Please help me. Thanks.
import java.io.*;
import java.util.*;
public class ResidentInfo {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int i,n;
n = scan.nextInt();
for(i=0 ; i<n ; i++)
{
int sl,tl,j,k;
String s, t;
boolean flag = false;
s = scan.nextLine();
t = scan.nextLine();
sl = s.length();
tl = t.length();
char[] sa = new char[sl];
char[] ta = new char[tl];
sa = s.toCharArray();
ta = t.toCharArray();
for(j=0 ; j<sl ; j++)
{
for(k=0 ; k<tl ; k++)
{
if(sa[j]==ta[k])
{
flag = true;
break;
}
}
if(flag)
{
break;
}
}
if(flag)
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}
}
The first thing this code does is determine if the two strings' lengths are equal. If the strings' lengths are not equal, the code prints no. If the lengths are equal, the code then checks each character in the exact same index in the strings, to see if they are equal. If the characters at a specific index is not equal, the code breaks the loop and prints no. If all of the characters at each index are equal the code prints yes.
You asked a question about next() and nextLine().
Try: Question asked already.
Scanner scan = new Scanner(System.in);
System.out.print("enter a number: ");
int n = scan.nextInt();
for(int i=0; i < n; i++)
{
boolean flag = true;
System.out.print("enter something for s: ");
String s = scan.next();
System.out.print("enter something for t: ");
String t = scan.next();
if(s.length() == t.length())
{
for(int j = 0; j < s.length(); j++)
{
if(s.charAt(j) != t.charAt(j))
{
flag = false;
break;
}
}
if(flag)
{
System.out.println("Yes");
}
else
{
System.out.println("NO");
}
}
else
{
System.out.println("NO");
}

if loop is not working? can anyone help me

public class meaingCompare {
public static void main(String[] args) {
int cnt = 0;
String st1, u, st2;
st2 = "funny";
int n = 5;
System.out.println("Enter the string");
Scanner in=new Scanner(System.in);
st1 = in.nextLine();
String[] v = st1.split("\\s+");
for(int i = 0; i < st1.length(); i++) {
if(v[i].equalsIgnoreCase(st2))
cnt++;
}
if(cnt>=4)
System.out.println(" match found");
}
}
I am just a beginner in java.I want to get the output as match found if the no: of words in the input string match the word funny is greater than 4 but the if loop is not working.
Your stop condition in the for loop is wrong: since you're looping on the array of strings v you should stop when you've reached the last element. Modify:
for(int i=0;i<st1.length();i++)
to:
for(int i=0;i<v.length;i++)
when traversing due to this st1.length() we get ArrayIndexOutofBoundException so compare with array length instead of strings length.
This works:
public static void main(String[] args)
{
int cnt=0;
String st1,u,st2;
st2="funny";
int n=5;
System.out.println("Enter the string");
Scanner in=new Scanner(System.in);
st1=in.nextLine();
String[]v=st1.split("\\s+");
for(int i=0;i<v.length;i++)
{
if(v[i].equalsIgnoreCase(st2))
cnt++;
}
if(cnt>=4)
System.out.println(" match found");
}
}
First of all, there is no such thing as an if loop. You have a for loop.
Your problem is that in your for loop, you check if i is less then the length of the String st1. However you need to check if I is less then the length of the array v. So, change this statement:
for(int i = 0; i < st1.length(); i++)
to this:
for(int i = 0; i < v.length; i++)
Hope this helped.

out of bounds error with word count

I'm trying to write my own Java word count program. I know there may already be a method for this, but I'd like to get it work. I'm getting an out of bounds error at line 14. I'm trying to use an input word to count how many times it appears in an input string. So I'm looping up to stringlength - wordlength, but that's where the problem is.
Here is the code:
import java.util.Scanner;
public class wordcount {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print( "Enter word : " );
String word = s.nextLine();
Scanner t = new Scanner(System.in);
System.out.print("Enter string: ");
String string = t.nextLine();
int count = 0;
for (int i = 0; i < string.length()-word.length(); i = i+1){
String substring = string.substring(i,i+word.length());
if (match(substring, word)==true){
count += 1;
}
}
System.out.println("There are "+count+ " repetitions of the word "+word);
}
public static boolean match(String string1, String string2){
for (int i=0; i<string1.length(); i+=1){
if (string1.charAt(i)!=string2.charAt(i)){
return false;
}
}
return true;
}
}
First of all, two Scanners are not necessary, you can do many inputs with the same Scanner object.
Also, this if condition
if (match(substring, word) == true)
can be rewritten like
if (math(substring, word))
I would also recommend you to use i++ to increase the loop variable. Is not strictly necessary but is "almost" a convention. You can read more about that here.
Now, about theIndexOutOfBoundsException, I've tested the code and I don't find any input samples to get it.
Besides, there is an issue, you are missing one iteration in the for:
for (int i = 0; i < string.length() - word.length() + 1; i++) { // Add '+ 1'
String substring = string.substring(i, i + word.length());
// System.out.println(substring);
if (match(substring, word)) {
count++;
}
}
You can test it by putting a print statement inside the loop, to print each substring.
I'm not getting an out of bounds error, can you tell me what values you were using for word and string?
I have identified a bug with your program. If word is equal to string, it still returns count 0. I suggest adding one more iteration and using regionMatches instead. RegionMatches makes your match method obsolete and will return false if word.length() + i is equal or greater than string.length(), avoiding out of bounds issues.
As you can see I also moved the calculations to a seperate method, this will make your code more readable and testable.
And as Christian pointed out; you indeed do only need one Scanner object. I've adapted the code below to reflect it.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter word : ");
String word = sc.nextLine();
System.out.print("Enter string: ");
String string = sc.nextLine();
int count = calculateWordCount(word, string);
System.out.println("There are " + count + " repetitions of the word " + word);
}
private static int calculateWordCount(String word, String string) {
int count = 0;
for (int i = 0; i < string.length() - word.length() + 1; i++) {
if (word.regionMatches(0, string, i, word.length())) {
count++;
}
}
return count;
}

Categories

Resources