I am trying to get user input and determine if the word is a palindrome or not. The main method should be where all of the print statements are placed.
package help;
import java.util.Scanner;
public class Help {
public static Scanner user_input;
public static void main(String[] args, Iterable<String> lines) {
System.out.print("Enter a word: ");
user_input=new Scanner(System.in);
}
public static boolean istPalindrom(char[] word) {
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
}
I want it to say
if true then System.out.println(The word is a palindrome.)
else System.out.println(The word is not a palindrome.)
I am not sure how to go about this.
Add following lines into main:
if (isPalindrome(user_input))
System.out.println ("The word is a palindrome.");
else
System.out.println("The word is not a palindrome.");
Note: Try to make your indentation better in order to make code easily understandable and for visual purposes :)
Your palindrome test looks good once you fix the indentation, but it's named oddly in English. You have a Scanner, so you can get lines of input. Then call toCharArray() on the String to get the char[] like
public static void main(String[] args) {
System.out.print("Enter a word: ");
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) {
String line = input.nextLine();
if (isPalindrome(line.toCharArray())) {
System.out.printf("The word %s is a palindrome.%n", line);
} else {
System.out.printf("The word %s is not a palindrome.%n", line);
}
}
}
public static boolean isPalindrome(char[] word) {
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
This solution might work:
public static void main(String[] args, Iterable<String> lines) {
user_input = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = user_input.nextLine();
if(istPalindrome(word.toCharArray()){
System.out.println("The word is a palindrome");
}else{
System.out.println("The word is not a palindrome");
}
}
The code for palindrome as simple as this if you want to use it !
public static boolean isPalindrom(String word) {
if(new StringBuilder(word).reverse().toString().equals(word)){
System.out.println("The word is a palindrome.");
} else {
System.out.println("The word is not a palindrome.");
}
}
Related
// I'm looking for any errors or mistakes I made in the code or another way to do it with if-then statements or usage of array. (very new to java)
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
String letter = input.nextLine();
int n = letter.length();
int numberOfLetters = 0;
for (int i = 0; i < letter.length(); i++) {
numberOfLetters++;
}
if(letter.charAt(0) != letter.charAt(n-1)){
String letter2 = letter.toLowerCase();
if (letter2.charAt(0) == letter2.charAt(n - 1)) {
System.out.println("This is a palindrome " + letter);
}
else {
System.out.println("This is not a palindrome " + letter);
}
}
}
}
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");
}
}
}
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");
}
}
}
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");
}
When I compile the program is comes up with the error exception in thread "main"
I I don't know why. I'm trying to create a program that allows the user to input a word and then output whether or not the word is a palindrome
import java.util.*;
public class Palindrome{
public static void main( String[] args ){
String word=getWord();
boolean w=isPalindrome(word);
if(w==true)
System.out.println(word + " is a palindrome");
else
System.out.println(word + " is not a palindrome");
}
public static String getWord(){
Scanner keyboard = new Scanner( System.in );
String word;
System.out.print("Enter a word: ");
word=keyboard.nextLine();
return word;
}
public static boolean isPalindrome(String word){
int y=word.length();
for (int i = 0; i < y; i++) {
if (word.charAt(i) != word.charAt(y-i)
return false;
}
return true;
}
}
Line if (word.charAt(i) != word.charAt(y-i) is obviously missing right round bracket.
if (word.charAt(i) != word.charAt(y-i)) is correct.
The if statement, presumably on that line, lacks a closing paren