package school;
import java.util.*;
public class PalindromeWords {
boolean palindrome(String S) {
String check="";
for(int i = S.length()-1;i>=0;i--) {
check = check+S.charAt(i);
}
if(check.equalsIgnoreCase(S)) {
return true;
}
else {
return false;
}
}
public static void main(String args[]) {
PalindromeWords ob = new PalindromeWords();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence.");
String S=sc.nextLine();
S = S + ' ';
int flag = 0,i=0;
String word;
for(i=0;i<S.length();i++) {
if(S.charAt(i)==' ') {
word = S.substring(flag,i);
if(ob.palindrome(word)) {
System.out.println(word);
flag =i+1;
}
}
}
}
}
I have been given an assignment in which I have to Write a Java Program to Print all the Palindrome words in a sentence. This is the code I wrote and I am not getting the correct output.
As you can see the output in the console gives no query in result.
You should move the step which increase flag outside if statement. Otherwise, it only works if the first word is palindrome.
if(ob.palindrome(word)) {
System.out.println(word);
}
flag = i+1;
Use the flag outside the loop.
if(ob.palindrome(word)==true) {
System.out.println(word);
}
flag =i+1;
This code should work.
Here is another solution as follows:
code:
import java.util.*;
public class PalindromeWords
{
boolean isPalindrome(String S)
{
boolean result = false;
String check="";
for(int i = S.length()-1;i>=0;i--)
{
check = check+S.charAt(i);
}
if(check.equalsIgnoreCase(S))
{
result = true;
}
return result;
}
public static void main(String args[])
{
PalindromeWords ob = new PalindromeWords();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence.");
String str = sc.nextLine();
String[] words = str.split(" ");
for(int i=0; i < words.length; i++)
{
if(ob.isPalindrome(words[i]))
{
System.out.println(words[i]);
}
}
}
}
output:
Enter the sentence.
hello mAdam
mAdam
boolean palindrome(String S){
String check="";
for(int i = S.length()-1;i>=0;i--)
{
check = check+S.charAt(i);
}
if(check.equalsIgnoreCase(S)==true)
{
return true;
}
else
{
return false;
}
}
public static void main(String args[])
{
Para ob = new Para();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence.");
String S=sc.nextLine();
S = S + ' ';
int flag = 0,i=0;
String word;
for(i=0;i<S.length();i++)
{
if(S.charAt(i)==' ')
{
word = S.substring(flag,i);
if(ob.palindrome(word)==true)
{
System.out.println(word);
}flag =i+1;
}
}
}
Related
import java.util.Scanner;
public class Pailindrome {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter a word");
String ori = sc1.nextLine();
isPailindrome(ori);
if (isPailindrome(ori))
System.out.println(ori + "is a Pailindrome");
else
System.out.println(ori + "is NOT a Pailindrome");
}
public static boolean isPailindrome(String ori) {
int i = 0;
int j = ori.length() - 1;
while (i < j) {
if (ori.charAt(i) != ori.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}
The code works perfectly I'm just confused how I will get it to work irrespective of the case
inputted by the user. For example aBba is a palindrome but It says it's not in the code I've done. I
would like any help if possible thanks.
You can convert all of the letters to lowerCase before you start the processing.
You can write your own function or use toLowerCase() String function.
import java.util.Scanner;
public class Pailindrome {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter a word");
String ori = sc1.nextLine();
ori = ori.toLowerCase();
isPailindrome(ori);
if (isPailindrome(ori))
}
System.out.println(ori + "is a Pailindrome");
} else {
System.out.println(ori + "is NOT a Pailindrome");
}
}
public static boolean isPailindrome(String ori) {
int i = 0;
int j = ori.length() - 1;
while (i < j) {
if (ori.charAt(i) != ori.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
Take the input and call toUpper(); that way when you check to see if it is a palindrome, all of the characters are uppercase.
String ori = scr.nextLint();
if(isPalindrome(ori.toUpperCase()))
//do something
Convert all the cases to lowercase/uppercase before checking the palindrome
isPailindrome(ori.toLowerCase());
Zoom in from both ends and adjust the case as required.
public static boolean isPalindrome(String str) {
int len = str.length();
for (int i = 0; i < len >>1; i++) {
if (Character.toLowerCase(str.charAt(i)) !=
Character.toLowerCase(str.charAt(len - i - 1))) {
return false;
}
}
return true;
}
public static void main(String[] args)
{
Scanner sentence = new Scanner(System.in);
System.out.println("This program will determine if an inputted phrase is a palindrome.");
System.out.println(" ");
System.out.println("Enter a phrase, word, or sentence:");
String a = sentence.nextLine();
String b = a.toLowerCase().replaceAll("[^a-z]"," "); //as long as the words are spelt the same way, the caps don't matter and it ignores spaces and punctuation
System.out.println();
System.out.println(palindromeChecker(b)); //calls method
}
public static String palindromeChecker(String b)
{
String reverse = new StringBuilder(b).reverse().toString();
String c;
if(b.equals(reverse)) {
c = "The word " +b+ " is a palindrome"; }
else {
c = "The word " +b+ " is not a palindrome"; }
return c;
}
}
My, problem is that for example, if i do Eva, can I see bees in a cave? It should be a palindrome, however it's not can u please help me with this and please try not to make it complicated.
Replace:
String b = a.toLowerCase().replaceAll("[^a-z]"," ");
With
String b = a.toLowerCase().replaceAll("[^a-z]","");
Otherwise, you're replacing non-alphabetical characters with spaces, which can influence the checking of the reverse String.
You need to remove all non-letters from your string:
public class Palindrome {
public static String strip(String s) {
return s.toLowerCase().replaceAll("[^a-z]", "");
}
public static boolean isPalindrome(String s) {
for (int i = 0; i < s.length() / 2; i++) {
if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(strip("Eva, can I see bees in a cave?"));
System.out.println(isPalindrome(strip("Eva, can I see bees in a cave?")));
}
}
Output:
evacaniseebeesinacave
true
public class PalindromeStringWithReverse {
public static void main(String[] args) {
String str = "21raceca r12";
str = str.replaceAll(" ", "");
boolean isPalindrome = false;
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) == str.charAt((str.length() - 1) - i)) {
isPalindrome = true;
continue;
}
isPalindrome = false;
}
if (isPalindrome) {
System.out.println("Palindrome");
} else {
System.out.println("not palindrome");
}
}
}
Please help me with the full code modified by someone again. I have tried, but error is coming as StringIndexOutOfBoundsException. I am able to enter just the input from the user.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RemoveVowels{
public static void main(String []args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Sample Program to Remove Vowels");
System.out.println("from a given string \n");
System.out.println("Enter a words : ");
String s = in.readLine();
System.out.println("\n" + "String with Vowels removed : ");
String r = removeVowels(s);
System.out.println(r);
}
private static String removeVowels(String s) {
String finalString = "";
for(int i = 0; i < s.length(); i++) {
if(!isVowel(Character.toLowerCase(s.charAt(i)))) {
finalString = finalString + s.charAt(i);
}
}
return finalString;
}
private static boolean isVowel(char c) {
String vowels = "aeiou";
for(int i = 0; i < 5; i++) {
if(c == vowels.charAt(i))
return true;
}
return false;
}
}
Add throws declaration to the method:
public static void main(String []args) throws IOException
or surround the code with try/catch:
try
{
s = in.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
You haven't included in your code to sort the string alphabetically, you can do that as follows:
private static String ascending(String s)
{
char[] asc = s.toCharArray();
Arrays.sort(asc);
String sorted = new String(asc);
return sorted;
}
Complete code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class RemoveVowels{
public static void main(String []args) throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Sample Program to Remove Vowels from a given string \n");
System.out.println("Enter a line : ");
String s=in.readLine();
System.out.println("\n" + "String with Vowels removed : ");
String r=removeVowels(s);
System.out.println(r);
}
private static String removeVowels(String s)
{
String finalString="";
for(int i=0;i<s.length(); i++)
{
if(!isVowel(Character.toLowerCase(s.charAt(i))))
{
finalString=finalString+s.charAt(i);
}
}
finalString= ascending(finalString);
return finalString;
}
private static String ascending(String s)
{
char[] asc = s.toCharArray();
Arrays.sort(asc);
String sorted = new String(asc);
return sorted;
}
private static boolean isVowel(char c)
{
String vowels="aeiou";
for(int i=0; i<5; i++)
{
if(c==vowels.charAt(i))
return true;
}
return false;
}
}
The output is
Sample Program to Remove Vowels
from a given string
Enter a words :
astalavista baby
String with Vowels removed :
stlvst bby
Here is your updated code, you were missing the try catch statement:
package removevowels;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RemoveVowels {
public static void main(String []args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Sample Program to Remove Vowels");
System.out.println("from a given string \n");
System.out.println("Enter a words : ");
String s = in.readLine();
System.out.println("\n" + "String with Vowels removed : ");
String r = removeVowels(s);
System.out.println(r);
}
catch (IOException ed){}
}
private static String removeVowels(String s) {
String finalString = "";
for (int i = 0;i < s.length(); i++) {
if (!isVowel(Character.toLowerCase(s.charAt(i)))) {
finalString = finalString + s.charAt(i);
}
}
return finalString;
}
private static boolean isVowel(char c) {
String vowels = "aeiou";
for (int i=0; i<5; i++) {
if (c == vowels.charAt(i))
return true;
}
return false;
}
}
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()));
}
}
}
Im trying to make a program to take input for a string from the scanner, but i want to break up the string that was inputed and reverse the order of words. This is what i have so far.
Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
StringBuilder welcome = new StringBuilder(input.next());
int i;
for( i = 0; i < welcome.length(); i++ ){
// Will recognize a space in words
if(Character.isWhitespace(welcome.charAt(i))) {
Character a = welcome.charAt(i);
}
}
What I want to do is after it recognizes the space, capture everything before it and so on for every space, then rearrange the string.
Edit after questions.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main( String[] args ) {
final String welcome = "How should we get words in string form a List?";
final List< String > words = Arrays.asList( welcome.split( "\\s" ));
Collections.reverse( words );
final String rev = words.stream().collect( Collectors.joining( ", " ));
System.out.println( "Your sentence, reversed: " + rev );
}
}
Execution:
Your sentence, reversed: List?, a, form, string, in, words, get, we, should, How
I did suggest first reverse the whole string.
Then reverse the substring between two spaces.
public class ReverseByWord {
public static String reversePart (String in){
// Reverses the complete string
String reversed = "";
for (int i=0; i<in.length(); i++){
reversed=in.charAt(i)+reversed;
}
return reversed;
}
public static String reverseByWord (String in){
// First reverses the complete string
// "I am going there" becomes "ereht gniog ma I"
// After that we just need to reverse each word.
String reversed = reversePart(in);
String word_reversal="";
int last_space=-1;
int j=0;
while (j<in.length()){
if (reversed.charAt(j)==' '){
word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, j));
word_reversal=word_reversal+" ";
last_space=j;
}
j++;
}
word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, in.length()));
return word_reversal;
}
public static void main(String[] args) {
// TODO code application logic here
System.out.println(reverseByWord("I am going there"));
}
}
Here is the way you can reversed the word in entered string:
Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
String s = input.next();
if(!s.trim().contains(' ')) {
return s;
}
else {
StringBuilder reversedString = new StringBuilder();
String[] sa = s.trim().split(' ');
for(int i = sa.length() - 1; i >= 0: i - 1 ) {
reversedString.append(sa[i]);
reversedString.append(' ');
}
return reversedString.toString().trim();
}
Hope this helps.
If you wanted to reduce the number of line of code, I think you can look into my code :
package com.sujit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StatementReverse {
public static void main(String[] args) throws IOException {
String str;
String arr[];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string:");
str = br.readLine();
arr = str.split("\\s+");
for (int i = arr.length - 1;; i--) {
if (i >= 0) {
System.out.print(arr[i] + " ");
} else {
break;
}
}
}
}
public class StringReverse {
public static void main(String[] args) {
String str="This is anil thakur";
String[] arr=str.split(" ");
StringBuilder builder=new StringBuilder("");
for(int i=arr.length-1; i>=0;i--){
builder.append(arr[i]+" ");
}
System.out.println(builder.toString());
}
}
Output: thakur anil is This
public class ReverseWordTest {
public static String charRev(String str) {
String revString = "";
String[] wordSplit = str.split(" ");
for (int i = 0; i < wordSplit.length; i++) {
String revWord = "";
String s2 = wordSplit[i];
for (int j = s2.length() - 1; j >= 0; j--) {
revWord = revWord + s2.charAt(j);
}
revString = revString + revWord + " ";
}
return revString;
}
public static void main(String[] args) {
System.out.println("Enter Your String: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(charRev(str));
}
public static void main(String[]args)
{
String one="Hello my friend, another way here";
String[]x=one.split(" ");
one="";
int count=0;
for(String s:x){
if(count==0||count==x.length) //that's for two edges.
one=s+one;
else
one=s+" "+one;
count++;
}
System.out.println(one); //reverse.
}