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());
}
Related
This question already has answers here:
equals vs Arrays.equals in Java
(9 answers)
Closed 1 year ago.
I am trying to check if a number is palindrome or not, I took the numbers in a string then put them into an array of numbers, and I was able to reverse this array of numbers into a new array. Now I want to check if numbersL[]==numbersLreversed[]. Note that my equal here means that both arrays got the same elements at the same indices.
import java.util.*;
public class Array_and_its_reverse {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String numberS = in.next(); //12121
String numbersarrayed[] = numberS.split(""); // put numbers in a string array
long numbersL[] = new long[numbersarrayed.length]; // original
for (int i = 0; i < numbersarrayed.length; i++) {
numbersL[i] = Long.parseLong(numbersarrayed[i]);
System.out.println(numbersL[i]);
}
long numbersLreversed[] = new long[numbersarrayed.length];
System.out.println("Array in reverse order: ");
for (int i = numbersL.length - 1; i >= 0; i--) {
numbersLreversed[i] = numbersL[i];
System.out.println(numbersLreversed[i]);
}
if (numbersLreversed == numbersL) {
System.out.println("right");
} else {
System.out.println("NO");
}
}
}
== checks for identity (i.e., both operands are the exact same object reference), which, as you see, won't be appropriate here. Instead, you can use the JDK's Arrays.equals:
if (Arrays.equals(numbersLreversed, numbersL)) {
System.out.println("right");
} else {
System.out.println("NO");
}
This question already has answers here:
determine if string has unique characters
(11 answers)
Closed 1 year ago.
I want my code to return true if all the characters in the string are different but it returns true even if some of the characters are the same .For example in the string input the character 'r' is repeated three times and the method still returns true.What am I doing wrong?
My code:
public static void main(String[]args)
{
System.out.println(code("qrrrtyuioplkjhgfdsazxcvbnm")); }
public static boolean code(String input)
{
for (int i = 0; i < 27; i++)
{
char temp=input.charAt(i);
char x =input.charAt(i+1);
if(temp!=x)
{
return true;
}
}
return false;
}
Running through each line of the code, we can see that it is checking the two characters next to each other. The first two characters are "qr", since these are different the function returns true, and doesn't even look at the three r's in a row. For it to achieve what you asked in the question the code should look like this:
public static void main(String[] args) {
System.out.println(code("qrrrtyuioplkjhgfdsazxcvbnm"));
}
public static boolean code(String input) {
for (int i = 0; i < input.length(); i++) { //I have changed it from 27, to input.length() as I assume you want it to work for any input
for (int j = i+1; j < input.length(); j++) {
if(input[i] == input[j]) {
return false;
}
}
}
return true;
}
public static boolean code(String input)
{
if (input.length > (26 or 52)) //depending if the string have upper case char or not, if you are do not know which char could be there just put the max number of char or delete the line with return state
return false;//if you have more than that number of character you for sure will have repetition due to pigeon hole principle
for (int i = 0; i < input.length; i++)
for (int j = i + 1; j < input.length; j++)
{
if (input.charAt(i) == input.charAt(j)) //check for all pairs to not to be the same
return false; //if found at least one pair of identical
}
return true;//if nothing found return true
}
Use a Set and return false as soon as something is present in the set, otherwise return true after cycling through the input string..
public boolean checkUniqueLetters(String inputString) {
Set<String> letterSet = new HashSet<>();
for (String letter : inputString.split("")) {
if (letterSet.contains(letter)) {
return false;
} else {
letterSet.add(letter);
}
}
return true;
}
https://docs.oracle.com/javase/8/docs/api/java/util/Set.html
This question already has answers here:
Check string for palindrome
(42 answers)
Closed 1 year ago.
I am trying to write a method to check if a given word is a palindrome, but as of now it does not work. I suspect the error lies within the if-statement and the fact that you don't compare objects such as strings with == but instead with equals, is that right? However Java does not allow me to write: if (firstHalf.charAt(i).equals(secondHalf.charAt(j))), so what can I do to make it work? Are there other errors in the code?
public static boolean isPalindrome(String string) {
String firstHalf = string.substring(0, string.length() / 2);
String secondHalf = string.substring(string.length() / 2, string.length());
for (int i = 0; i <= firstHalf.length(); i++) {
for (int j = secondHalf.length(); j <= 0; j--) {
if (firstHalf.charAt(i) == secondHalf.charAt(j)) {
return true;
}
}
}
return false;
}
Why not do it this way?
public static boolean isPalindrome(String string){
StringBuilder sb = new StringBuilder(string);
sb.reverse();
return sb.toString().equals(string);
}
Your character test was backwards. All of the comparisons have to be equal for the String to be a palindrome.
Also, splitting the String is unnecessary. You can logically split the String with two indices.
Try this code.
public static boolean isPalindrome(String string) {
int frontIndex = 0;
int backIndex = string.length() - 1;
while (frontIndex < backIndex) {
if (string.charAt(frontIndex++) != string.charAt(backIndex--)) {
return false;
}
}
return true;
}
you can make each character a String like so
String s1 = "" + c1;
and then compare them with .equals(s1, s2)
Or you can use the Character class which is a wrapper around primitive character.
That would also enable you to use c1.equals(c2)
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.";
}
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