Palindrome number check- issue with output - java

I tried to write a program to check whether a number is a palindrome or not in Java. I tried to convert int to String, and using built-in methods, wrote this logic. But I don't know why I am getting incorrect output for the given input.
class Main {
public static void main(String[] args) {
int x=1213;
StringBuilder s= new StringBuilder();
s.append(x);
StringBuilder s2=new StringBuilder();
s2=s.reverse();
if((s.toString()).equals(s2.toString()))
{
System.out.println(x+" is a palindrome number");
}
else{
System.out.println(x+"is not a palindrome number");
}
}

s2=s.reverse();
Here the StringBuilder class is not immutable , reverse operation will reverse the content of the original the StringBuilder s, you should construct a new StringBuilder here :
public class Main {
public static void main(String[] args) {
int x=1213;
StringBuilder s= new StringBuilder();
s.append(x);
StringBuilder s2=new StringBuilder();
s2=new StringBuilder(s).reverse();
if((s.toString()).equals(s2.toString()))
{
System.out.println(x+" is a palindrome number");
}
else{
System.out.println(x+"is not a palindrome number");
}
}
}

You call s.reverse(), which reverses s in place; and you assign it to s2, so s and s2 are the same object.
You don't need two StringBuilders at all, since you only need to make one modification.
StringBuilder sb = new StringBuilder();
sb.append(x);
sb.reverse();
if (sb.toString().equals(String.valueOf(x))) {
// the number is a palindrome
}

Related

I cant make the indexOf method to work based on an integer

I have to write a program that where one inputs a String and the program returns the backwards version of that String. I am using an indexOf method to count the letters in it and then invert it. The code I'm using is:
MAIN CLASS
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("enter word");
String word = in.nextLine;
word = in.nextLine;
String separate[];
Reverse rev = new Reverse();
rev.returnrev(word, separate);
rev.print(separate);
}
}
METHOD CLASS
public class Reverse{
public String returnrev(String word, String separate[]){
int len = word.length();
separate = new String[len];
for(int i=0;i<len;i++){
separate[i] = word.indexOf(len-i, len-i+1);
};
}
public String print(String separate[]){
int slen = separate.length;
for(int i=0;i<slen;i++){
System.out.print(separate[i]);
}
}
}
Read the API for the String.indexOf(...) method. It does not do what you think it does. The indexOf(...) method returns an "int" value, not a String value.
I think you want to use the String.substring(...) method (based on your existing logic). It does return a String value.

How do I replace more than one type of Character in Java String

newbie here. Any help with this problem would be appreciated:
You are given a String variable called data that contain letters and spaces only. Write the Java class to print a modified version of the String where all lowercase letters are replaced by ? and all whitespaces are replaced by +. An example is shown below: I Like Java becomes I+L???+J???.
What I have so far:
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String data;
//prompt
System.out.println("Enter a sentence: ");
//input
data = input.nextLine();
for (int i = 0; i < data.length(); i++) {
if (Character.isWhitespace(data.charAt(i))) {
data.replace("", "+");
if (Character.isLowerCase(data.charAt(i))) {
data.replace(i, i++, ); //not sure what to include here
}
} else {
System.out.print(data);
}
}
}
any suggestions would be appreciated.
You can do it in two steps by chaining String#replaceAll. In the first step, replace the regex, [a-z], with ?. The regex, [a-z] means a character from a to z.
public class Main {
public static void main(String[] args) {
String str = "I Like Java";
str = str.replaceAll("[a-z]", "?").replaceAll("\\s+", "+");
System.out.println(str);
}
}
Output:
I+L???+J???
Alternatively, you can use a StringBuilder to build the desired string. Instead of using a StringBuilder variable, you can use String variable but I recommend you use StringBuilder for such cases. The logic of building the desired string is simple:
Loop through all characters of the string and check if the character is a lowercase letter. If yes, append ? to the StringBuilder instance else if the character is whitespace, append + to the StringBuilder instance else append the character to the StringBuilder instance as it is.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I Like Java";
StringBuilder sb = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (Character.isLowerCase(ch)) {
sb.append('?');
} else if (Character.isWhitespace(ch)) {
sb.append('+');
} else {
sb.append(ch);
}
}
// Assign the result to str
str = sb.toString();
// Display str
System.out.println(str);
}
}
Output:
I+L???+J???
If the requirement states:
The first character of each word is a letter (uppercase or lowercase) which needs to be left as it is.
Second character onwards can be any word character which needs to be replaced with ?.
All whitespace characters of the string need to be replaced with +.
you can do it as follows:
Like the earlier solution, chain String#replaceAll for two steps. In the first step, replace the regex, (?<=\p{L})\w, with ?. The regex, (?<=\p{L})\w means:
\w specifies a word character.
(?<=\p{L}) specifies a positive lookbeghind for a letter i.e. \p{L}.
In the second step, simply replace one or more whitespace characters i.e. \s+ with +.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I like Java";
str = str.replaceAll("(?<=\\p{L})\\w", "?").replaceAll("\\s+", "+");
System.out.println(str);
}
}
Output:
I+l???+J???
Alternatively, again like the earlier solution you can use a StringBuilder to build the desired string. Loop through all characters of the string and check if the character is a letter. If yes, append it to the StringBuilder instance and then loop through the remaining characters until all characters are exhausted or a space character is encountered. If a whitespace character is encountered, append + to the StringBuilder instance else append ? to it.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I like Java";
StringBuilder sb = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i++);
if (Character.isLetter(ch)) {
sb.append(ch);
while (i < len && !Character.isWhitespace(ch = str.charAt(i))) {
sb.append('?');
i++;
}
if (Character.isWhitespace(ch)) {
sb.append('+');
}
}
}
// Assign the result to str
str = sb.toString();
// Display str
System.out.println(str);
}
}
Output:
I+l???+J???
package com.company;
import java.util.*;
public class dat {
public static void main(String[] args) {
System.out.println("enter the string:");
Scanner ss = new Scanner(System.in);
String data = ss.nextLine();
for (int i = 0; i < data.length(); i++) {
char ch = data.charAt(i);
if (Character.isWhitespace(ch))
System.out.print("+");
else if (Character.isLowerCase(ch))
System.out.print("?");
else
System.out.print(ch);
}
}
}
enter the string:
i Love YouU
?+L???+Y??U
Firstly, you are trying to make changes to String object which is immutable. Simple way to achieve what you want is convert string to character array and loop over array items:
Scanner input = new Scanner(System.in);
String data;
//prompt
System.out.println("Enter a sentence: ");
//input
data = input.nextLine();
char[] dataArray = data.toCharArray();
for (int i = 0; i < dataArray.length; i++) {
if (Character.isWhitespace(dataArray[i])) {
dataArray[i] = '+';
} else if (Character.isLowerCase(dataArray[i])) {
dataArray[i] = '?';
}
}
System.out.print(dataArray);
See the below code and figure out what's wrong in your code. To include multiple regex put the char within square brackets:
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String data = input.nextLine();
String one = data.replaceAll(" ", "+");
String two = one.replaceAll("[a-z]", "?");
System.out.println(two);
}
}
You can use String.codePoints method to get a stream over int values of characters of this string, and process them:
private static String replaceCharacters(String str) {
return str.codePoints()
.map(ch -> {
if (Character.isLowerCase(ch))
return '?';
if (Character.isWhitespace(ch))
return '+';
return ch;
})
.mapToObj(Character::toString)
.collect(Collectors.joining());
}
public static void main(String[] args) {
System.out.println(replaceCharacters("Lorem ipsum")); // L????+?????
System.out.println(replaceCharacters("I Like Java")); // I+L???+J???
}
See also: Replace non ASCII character from string

Palindrome problems with a for loop [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
Hi I'm trying to build a palindrome but it seem to be not working, please could you help. I'm expected to catch true on dad and false on other things
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Your User Name");
String userInput =input.nextLine();
System.out.println(abcDEF(userInput));
}
static boolean abcDEF(String userInput) {
StringBuilder s1 = filter(userInput);
StringBuilder s2 = reverse(userInput);
return s1.toString() == s2.toString();
}
static StringBuilder filter(String userInput) {
StringBuilder sb = new StringBuilder();
char[] inputData = userInput.toCharArray();
for (int i = 0; i < userInput.length(); i++) {
if (userInput.matches("[a-zA-Z0-9]+")) {
sb.append(inputData[i]);
}
}
return sb;
}
static StringBuilder reverse(String userInput) {
StringBuilder sb = filter(userInput);
sb.reverse();
return sb;
}
change your abcDEF() to this(last line):
static boolean abcDEF(String userInput) {
StringBuilder s1 = filter(userInput);
StringBuilder s2 = reverse(userInput);
return s1.toString().equals(s2.toString());
}
You are comparing the references of two strings in your code, which is not same in your case. Rather, you should compare the content of the strings. And this is how String contents are compared.

Palindrome gets terminated

Main Class (required)
import java.util.*;
public class FindingPalindrome {
private String inputString;
private Stack<Character> stack = new Stack<Character>();
public FindingPalindrome(String str)
{
inputString = str;
fillStack();
}
public void fillStack()
{
for(int i = 0; i < inputString.length(); i++)
{
stack.push(inputString.charAt(i));
}
}
public String reverseString()
{
String result = new String();
while(!stack.isEmpty())
{
result = result.concat(Character.toString(stack.pop()));
}
return result;
}
public boolean isPalindrome()
{
if(inputString.equalsIgnoreCase(reverseString()))
return true;
else return false;
}
}
Tester Class (required)
import java.util.*;
public class TestPalindrome
{
private static Scanner s;
public static void main(String args[])
{
s = new Scanner(System.in);
System.out.println("Enter the string");
// Read the data
String st1=s.nextLine();
// Create StringBuffer obj for st1
StringBuffer sb=new StringBuffer(st1);
// Reverse the letters
sb.reverse();
st1 = st1.toLowerCase().replaceAll("[^a-z]","");
// Check & Print if palindrome
if(st1.equals(sb.toString()))
System.out.println("Palindrome String");
}
}
Whenever I add "Stop! pots" the code terminates itself and doesn't print the output. I also added the replaceAll(), but it didn't work either. Simple palindrome works "ada", "Kayak", but palindrome with spaces and characters is not working
You are doing it in the wrong order:
// Read the data
String st1=s.nextLine();
// Create StringBuffer obj for st1
StringBuffer sb=new StringBuffer(st1);
// Reverse the letters
sb.reverse();
st1 = st1.toLowerCase().replaceAll("[^a-z]",""); // <<<<<<< too late.
// You created sb with the original
// including punctuation
// Check & Print if palindrome
if(st1.equals(sb.toString()))
System.out.println("Palindrome String");
Replace with
// Read the data
String st1=s.nextLine();
st1 = st1.toLowerCase().replaceAll("[^a-z]",""); // <<<< moved this
// Create StringBuffer obj for st1
StringBuffer sb=new StringBuffer(st1); // <<<< now this is a copy without punctuation
// Reverse the letters
sb.reverse();
// Check & Print if palindrome
if(st1.equals(sb.toString()))
System.out.println("Palindrome String");

Capitalize every word using Scanner(System.in) Java

This code should allow the user to input a sentence, change it to lower case, and then capitalize the first letter of each word. But I can't get the scanner to work, it just prints nothing. Any suggestions?
public class Capitalize
{
public static void capCase(String theString)
{
String source = theString;
StringBuffer res = new StringBuffer();
char[] chars = theString.toLowerCase().toCharArray();
boolean found = false;
for(int i = 0; i<chars.length; i++)
{
if(!found&& Character.isLetter(chars[i])){
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i])){
found = true;
}
}
}
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
System.out.println(scanner.next());
}
}
Problems as I see them:
The code as it stands will only print the first word typed in once the user presses enter
The method doesn't return anything, so effectively it does all that work and discards it.
So here is what I might do:
I'm going to put everything in main for the sake of concision
public class Capitalize {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String sentence = Scanner.nextLine();
StringBuilder ans = new StringBuilder(); // result
for(String s : sentence.split(" ")) { // splits the string at spaces and iterates through the words.
char[] str = s.toLowerCase().toCharArray(); // same as in OPs code
if(str.Length>0) // can happen if there are two spaces in a row I believe
str[0]=Character.toUpperCase(str[0]); // make the first character uppercase
ans.Append(str); // add modified word to the result buffer
ans.Append(' '); // add a space
}
System.out.println(ans);
}
}
You forgot to call the capCase() method, your code only asks for input from stdin and prints it out straight
I tried running the program in main method it runs fine for me. But if you want to get the whole sentence you will have to call scanner like an iterator and then get each next token bu calling scanner.next() method Scanner deliminates words in a sentence on the basis of white spaces. my example implementation is as follows. The you can pass each word in the your function to process it.
`public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
while (scanner.hasNext())
System.out.println(scanner.next());
}`
I would probably do this
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) { // While there is input.
String line = scanner.nextLine(); // read a line.
int i = 0;
for (String s : line.split(" ")) { // split on space... word(s).
if (i != 0) {
System.out.print(" "); // add a space, except for the first word on a line.
}
System.out.print(capCase(s)); // capCase the word.
i++; // increment our word count.
}
System.out.println(); // add a line.
System.out.flush(); // flush!
}
}
public static String capCase(String theString) {
if (theString == null) {
return ""; // Better safe.
}
StringBuilder sb = new StringBuilder(theString
.trim().toLowerCase()); // lowercase the string.
if (sb.length() > 0) {
char c = sb.charAt(0);
sb.setCharAt(0, Character.toUpperCase(c)); // uppercase the first character.
}
return sb.toString(); // return the word.
}
Problem :
1.you need to send the complete Line and send the String to the function capCase()
2.You are not returning the char array back to the caller.
Solution
1.use the below statement to read complete Line
String str=scanner.nextLine();
2.Change return type of capCase() from void to char[] as below:
public static char[] capCase(String theString)
you should return the char[] variable chars from capCase() function as below:
return chars;
Complete Code:
public static char[] capCase(String theString)
{
String source = theString;
StringBuffer res = new StringBuffer();
char[] chars = theString.toLowerCase().toCharArray();
boolean found = false;
for(int i = 0; i<chars.length; i++)
{
if(!found&& Character.isLetter(chars[i])){
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i])){
found = true;
}
}
return chars;
}
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
String str=scanner.nextLine();
System.out.println(capCase(str));
}
Try,
public static void main(String[] args) {
System.out.println(capCase("hello world"));
}
public static String capCase(String theString) {
StringBuilder res = new StringBuilder();
String[] words=theString.split(" +");
for (String word : words) {
char ch=Character.toUpperCase(word.charAt(0));
word=ch+word.substring(1);
res.append(word).append(" ");
}
return res.toString();
}
Try this code it worked for me:
import java.util.Scanner;
public class Capitalize {
/**
* This code should allow the user to input a sentence, change it to lower
* case, and then capitalize the first letter of each word. But I can't get
* the scanner to work, it just prints nothing. Any suggestions?
*
* #param theString
*/
public static void capCase(String theString) {
String source = theString.trim();
StringBuffer res = new StringBuffer();
String lower = theString.toLowerCase();
String[] split = lower.split(" ");
for (int i = 0; i < split.length; i++) {
String temp = split[i].trim();
if (temp.matches("^[a-zA-Z]+")) {
split[i] = temp.substring(0, 1).toUpperCase()
+ temp.substring(1);
}
res.append(split[i] + " ");
}
System.out.println(res.toString());
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
capCase(scanner.nextLine());
// System.out.println(scanner.next());
}
}
I've tested it. It works.
import java.util.Scanner;
import org.apache.commons.lang3.text.WordUtils;
public class Capitalize {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(s.hasNextLine()) {
System.out.println(WordUtils.capitalize(s.nextLine()));
}
}
}

Categories