This question already has answers here:
Check string for palindrome
(42 answers)
What's the simplest way to print a Java array?
(37 answers)
Closed 9 years ago.
First time posting here! Yeah I kind of just need some help with this assignment. We had to read an input file, go through a loop for each character in a line of the input file, and store that info in a char array, and then finally write an isPalindrome method and call it to determine if that line is a palindrome and print it to the console.
This is what I have so far, sorry if I didn't format correctly, it was kind of confusing.
I'm still kind of a beginner and I'm not sure where I'm going wrong. My output is essentially "[C#91bee48 is not a palindrome!" over and over again with some variation on whether or not its a palindrome.
public class Palindromes {
public static void main(String[] args) {
int k = 0;
try {
Scanner inF = new Scanner(new File("palindromes.txt"));
String aString;
while (inF.hasNextLine()) {
aString = inF.nextLine();
k++;
for (int i = 0; i < k; i++) {
char[] phrases = new char[aString.length()];
if (Character.isLetter(aString.charAt(k))) {
phrases[i] = aString.charAt(i);
}
isPalindrome(phrases);
}
}
}
catch (FileNotFoundException e) {
System.err.println("palindromes.txt not found!");
}
}
public static void isPalindrome(char[] phrases) {
boolean isPalindrome = false;
int i1 = 0;
int i2 = phrases.length - 1;
while (i2 > i1) {
if (phrases[i1] != phrases[i2]) {
isPalindrome = false;
System.out.println(phrases + " is not a palindrome!");
} else {
isPalindrome = true;
System.out.println(phrases + " is a palindrome!");
}
i1++;
i2--;
}
}
}
Use Arrays.toString() to get the string representing the array.
For example:
System.out.println(Arrays.toString(phrases) + " is not a palindrome!");
Otherwise you get the default toString() for an array object - which is not what you are after.
The logic of your while loop is faulty. This kind of loop is a common idiom: you have to check a number of things, and if any check fails, you want the result to be false. If no check fails, you want the result to be true. The thing is, you can't tell if the result is true until the loop is completely finished. Your code is:
while (i2 > i1)
{
if(phrases[i1] != phrases[i2])
{
isPalindrome = false;
System.out.println(phrases + " is not a palindrome!");
}
else
{
isPalindrome = true;
System.out.println(phrases + " is a palindrome!");
}
i1++;
i2--;
}
The problem is that you're printing "is a palindrome" before you've checked all the characters, and you can't possibly know that. The way to write this kind of loop is something like this:
isPalindrome = true;
while (i2 > i1)
{
if(phrases[i1] != phrases[i2])
{
isPalindrome = false;
break; // get out of the loop, it's pointless to continue
}
i1++;
i2--;
}
// *** NOW you can check isPalindrome and display your output
Related
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);
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Im trying to make a simple programm that compares if a number or word is a palindrome. Ive made the following code, but I dont get why my if statement doesnt work. If you print the results you can see the numbers or letters are the same but my if statement doesnt think so. Here is my code. Thanks :
import java.util.*;
public class myPalindromo
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
String number;
ArrayList < String > myNumber = new ArrayList < String > ();
Scanner sn = new Scanner(System.in);
number= sn.nextLine();
for(int i = 0 ; i<number.length() ; i++)
{
myNumber.add(number.valueOf(number.charAt(i)));
}
for(int i = 0; i<myNumber.size(); i++)
{
System.out.println(myNumber.get(i)+"=="+myNumber.get((myNumber.size()-1)-i));
if(myNumber.get(i)== myNumber.get((myNumber.size()-1)-i))
System.out.println("palindrome");
else
System.out.println("not palindrome");
}
}
}
To check if a string is palindrome try this:
static boolean isPalindrome(String s) {
int center = (int)s.length()/2 - 1;
for (int i = 0; i <= center; i++) {
if (s.charAt(i) != s.charAt(s.length() - i-1) )
return false;
}
return true;
}
You should change the If statement to this one
if(Integer.parseInt(myNumber.get(i))== Integer.parseInt(myNumber.get((myNumber.size()-1)-i)))
Thats because you were comparing string instead of the actual numbers.
You can use the reverse method in the StringBuilder to accomplish this.
public static boolean isPalindrome(String str) {
return str.equals(new StringBuilder(str).reverse().toString());
}
This question already has answers here:
How do I break out of nested loops in Java?
(37 answers)
Closed 8 years ago.
Please have a look at the following code (Java)
while((str=br.readLine())!=null)
{
int tempCounter=0;
for(int i=0;i<str.length();i=i+3)
{
String word = str.substring(i, i+3);
// System.out.println(word);
int insert = db.insert(index, word);
if(insert<0)
{
break;
}
tempCounter++;
}
index++;
System.out.println("Index Updated: "+index);
System.out.println(String.valueOf("Total words in this run: "+tempCounter));
if(index==5)
{
break;
}
}
if insert is less than 0, the I need to break both for and while loops. How can I do this?
Problem here is I need to break "both" loops if insert is less than 0. And you can't add 2 break commands one after another, even with labels.
You may try this simple example to see how a labeled loop works:
public static void main(String[] args) {
int i = 0; int j = 0;
EXIT: for (; i < 10; i++) {
for (; j < 10; j++) {
if (i * j > 50) {
break EXIT;
}
}
j = 0;
}
System.out.printf("Finished with i=%s and j=%s\n", i, j);
}
OUTPUT:
Finished with i=6 and j=9
+1.. #AntonH.. label is an first option.. if you are confused how to use label.. you can use a boolean variable like below..
while (...) {
boolean brk = false;
for (...) {
if(insert<0)
{ brk = true;
break;
}
}
if(brk)
{
break;
}
}
while((str=br.readLine())!=null)
{
int tempCounter=0;
boolean check = false;
for(int i=0;i<str.length();i=i+3)
{
String word = str.substring(i, i+3);
// System.out.println(word);
int insert = db.insert(index, word);
if(insert<0)
{
check = true;
break;
}
tempCounter++;
}
index++;
if(check)
break;
System.out.println("Index Updated: "+index);
System.out.println(String.valueOf("Total words in this run: "+tempCounter));
if(index==5)
{
break;
}
}
You can do by this way
Your question is already partly answered here. Use the label in front of the line of the while loop, e.g. OUTMOST, then when the insert is less than 0, 'break OUTMOST'. For example:
OUTMOST:
while(someCondition) {
for(int i = 0; i < someInteger; i++) {
if (someOtherCondition)
break OUTMOST;
}
}
IMO, an exception is inappropriate; a label is rare and not likely to be understood by future readers.
Invoking KISS principle, why not just use an extra flag and augment the expression used in each loop:
boolean isInsertFail = false;
while((! isInsertFail) && (str=br.readLine())!=null))
{
int tempCounter=0;
for(int i=0;(! isInsertFail) && i<str.length();i=i+3)
{
String word = str.substring(i, i+3);
// System.out.println(word);
int insert = db.insert(index, word);
if(insert<0)
{
isInsertFail = true;
}
tempCounter++;
}
if (!isInsertFail) {
index++;
System.out.println("Index Updated: "+index);
System.out.println(String.valueOf("Total words in this run: "+tempCounter));
if(index==5)
{
break;
}
}
}
Note that in Eclipse, one could click on isInsertFail, and the syntax highlighting should illustrate its use.
One approach is to use an exception, depending on the expected result of the db.insert routine.
In short, create a new EDBInsertionException exception (a class extending Exception) and raise the exception in your for loop.
try
{
while((str=br.readLine())!=null)
{
int tempCounter=0;
for(int i=0;i<str.length();i=i+3)
{
String word = str.substring(i, i+3);
// System.out.println(word);
int insert = db.insert(index, word);
if(insert<0)
{
throw new EDBInsertionException("No record inserted: " + insert);
}
tempCounter++;
}
index++;
System.out.println("Index Updated: "+index);
System.out.println(String.valueOf("Total words in this run: "+tempCounter));
if(index==5)
{
break;
}
}
}
catch (EDBInsertionException e)
{
// MZ: The database insertion has failed
log.error(e.getMessage(), e);
// MZ: Supplemental action: Delegate, escalate, rollback, etc
}
EDIT
Expanded the example to illustrate a potential usage of an (user) exception.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I made a program to search for a certain string in another string and print Word found if the condition is true or print word not found if condition is false
The logic is as follows
enter word
length of word
for searching for letter [1]
if true
then for till length of word match with string to be searched
else continue loop
But I always get word not found no matter what the input, please help me over here!!!
The code is as follows :-
import java.util.Scanner;
class Search_i_String
{
public static void main(String args[])
{
int flag=0;
Scanner Prakhar=new Scanner(System.in);
System.out.println("Enter a String");
String ori=Prakhar.nextLine();
System.out.println("Enter the String to be Searched");
String x=Prakhar.nextLine();
char a[]=new char[ori.length()];
char b[]=new char[x.length()];
for(int i=0;i<ori.length();i++)
{
a[i]=ori.charAt(i);
}
for(int i=0;i<x.length();i++)
{
b[i]=x.charAt(i);
}
for(int i=0;i<a.length;i++)
{
if (a[i]==b[0])
{
for(int j=0;j<b.length;j++)
{
while(flag==0)
{
if(b[j]==a[i])
{
flag=0;
}
else if(b[j] != a[i])
{
flag=1;
}
i++;
}
}
}
}
if (flag==0)
{
System.out.println("Word Found !!!");
}
else
System.out.println("Word not Found");
}
}
P.S. : I know I can use the contains() function but I can as my professor suggests against it and could someone please correct the program I have written, because I could have scavenged off a program from the internet too if I had to, I just wanted to use my own logic
Thank You(again)
while(flag==0)
{
if(b[j]==a[i])
{
flag=0;
}
else if(b[j] != a[i])
{
flag=1;
}
i++;
j++; //add this and try once
}
If you are comparing strings in Java, you have to use equals();
So, stringA.equals(stringB);
Cheers!
Let me get this straight. You're looking for b array inside of a array? "Enter the string to be searched" means that you are searching the other way around, but I'll go with the logic your code seems to follow... Here's a naive way to do it:
if (a[i]==b[0])
{
flag = 0;
for(int j=0;j<b.length;j++)
{
if(b[j] != a[i+j]) // will array index out of bounds when its not foud
{
flag++; // you should probably break out of a named loop here
}
}
if(flag == 0){/*win*/}
}
You're modifying your first search loop with variable i when you don't have to. You can just add i to j. Also, you don't need the while loop inside if i'm understanding your problem. Like others have said, functions exist to do this already. This algorithm isn't even as efficient as it could be.
I know of an algorithm where you check starting in the last character in b instead of the first character in b to begin with. Then you can use that information to move your search along faster. Without resorting to full pseudo code, anyone know what that's called?
The simple way(but not the fastest way) is use double loop to check the chars in strings one by one, pls ref to my code and comments:
public class SearchString {
public static void main(String[] args) {
String a = "1234567890";
String b = "456";
// Use toCharArray() instead of loop to get chars.
search(a.toCharArray(), b.toCharArray());
}
public static void search(char[] a, char[] b) {
if (a == null || b == null || a.length == 0 || b.length == 0) {
System.out.println("Error: Empty Input!");
return;
}
int lenA = a.length, lenB = b.length;
if (lenA < lenB) {
System.out
.println("Error: search key word is larger than source string!");
return;
}
// Begin to use double loop to search key word in source string
for (int i = 0; i < lenA; i++) {
if (lenA - i < lenB) { // If the remaining source string is shorter than key word.
// Means the key word is impossible to be found.
System.out.println("Not found!");
return;
}
// Check the char one by one.
for (int j = 0; j < lenB; j++) {
if (a[i + j] == b[j]) {
if (j == lenB - 1) { // If this char is the last one of key word, means it's found!
System.out.println("Found!");
return;
}
} else {
// If any char mismatch, then right shift 1 char in the source string and restart the search
break;
}
}
}
}
}
You can just use String.contains();
If you really want to implement a method, try this one:
public static void main(String[] args) {
// Initialize values searchedWord and original by user
String original = [get original word from user] ;
String searchedWord = [get searched for word from user];
boolean containsWord = false;
int comparePosition = 0;
for(int i = 0; i < original.length() - searchedWord.length(); i++) {
if(original.charAt(i) == searchedWord.charAt(comparePosition)) {
comparePosition += 1;
} else {
comparePosition = 0;
}
if(comparePosition == searchedWord.length()) {
containsWord = true;
break;
}
}
return containsWord? "Word found!!" : "Word not found.";
}
I'm trying to write a program which will output what Palindromes will work from entering in a string and how many there are. I keep getting a lot of errors and I'm still trying to get my head around some of the harder topics in Java!
Here's what I have already, as always, all answers are greatly appreciated!
public static boolean Palindrome(String text) {
int index;
int palindrome;
System.out.println("Please enter your text ");
text = EasyIn.getString();
for(index = 0; index < amount.length() / 2; index++) {
if(text.charAt(index) != text.charAt(text.length() - index - 1)) {
return false;
}
}
System.out.println("The number of valid palindrome(s) is " + amount);
amount = EasyIn.getString();
}
I think the problem is in amount.length(), you should use text.length(), since you are looping over the half of text. The algorithm works fine. Here is a reduced example:
public static boolean palindrome(String text)
{
for (int index = 0; index < text.length() / 2; index++) {
if (text.charAt(index) != text.charAt(text.length() - index - 1)) {
return false;
}
}
return true;
}
Note:
You forgot to add a return true statement, if you don't add one, is possible that the for loop finishes and no return statement is reached, which will cause an error.
I would recommend you to follow Java naming conventions. You method should be called like someMethodName instead of SomeMethodName. This last is used for class names.
Edit:
As #bobbel commented, you could improve this code by assigning text.length() to a variable and using it inside the for.
There can be two things:
ammount variable that you used either it could be a string array that you are maintaining strings inside it, if this is the case than you have to loop first through array of strings and then maintain one nested loop to check that strings inside it are palindrom or not
or second case is that you have used the variable incorrect it may be text instead of ammount
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("enter string to check for palidrome");
String orginal = in.next();
int start = 0;
int middle = orginal.length()/2;
int end = orginal.length() - 1;
int i;
for(i=start; i<=middle; i++) {
if(orginal.charAt(start) == orginal.charAt(end)) {
start++;
end--;
} else {
break;
}
}
if(i == middle+1) {
System.out.println("palidrome");
} else {
System.out.println("not palidrome");
}
}
This is the Simplest way of Checking Palindrom number.
package testapi;
public class PalindromNumber {
public static void checkPalindrom(Object number) {
StringBuilder strNumber = new StringBuilder(number.toString());
String reverseNumber = strNumber.reverse().toString();
if (number.toString().equals(reverseNumber)) {
System.out.println(number + " is palindrom number");
} else {
System.out.println(number + " is not palindrom number");
}
}
public static void main(String[] args) {
checkPalindrom(101);
checkPalindrom(10.01);
checkPalindrom("aanaa");
}
}