How do you check if a string is a palindrome in java? - java

I am trying to write a program that checks if a string is a palindrome and so far I know I am on the right path but when I enter my code it keeps on running for ever. I don't know what the problem is and would like help finding out the solution. In my program I want the user to enter word or words in the method Printpalindrome and then the program should know if the string is a palindrome or not.
Here is my code:
...
Scanner console = new Scanner (System.in);
String str = console.next();
Printpalindrome(console, str);
}
public static void Printpalindrome(Scanner console, String str) {
Scanner in = new Scanner(System.in);
String original, reverse = "";
str = in.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- ) {
reverse = reverse + str.charAt(i);
}
if (str.equals(reverse))
System.out.println("Entered string is a palindrome.");
}
}

Because of this line:
n = in.nextLine();
your program is waiting for a second input, but you already got one before entering the function.
Remove this line and it works.
Here's your program, cleaned (and tested) :
public static void main(String[] args){
Scanner console = new Scanner (System.in);
String n = console.next();
Printpalindrome(n);
}
public static void Printpalindrome(String n){
String reverse = "";
for ( int i = n.length() - 1; i >= 0; i-- ) {
reverse = reverse + n.charAt(i);
System.out.println("re:"+reverse);
}
if (n.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is NOT a palindrome.");
}
Of course, this isn't the best algorithm, but you already know there are many QA on SO with faster solutions (hint: don't build a string, just compare chars).

Remove
Scanner in = new Scanner(System.in);
and
n = in.nextLine();
from Printpalindrome function
and it should work.

This can be implemented in a far more efficient manner:
boolean isPalindrom(String s){
if (s == null /* || s.length == 0 ?*/) {
return false;
}
int i = 0, j = s.length() - 1;
while(i < j) {
if(s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
The argument for PrintPalindrom is ignored. You read another value with `in.nextLine()'. Which is the reason for your issues.

Ur code with some correction:-
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string 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 is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}

I tried your code and what i observed was that :
first of all you are making a string to enter on the line 2 of your code:
String n=console.next();
next the the program again goes to waiting when this line gets executed:
n = in.nextLine();
actually this particular line is also expecting an input so that is why the program halt at this point of time.
If you enter your String to be checked for palindrome at this point of time you would get the desired result .
But I would rather prefer you to delete the line
n = in.nextLine();
because, with this, you would have to enter two words which are ambiguous.

Related

palindrome program not working as expected

I know it's very puny thing for experts here but I want to check why my palindrome program is not working as expected, it shows as palindrome to every number or string i enter, can you please look into it where the issue is, please.
actually i'm trying to create this program on my own and not checking any ready made method for it so asking here. please help.
here's my program
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
String k = sc.next();
int s = k.length()/2;
boolean b = true;
while(s>0){
for (int i = 0; i<=s; i++) {
if(k.charAt(i)==k.charAt(s)){
b = true;
}
}
if (b)
s--;
else
System.out.println("exit");
}
if(b)
System.out.println("palindrome");
}
}
s is the midpoint, and you are modifying it in your loop. Also, you never set b to false in any condition. Fixing those two bugs, should give you something like
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
String k = sc.next();
int s = k.length() / 2;
boolean b = true; // <-- Default to true
for (int i = 0; i <= s; i++) { // <-- Only need one loop.
if (k.charAt(i) != k.charAt(k.length() - i - 1)) {
b = false; // <-- Only need to update when it isn't a palindrome.
break; // <-- terminate the loop.
}
}
if (b) { // <-- Use braces. Even when optional.
System.out.println("palindrome");
}
You might be better off writing a simple method to do the check and call that method with your input.
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
String str = sc.next();
System.out.printf("'%s' %s%n", str, (isPalindrome(str) ? "is " : "is not ") + "a palindrome.");
For inputs of radar and abcdcbc prints
'radar' is a palindrome.
'abcdcbc' is not a palindrome.
The method
public static boolean isPalindrome(String str) {
int len = str.length();
for (int i = 0; i < len / 2; i++) {
if (str.charAt(i) != str.charAt(len - i - 1)) {
return false; // return as soon as characters don't match
}
}
// if the program gets this far, the string must be a palindrome
return true;
}

I am trying to write a code but facing a java.lang.StringIndexOutOfBoundsException. Please check the code out

So I am trying to take multiple inputs.
here is the question:-
Given two strings of equal length, you have to tell whether they both strings are identical.
Two strings S1 and S2 are said to be identical, if any of the permutation of string S1 is equal to the string S2. See Sample explanation for more details.
Input :
First line, contains an intger 'T' denoting no. of test cases.
Each test consists of a single line, containing two space separated strings S1 and S2 of equal length.
Output:
For each test case, if any of the permutation of string S1 is equal to the string S2 print YES else print NO.
Constraints:
1<= T <=100
1<= |S1| = |S2| <= 10^5
String is made up of lower case letters only.
import java.io.*;
import java.util.*;
public class test
{
public static void main(String args[])throws IOException
{
String parts[]=new String[10];
Scanner sc=new Scanner(System.in);
System.out.println("Enter no of inputs");
int n=sc.nextInt();
int j=n;
for(int i=0;i<j;i++)
{
System.out.println("Enter string");
String s=sc.next();
int in=s.indexOf(" ");
String s1=s.substring(0,in);
String s2=s.substring(in+1);
boolean status = true;
if (s1.length() != s2.length())
{
status = false;
}
else
{
char[] ArrayS1 = s1.toCharArray();
char[] ArrayS2 = s2.toCharArray();
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
status = Arrays.equals(ArrayS1, ArrayS2);
}
if (status==true)
{
System.out.println(s1 + " and " + s2 + " are anagrams");
}
else
{
System.out.println(s1 + " and " + s2 + " are not anagrams");
}
}
}
}
the error
issue
The issue is the statement
String s = sc.next();
That will never consume a token with a space (because white space is the delimiter). Change it to
String s = sc.nextLine();
And then
int in = s.indexOf(" ");
will work (but only if the input contains a space); so you should still test it is not -1 yourself.
if (in >= 0) {
String s1 /* ... */
}
Also,
int n=sc.nextInt();
will leave trailing newlines (and skip your next input) using nextLine() so consume that too.
int n=sc.nextInt();
sc.nextLine(); // <-- skip trailing new line.
Change your code as follows:
System.out.print("Enter no of inputs: ");
int n = Integer.parseInt(sc.nextLine());
for (int i = 0; i < n; i++) {
System.out.print("Enter string: ");
String s = sc.nextLine();
...
...
...
}
A sample run:
Enter no of inputs: 3
Enter string: Hello Hi
Hello and Hi are not anagrams
Enter string:
I recommend you go through Scanner is skipping nextLine() after using next() or nextFoo()? for a better understanding of Scanner.
Try this:
System.out.println("Enter string");
sc.nextLine();
String s = sc.nextLine();
Try below code. It print YES and NO according to your requirement.
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
// Main Class
public class ThreadGroupDemo implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) throws IOException {
String parts[] = new String[10];
Scanner sc = new Scanner(System.in);
System.out.println("Enter no of inputs");
int n = Integer.parseInt(sc.nextLine());
int j = n;
for (int i = 0; i < j; i++) {
System.out.println("Enter string");
String s = sc.nextLine();
int in = s.indexOf(" ");
String s1 = s.substring(0, in);
String s2 = s.substring(in + 1);
boolean status = true;
if (s1.length() != s2.length()) {
status = false;
} else {
char[] ArrayS1 = s1.toCharArray();
char[] ArrayS2 = s2.toCharArray();
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
status = Arrays.equals(ArrayS1, ArrayS2);
}
if (status == true) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
I hope it helps.

Palindrome Checker with nested loops thats checks the input and then flips its to compare

Im stuck on this, I need a code that use 2 nested loops for this assignment (there are other solutions, but I need to demonstrate my understanding of nested loops). But I just dont get it. The outer loop repeats the entire algorithm and the inner loop iterates half-way (or less) through the string. I am not sure on what I need to put inside the for loops. This is what I have so far. Any Assistance would be pleasured.
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String x = 0;
String y = input.length-1;
for (String i = 0; i < line.length-1; i ++){
for (String j = 0; j < line.length-1; j ++){
if (input.charAt(x) == input.charAt(y))
{
x++;
y--;
}
}
}
}
Example Output:
Enter a string: 1331
1331 is a palindrome.
Enter a string: racecar
racecar is a palindrome.
Enter a string: blue
blue is NOT a palindrome.
Enter a string:
Empty line read - Goodbye!
Your algorithm is flawed, your nested loop should be to prompt for input - not to check if the input is a palindrome (that requires one loop itself). Also, x and y appear to be used as int(s) - but you've declared them as String (and you don't actually need them). First, a palindrome check should compare characters offset from the index at the beginning and end of an input up to half way (since the offsets then cross). Next, an infinite loop is easy to read, and easy to terminate given empty input. Something like,
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a string: ");
System.out.flush();
String line = input.nextLine();
if (line.isEmpty()) {
break;
}
boolean isPalindrome = true;
for (int i = 0; i * 2 < line.length(); i++) {
if (line.charAt(i) != line.charAt(line.length() - i - 1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.printf("%s is a palindrome.%n", line);
} else {
System.out.printf("%s is NOT a palindrome.%n", line);
}
}
System.out.println("Empty line read - Goodbye!");
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String reversedText ="";
for(int i=line.length()-1/* takes index into account */;i>=0;i++) {
reversedText+=line.split("")[i]; //adds the character to reversedText
}
if(reversedText ==line){
//is a palidrome
}
}
Your code had lot of errors. I have corrected them and used a while loop to check if its a palindrome or not. Please refer below code,
import java.util.Scanner;
public class Post {
public static void main(String[] args) {
String line;
boolean isPalindrome = true;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
int x = 0;
int y = line.length() - 1;
while (y > x) {
if (line.charAt(x++) != line.charAt(y--)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println(line + " is a palindrome");
} else {
System.out.println(line + "is NOT a palindrome");
}
System.out.println();
}
}
}

Sentence Capitalizer with specific requirement

It's hard to explain but I'm trying to create a program that only capitalizes the letter of every word that ends with a period, question mark, or exclamation point. I have managed to receive a result when inputting any of the marks but only when it is entered the second time. In other words I have to hit enter twice to get a result and I'm not sure why. I am still working on it on my own but I'm stuck at this problem.
import java.util.*;
public class SentenceCapitalizer
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Input a sentence: ");
String line = keyboard.nextLine();
String wrong = keyboard.nextLine();
String[] check = {".!?"};
String upper_case_line="";
Scanner lineScan = new Scanner(line);
for (String sent : check)
{
if (sent.startsWith(wrong))
{
System.out.println("cant use .?!");
}
else
{
/* if (line.startsWith(" "))//if starts with space
System.out.println("good");
else
System.out.println("bad");
*/
//if (int i = 0; i < line.length; i++)
//{char c = line.chartAt(i);
while(lineScan.hasNext())
{
String word = lineScan.next();
upper_case_line += Character.toUpperCase(word.charAt(0)) +
word.substring(1) + " ";
}
System.out.println(upper_case_line.trim());
}
}
}
}
Solution
Hey just a quick solution for your question. Converts the string to character array and then checks the character array for '.!?' if it finds the value then it will make the next letter a capital!
public class SentenceCapitalizer {
public static void main(String[] args) {
//Scanner, Variable to hold ouput
Scanner keyboard = new Scanner(System.in);
System.out.print("Input a sentence: ");
String line = keyboard.nextLine();
//Char array, boolean to check for capital
char [] lineChars = line.toCharArray();
boolean needCapital = false;
//String to hold output
String output = "";
//Check for period in line
for (int i = 0; i < lineChars.length; i++) {
//Make sure first char is upper case
if (i == 0) {
lineChars[i] = Character.toUpperCase(lineChars[i]);
}
//Check for uppercase if char is not space
if (needCapital && Character.isLetter(lineChars[i])) {
lineChars[i] = Character.toUpperCase(lineChars[i]);
needCapital = false;
}
if (lineChars[i] == '.' || lineChars[i] == '?' || lineChars[i] == '!') {
needCapital = true;
}
//Add character to string
output += lineChars[i];
}
//Output string
System.out.println (output);
}
}

Scanner only reading first set of input

This is a code I have developed to separate inputs by the block (when a space is reached):
import java.util.Scanner;
public class Single {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Three Numbers:");
String numbers = in.next();
int length = numbers.length();
System.out.println(length);
int sub = length - length;
System.out.println(sub);
System.out.println(getNumber(numbers, length, sub));
System.out.println(getNumber(numbers, length, sub));
System.out.println(getNumber(numbers, length, sub));
}
public static double getNumber(String numbers, int length, int sub){
boolean gotNumber = false;
String currentString = null;
while (gotNumber == false){
if (numbers.substring(sub, sub + 1) == " "){
sub = sub + 1;
gotNumber = true;
} else {
currentString = currentString + numbers.substring(sub, sub);
sub = sub + 1;
}
}
return Double.parseDouble(currentString);
}
}
However, it only reads the first set for the string, and ignores the rest.
How can I fix this?
The problem is here. You should replace this line
String numbers = in.next();
with this line
String numbers = in.nextLine();
because, next() can read the input only till the first space while nextLine() can read input till the newline character. For more info check this link.
If I understand the question correctly, you are only calling in.next() once. If you want to have it process the input over and over again you want a loop until you don't have any more input.
while (in.hasNext()) {
//do number processing in here
}
Hope this helps!

Categories