to check whether a string is palindrome or not using java - java

import java.util.Scanner;
public class palindrome{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String rev;
for(int i=str.length()-1,k=0;i>=0 && k<str.length();i--,k++)
{
rev.charAt(k) = str.charAt(i);
}
if(rev==str)
System.out.println("string is palidrome");
else
System.out.println("string is not palindrome");
}
}
what is wrong with this code?
note: error is showing at the following line of code
rev.charAt(k)=str.charAt(i);

.charAt(k) doesn't return a location, it only tells you what character is there.

Sample code for palindrome program
import java.util.*;
class PalindromeExample2
{
public static void main(String args[])
{
String original, reverse = ""; // Objects of String class
Scanner in = new Scanner(System.in);
System.out.println("Enter a string/number to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string/number is a palindrome.");
else
System.out.println("Entered string/number isn't a palindrome.");
}
}

Related

I can't add a string to itself

I'm new to java and trying to add a string to itself (plus other strings also) and it runs but doesn't do anything at all, as in it just outputs "test", which is what it is before
everything else seems to work
package chucknorris;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
for (int current = 0;current <= length;current++) {
String letter = input.substring(current, current);
output = output + letter + " ";
if (current == length) {
System.out.println(output);
}
}
}
}
Try this Solution, but you should use StringBuilder if you want to edit a String for a multiple times
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
for (int current = 0;current <= length;current++) {
if (current >= length) {
break;
}
String letter = input.substring(current, current + 1);
output = output + letter;
}
System.out.println(output);
}
}
use concat for the string concatenation.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
output = output.concat(output).concat(input).concat("");
System.out.println(output);
}

To check each word in a sentence whether they are palindrome or not

In a given sentences, reverse each word and print the reversed words in the sentences. if there is a palindrome print those words .if there is no palindrome print "No Palindrome".
this is what i wrote
import java.util.Scanner;
public class main{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
String s1=input.nextLine();
String arr[]=s1.split("\\s",s1.length());
int count=0;
String palindrome[]=new String[s1.length()];
for(int i=0;i<arr.length;i++){
String s2="";
for(int j=arr[i].length()-1;j>=0;j--){
s2=s2.concat(Character.toString(arr[i].charAt(j)));
System.out.println(arr[i].charAt(j));
}
System.out.print(" ");
if(arr[i].equals(s2)){
count++;
palindrome[i]=s2;
}
}
if(count>0){
for(String i:palindrome)
System.out.println(i);}
else
System.out.println("Not a palindrome");
}
}
But code is not giving proper output.
This should work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s1 = input.nextLine();
String[] arr = s1.split(" ");
StringBuilder output = new StringBuilder();
for (String currentWord : arr) {
String reverseWord = new StringBuilder(currentWord).reverse().toString();
if (currentWord.equals(reverseWord)) {
output.append(reverseWord);
} else {
output.append("No Palindrome ");
}
}
System.out.println(output);
}
Here's a shorter way of doing this:
//prints each palindome word in a sentence
Arrays.asList(sentence.split(" ")).stream().filter(this::isPalindrome).forEach(System.out::println);
Here is a working code that you can use for checking the input string/number is palindrome or not palindrome
code:
import java.util.*;
class stackOverflow {
public static void main(String[] args) {
String original, reverse = ""; // Objects of String class
Scanner in = new Scanner(System.in);
System.out.println("Enter a string/number to check if it is a palindrome or not:");
// takes input string
original = in.nextLine();
int length = original.length(); // length of the string to do iteration on it
// check the string from the end to the start to reverse it
// read and append it with the reverse variable in backward
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
// Finally we check if the input string and reversed string
if (original.equals(reverse))
System.out.println("Is palindrome.");
else
System.out.println("Not palindrome.");
}
}
I've edited your code and now it's working fine:
import java.util.*;
class stackOverflow {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
String s1=input.nextLine();
String arr[]=s1.split("\\s",s1.length());
for(int i=0;i<arr.length;i++){
String s2="";
for(int j=arr[i].length()-1;j>=0;j--){
s2=s2.concat(Character.toString(arr[i].charAt(j)));
//System.out.println(arr[i].charAt(j));
}
//System.out.print(" ");
if(arr[i].equals(s2)){
//palindrome[i]=s2; // you are inserting the s2 value into the first element of the array,
//so the rest of the positions remains empty/null that's not a problem to solve palindrome
System.out.println("Is a palindrome");
}
else
System.out.println("Not a palindrome");
}
}
}

Make the program the you if the word you've inputed in the console is a palindrome or not in Java

I've been trying to make this program work, have the person write a word in the console and make the console have an output saying if that word is or isn't a palindrome.
package sct;
import java.util.Scanner;
public class Assignment3Problem4 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a a string: ");
String DAWORD = reader.nextLine();
reader.close();
int n = DAWORD.length();
boolean isPalindrome = true;
for (int i = 0; i < n; ++i) {
if (DAWORD.charAt(i) != DAWORD.charAt(n - i - 1)) {
isPalindrome = false;
break;
}
if (isPalindrome)
System.out.println("This word is a palindrome");
else
System.out.println("This word is not a palindrome");
}
}
}
Sadly, this didn't work and the console doesn't let me input a string, can someone find out why and fix the code?
You shouldn't print whether the word is a palindrome (or not) until after the for loop. That's the only issue I had running the posted code.
Scanner reader = new Scanner(System.in);
System.out.println("Enter a a string: ");
String DAWORD = reader.nextLine();
reader.close();
int n = DAWORD.length();
boolean isPalindrome = true;
for (int i = 0; i < n; ++i) {
if (DAWORD.charAt(i) != DAWORD.charAt(n - i - 1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome)
System.out.println("This word is a palindrome");
else
System.out.println("This word is not a palindrome");
You might want to remove reader.close() (as that also closes System.in).
Another approach you could consider is putting your input into a StringBuilder object, reverse it, then check if it equals your input.
Something like:
import java.util.Scanner;
public class StackOverflow {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a string: ");
String DAWORD = reader.nextLine();
reader.close();
if (new StringBuilder(DAWORD).reverse().toString().contentEquals(DAWORD))
System.out.println("This word is a palindrome");
else
System.out.println("This word is not a palindrome");
}
}
Result:
Enter a string:
racecar
This word is a palindrome
You can also use an external apache lang library from here https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.7. Then you can use StringUtils.reverse() method which reverses a string and then compare reversed string with the normal one , like so:
import org.apache.commons.lang3.StringUtils;
public class Main4 {
public static void main(String[] args) {
String str = "kajak";
String str2 =StringUtils.reverse(str);
if (str2.equals(str)){
System.out.println("It's a palidrom");
}
else{
System.out.println("Not a palidorm");
}
}
}

Java palindrome until EOF

I have a program that is supposed to ask the user for a number and it will determine whether it is a palindrome or not. It's supposed to keep asking for numbers until EOF is input - So far it asks for the number twice and doesn't seem to be doing the while loop correctly.
Any insight is appreciated
import java.util.Scanner;
public class PalindromeEOF
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to check if it is a palindrome:");
String num = scanner.nextLine();
String reverse = "";
while (scanner.hasNextLine())
{
for ( int i = 0; i<num.length(); i++ )
{
reverse = num.charAt(i) + reverse;
}
if (num.equals(reverse))
{
System.out.println("\nEntered number IS a palindrome.");
}
else
{
System.out.println("\nEntered number is NOT a palindrome.");
}
System.out.println("\nEnter a number to check if it is a palindrome:");
num = scanner.nextLine();
reverse = "";
}
System.out.println("\nProgram ended on request");
}
}
This worked for me; unless you need num or reverse outside the while loop it should work.
import java.util.Scanner;
public class PalindromeEOF
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to check if it is a palindrome:");
while (scanner.hasNextLine())
{
String num = scanner.nextLine();
String reverse = "";
for ( int i = 0; i<num.length(); i++ )
{
reverse = num.charAt(i) + reverse;
}
if (num.equals(reverse))
{
System.out.println("\nEntered number IS a palindrome.");
}
else
{
System.out.println("\nEntered number is NOT a palindrome.");
}
System.out.println("\nEnter a number to check if it is a palindrome:");
}
System.out.println("\nProgram ended on request");
}
}
I would separate the palindrome test into its' own method. You could do that in a one line method like
public static boolean isPalindrome(String str) {
return new StringBuilder(str).reverse().toString().equals(str);
}
but I would prefer to iterate the first half of the characters and compare them to the second half in reverse like
public static boolean isPalindrome(String str) {
if (str == null) {
return false;
}
char[] chars = str.toCharArray();
for (int i = 0; i * 2 <= chars.length; i++) {
if (chars[i] != chars[chars.length - i - 1]) {
return false;
}
}
return true;
}
Then your main can invoke that in an infinite loop (terminating on the lack of input) like
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a number to check if it is a palindrome:");
if (!scanner.hasNextLine()) {
break;
}
String num = scanner.nextLine();
if (isPalindrome(num)) {
System.out.printf("%s is a palindrome%n", num);
} else {
System.out.printf("%s is NOT a palindrome%n", num);
}
}
System.out.println("Program ended on request");
}

How would I make this loop until the user enters a blank line in java?

import java.util.Queue;
import java.util.Scanner;
import java.util.LinkedList;
class PalindromeTest
{
public static void main(String[] args)
{
System.out.print("Enter any string:");
Scanner in = new Scanner(System.in);
String inputString = in.nextLine();
Queue queue = new LinkedList();
for (int i = inputString.length()-1; i >=0; i--)
{
queue.add(inputString.charAt(i));
}
String reverseString = "";
while (!queue.isEmpty())
{
reverseString = reverseString+queue.remove();
}
if (inputString.equals(reverseString))
System.out.println("The input String is a palindrome.");
else
System.out.println("The input String is not a palindrome.");
}
}
So this code prints out if the string input is a Palindrome, but not sure how to make it so it loops and terminates when a blank line is entered. I've tried a do while loop but had no luck
Like this maybe?
System.out.print("Enter any string:");
Scanner in = new Scanner(System.in);
String inputString; //extract the inputString as a variable
while (!(inputString = in.nextLine()).equals("")) //just add this loop, the rest is same as yours
{
Queue queue = new LinkedList();
for (int i = inputString.length() - 1; i >= 0; i--)
{
queue.add(inputString.charAt(i));
}
String reverseString = "";
while (!queue.isEmpty())
{
reverseString = reverseString + queue.remove();
}
if (inputString.equalsIgnoreCase(reverseString))
{
System.out.println("The input String is a palindrome.");
}
else
{
System.out.println("The input String is not a palindrome.");
}
System.out.print("Enter any string:");
}

Categories

Resources