palindrome program not working as expected - java

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;
}

Related

Accepting string inputs into an array and checking the availability of the string in the array

So I am completely new to java, and I want to create a code to accept string inputs from a user, and store it into an array. After this in the next statement, I will type a value into the terminal, and I want the code to compare my string input to one of the strings in the array and print available on the terminal when the string is available and vice versa. The first part of my code was right (hopefully) but I had a problem in comparing the strings. I feel it doesn't check the strings with my input in the code. Here is my code, Could anyone please help me with this? Thank you so much.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a[] = new String[20] //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() //entering a string to search
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) //I feel the problem is here
System.out.println(search + "course is available");
break;
else
System.out.println(search + "course is not available");
}
}
}
}
I expect the output to be
<string> course is available
when my string matches a string in the array and
<string> course is not available
when my entered string doesn't match a string in the array
But there is no output :(
I have modified your code and commented on line where it need to be explained. check it carefully.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
String a[] = new String[no_of_courses]; // do not assume when you have proper data.
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); // accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); // entering a string to search
boolean flag = false;
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) // I feel the problem is here
{
flag = true;//do not print here. just decide whether course is available or not
break;
}
}
//at the end of for loop check your flag and print accordingly.
if(flag) {
System.out.println(search + "course is available");
}else {
System.out.println(search + "course is not available");
}
}
}
}
class Course {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String a[] = new String[20] ; //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if(no_of_courses <= 0)
System.out.println("Invalid Range");
else
{
System.out.println("Enter course names:");
for(int i=0 ; i < no_of_courses ; i++)
{
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() ; //entering a string to search
boolean found = false;
for(int i = 0 ; i < no_of_courses ; i++)
{
if(a[i].equalsIgnoreCase(search)) //I feel the problem is here
{
**found = true;**
break;
}
}
if(found) {
System.out.println(search+ "course is available");
}else {
System.out.println(search+ "course is not available");
}
}
}
}
This is really a good effort and you almost got it. So just a couple of things
Since you are inputting the number of courses, just use that value to initialise your array (it's just a good practice to get into to try not initialise things before you actually need them).
If you are doing String comparisons and case sensitivity does not matter, rather use .equalsIgnoreCase(String)
To solve your problem, you just needed a boolean variable to indicate whether or not you had found a match. Initially this would be FALSE (no match found) and you would run through your array until a match is found. Once found this would be flagged TRUE and you'd breakout your loop (which you correctly did).
Only once out your loop, you'd print out whether you found a match.
Have a look:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0) {
System.out.println("Invalid Range");
} else {
String a[] = new String[no_of_courses];
System.out.println("Enter course names:");
for (int i = 0; i < a.length; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); //entering a string to search
boolean courseFound = Boolean.FALSE;
for(int i = 0; i < a.length; i++) {
if (a[i].equalsIgnoreCase(search)) {
courseFound = Boolean.TRUE;
break;
}
}
if(courseFound) {
System.out.println(search + "course is available");
} else {
System.out.println(search + " course is not available");
}
}
}
Oh, just for interest (and when you start working with some more advanced constructs), you could always just use stream, which was introduced in Java 8. It'll trim down 12 lines to 5...
if(Arrays.stream(a).anyMatch(i -> i.equalsIgnoreCase(search))) {
System.out.println(search + " course is available");
} else {
System.out.println(search + " course is not available");
}
I noticed a few things - Does your program run to the end? When i copy/pasted into my ide i noticed a few missing semi-colons, and like Yhlas said, your last if/else statement syntax is incorrect.
And this doesn't have anything to do with whether or not your program will give you the right answer, but your last loop will print over and over again because it will check each element in a, and each time it loops and finds a mismatch it will print something out

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);
}
}

How do you check if a string is a palindrome in 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.

Issue with Palindrome class using Stacks

I am trying to write a Palindrome class using Stacks to determine if a word entered by user is a palindrome. There seems to be an issue in my Palindrome class. Can someone please help me identify it? My program works but no matter what word I type, it returns that the word is not a palindrome.
import java.util.Stack;
public class Palindrome
{
public Palindrome()
{
Stack stack = new Stack();
String input = "";
boolean isPalindrome = false;
for(int i = 0; i < input.length(); i++)
{
stack.push(i);
}
String opposite = " ";
while(!stack.isEmpty())
{
opposite = opposite + stack.pop();
}
if(input.equals(opposite))
isPalindrome = true;
else
isPalindrome = false;
}//end main
}//end class Palindrome
Here is my PalindromeCheck class:
import java.util.Scanner;
public class PalinDromeCheck
{
public static void main(String[] args)
{
Palindrome pal = new Palindrome();
Scanner type = new Scanner(System.in); //create scanner for user to type a word
String word = null; //initial word to check
String stop = null; //stops processing of word
do
{
System.out.println("Enter a word to determine if it is a palindrome: ");
word = type.nextLine(); //user types word
if(pal.equals(word))
System.out.println("is a palindrome");
else
System.out.println("is not a palindrome\n");
System.out.println("Would you like to try another word? Type Y for 'Yes' or N for 'No'");
stop = type.nextLine(); //stops processing
}
while(stop.equalsIgnoreCase("y")); //continues to process and ignores upper or lowercase Y
}
}
You have several bugs.
First, you need to give the input to the Palindrome class.
Second, when you reverse the input using stack, you push the index on the stack, not the character.
Third, it's not a good practice to do everything une constructor. Palindrome class doesn't need to know the input as member or for initialization purpose
If you don't need to have several implementation of Palindrome, you shall use a static method.
Try this :
public class Palindrome
{
public static boolean isPalindrome(String input)
{
char[] inputArray = input.toCharArray();
bool isOk = true;
for(int i = 0; i < inputArray.length/2 && isOk; i++){
isOk &= inputArray[i] == inputArray[inputArray.length - i - 1];
}
return isOk;
} // end method
} //end class Palindrome
Then, your main function could be :
public static void main(String[] args)
{
System.out.println("Enter a word to determine if it is a palindrome: ");
word = type.nextLine(); //user types word
if(Palindrome.isPalindrome(word)) {
System.out.println("is a palindrome");
} else {
System.out.println("is not a palindrome\n");
}
} // End of main
Is this your full Palindrome-Class? If yes, it has no input to handle!
public class Palindrome
{
public static boolean isPalindrome(String input)
{
Stack stack = new Stack();
for(int i = 0; i < input.length(); i++)
{
stack.push(input.charAt(i));
}
String opposite = "";
while(!stack.isEmpty())
{
opposite = opposite + stack.pop();
}
return input.equals(opposite);
}//end main
}//end class Palindrome
this creates a static method you can use in your code like:
System.out.println("Enter a word to determine if it is a palindrome: ");
word = type.nextLine(); //user types word
if(Palindrome.isPalindrome(word))
System.out.println("is a palindrome");
else
System.out.println("is not a palindrome\n");
Your input is empty because you set input to "" in the constructor. You would be better off using a constructor argument to contain the input and then keep track of that using a member variable.
The code you typed is probably better suited to be in a method (equals perhaps? You will have to override this). You might want to consider pushing the character from the input string onto the stack rather then 0, 1, 2, 3... n (where n = input.length() - 1).
Your current .equals(word) does not do what you think it does because you have not provided an overload.

Categories