So i decided to print all palindrome words in a string. I didnt use arrays or the method to find palindrome of only 3-character-words.Here is my code,the problem being,it prints out nothing
import java.util.Scanner;
class Pa{
public static void main(String[] args){
Scanner sc = new Scanner (System.in);
String s=sc.nextLine();
char b;
int i,a;
String st="";/to extract a word
s=s+" ";
String t="";/to extract the reverse of the word
a=s.length();
for(i=0;i<a;i++){
b=s.charAt(i);
if(b!=' '){
st=st+b;/word
t=b+st;/reversed word
} else {
if(st.equals(t)){
System.out.println(st);
}
st="";
t="";
}
}
}
}
I cannot figure out what's wrong and would not appreciate the split or 3-word palindrome finder options or the normal even-or-odd only palindrome finding options.
To check whether a String is a Palindrom a single loop is sufficient
public static boolean isPalindrom(String word) {
word = word.toLowerCase();
for (int i = 0; i < word.length() / 2; i++) {
if (word.charAt(i) != word.charAt(word.length() - (i + 1))) {
return false;
}
}
return true;
}
Then you can split your input string at every whitespace like input.split("\\s") and check for every word if it's a palindrom
The simplest way to check palindrome:
private static boolean isPalindrom(String s) {
return s.equals(new StringBuilder(s).reverse().toString());
}
Your problem is below. Instead of appending b to the reversed string, you're appending it to the normal string.
b=s.charAt(i);
if(b!=' '){
st=st+b;
t=b+st; // This should be t=b+t
} else {
//input-mom gives me a pen(reverse-mom sevig em a nep)(checking each word by reverse)//
//output-palindrome//
//input-he is a boy//
//output-not a palindrome//
import java.util.*;
class main2
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string");
String str=sc.nextLine(); //he is a boy//
int ctr=0;
String temp="",temp1="",x="",y="";
int i,j;
String str1[]=str.split(" ");//[he,is,a,boy]//
for(i=0;i<str1.length;i++)//length=4//
{
temp=str1[i];//reverse each word//
for(j=temp.length()-1;j>=0;j--)
{
x=x+temp.charAt(j);
}
x=x+" ";
}
System.out.println(x);
for(int k=0;k<str1.length;k++)
{
temp1=str1[k]; //he//
for(int l=temp1.length()-1;l>=0;l--)
{
y=y+temp1.charAt(l);//eh//
}
if(y.equalsIgnoreCase(temp1))//he==eh?//
{
ctr++;
System.out.println(y);//for printing the word//
}
}
if(ctr==0)
System.out.println("Not a palindrome");
else
System.out.println("Palindrome");
}
}
import java.util.*;
class palindrome {
String reverse(String str)
{
String tmp="";
int l=str.length()-1;
for(int i=l,n=0;i>=n;i--)
{
tmp=tmp+str.charAt(i);
}
return tmp;
}
}
class palindrome_word{
public static void main(String[] args){
Scanner sc = new Scanner (System.in);
palindrome ob=new palindrome ();
System.out.println("enter a sentance");
String s=sc.nextLine();
char b;
int i,a;
String st="";//to extract a word
s=s+" ";
String t="";//to extract the reverse of the word
a=s.length();
System.out.println("palindrome words");
for(i=0;i<a;i++){
b=s.charAt(i);
if(b!=' '){
st=st+b;//word
// t=b+st;reversed word
} else {
t=ob.reverse(st);
if(st.equalsIgnoreCase(t)){
System.out.println(st);
}
st="";
t="";
}
}
sc.close();
}
}
Related
I was given the task of splitting my program which outputted the longest word in a sentence into a number of methods within the same class. I keep on trying out different ways but none seem to work. Could someone help me out?
This is the program:
import java.util.Scanner;
public class Test{
public static str getUserInput(Scanner sc) {
System.out.print("Enter a string or sentence: ");
// Return the string inputted by the user
return sc.nextLine();
return str;
}
public static void getlongestWord(str) {
Scanner str2 = new Scanner(str);
//Initialise longestWord with the first word in str
String longestWord = str2.next();
//Initiaise maxlen with length of first word in str
int maxlen = longestWord.length();
while(str2.hasNext()) //This loop will keep running till words are present
{
String word = str2.next(); //Storing next word in variable
int len = word.length(); //Storing word's length
if(len>maxlen) //If this length is more than maxlen, longestWord and maxlen are changed
{
longestWord = word;
maxlen = len;
}
}
return longestWord;
return maxlen;
}
int longestWord;
int maxlen;
public static void getOutput (int longestWord) {
System.out.println("The longest word is '" + longestWord );
}
public static void getOuput2 (int maxlen){
System.out.println ("of length "+maxlen+" characters.");
}
}
I left some comments in your code:
import java.util.Scanner;
public class Test {
public static str getUserInput(Scanner sc) { // The return type should be of type String and not str.
System.out.print("Enter a string or sentence: ");
return sc.nextLine();
return str; // you can't have a return statement immediately after another return statement :)
}
public static void getlongestWord(str) { // The method parameter is not of a valid type (it is not String)
Scanner str2 = new Scanner(str);
String longestWord = str2.next();
int maxlen = longestWord.length();
while(str2.hasNext())
{
String word = str2.next();
int len = word.length();
if(len>maxlen)
{
longestWord = word;
maxlen = len;
}
}
return longestWord;
return maxlen; // you can't have a return statement immediately after another return statement :)
}
int longestWord; // Instance variables should be declared at the top of the class
int maxlen;
public static void getOutput(int longestWord) { // Methods named {getSomething()} should return that something. This method returns void.
System.out.println("The longest word is '" + longestWord);
}
public static void getOuput2(int maxlen) { // Focus on proper naming.
System.out.println("of length " + maxlen + " characters.");
}
}
I also wrote my own version of what you are trying to do:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.print("Enter a string or sentence: ");
Scanner sc = new Scanner(System.in);
processInput(sc);
}
public static void processInput(Scanner sc) {
String sentence = sc.nextLine();
String longestWord = findLongestWord(sentence);
printInfo(longestWord);
}
public static String findLongestWord(String sentence) {
String longest = "";
for (String currentWord : sentence.split(" ")) {
if (longest.length() < currentWord.length())
longest = currentWord;
}
return longest;
}
public static void printInfo(String longestWord) {
System.out.println("The longest word is '" + longestWord);
System.out.println("of length " + longestWord.length() + " characters.");
}
}
My solution is in no way a perfect solution so you could go ahead and understand the changes I made, and then implement your own changes.
Remember: every class and method should be responsible for one thing only.
A simple way to do it is to split the string on whitespace and then iterate the resulting array to find the longest word. To find the longest word, you can start with the assumption that the first word is the longest and store it in a variable (e.g. String longestWord) and whenever a word longer than this is encountered, replace the stored word with that word.
public class Main {
public static void main(String[] args) {
// Test string
String str = "Stack Overflow is the largest, most trusted online community for developers to learn, share their programming knowledge, and build their careers.";
System.out.println("The longest word in the sentence: " + getLongestWord(str));
}
static String getLongestWord(String str) {
// Split the string on whitespace
String[] arr = str.split("\\s+");
// Start with the assumption that the first word is longest
String longestWord = arr[0];
int maxLen = longestWord.length();
for (String s : arr) {
if (s.length() > maxLen) {
maxLen = s.length();
longestWord = s;
}
}
return longestWord;
}
}
Output:
The longest word in the sentence: programming
I am beginner in Java & I am assigned with a lot of programs for my project this week. However, this one is confusing me for a long time now. I wrote a code for it but it is not displaying any result. There are no syntax errors btw! Have a look- Thank You!
import java.util.*;
import java.lang.*;
public class primeWord_reverser
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int i,p,flag=0;
System.out.println("Enter the sentence:");
String SEN=sc.next();
SEN=SEN.toUpperCase();
SEN=SEN+" ";
int L=SEN.length();
StringBuilder fnalS= new StringBuilder("");
StringBuilder finalS=new StringBuilder("");
for(i=0;i<L-1;i++)
{
char chr=SEN.charAt(i);
if (chr!=' ')
{
fnalS.insert(fnalS.length(),chr);
}
else if(chr==' ')
{
int LfnalS=fnalS.length();
int m=LfnalS/2;
for(p=2;p<=m;p++)
{
if(LfnalS%p==0)
{
flag++;
}
}
if(flag==0)
{
fnalS.reverse();
finalS.append(" "+fnalS);
}
else if(flag>0)
{
finalS.append(" "+fnalS);
}
fnalS=new StringBuilder("");
flag=0;
}
}
System.out.println("the sentence is: "+finalS);
}
}
Try to change your code of:
String SEN = sc.next();
to
String SEN = sc.nextLine();
and remove -1 on your for loop:
for(i=0;i<L-1;i++)
to
for(i=0;i<L;i++)
The basic function of this program is to take a word and search in an array of strings than search and print the string containing that word.
public static void main(String[] args) {
String[] str = {"I am Alive.", "Are you dead?", "Let's see if it works."};
String search;
int count=0;
Scanner s=new Scanner(System.in);
System.out.println("enter word");
search=s.nextLine();
for(int i=0;i<str.length;i++){
//check strings individually
if(str[i].charAt(i)=='.'||str[i].charAt(i)=='?'){ //search for dot or any sentence finisher
count++;
}
if(str[i].contains(search)){
System.out.println(str[count]);
} else {
System.out.println("Not found");
break;
}
}
}
You should not break the loop there since it is only considered not found once you went through all the sentences in the array. Something like this:
public static void main(String[] args) {
String[] str={"I am Alive.","Are you dead?","Let's see if it works."};
String search;
Scanner s=new Scanner(System.in);
System.out.println("Enter word");
search=s.nextLine();
boolean found = false;
for(int i=0;i<str.length;i++){
if(str[i].contains(search)){
System.out.println(str[i]);
found = true;
}
}
if (!found) {
System.out.println("Not found");
}
}
Watch out that break, it's executed always.
Check this:
public static void main(final String... args) {
final String[] strings = { "I am Alive.", "I am Alive...too.", "Are you dead?",
"Let's see if it works." };
int found = -1;
System.out.print("Enter search term > ");
try (final Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name())) {
final String input = scanner.nextLine();
for (int i = 0; (i < strings.length) && (found < 0); i++) {
if (strings[i].contains(input) && (strings[i].contains(".") ||
strings[i].contains("?"))) {
//System.out.println(strings[i]);
found = i;
}
}
}
System.out.printf("%s%n", (found >= 0) ? strings[found] : "Not found");
}
Here is my homework:
accept a sentence and print the words that have consecutive characters equal
INPUT: an apple a day keeps
OUTPUT: apple keeps
Here is what I am working on:
import java.util.*;
public class Program1
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=sc.nextLine();
String str=s.toLowerCase();
int l,i=0; char c,d;int a,b,m=0;int n=0; String r=""; String res="";
l=s.length();
str=" "+str+" ";
for(i=0;i<(l-1);i++)
{
c=str.charAt(i);
d=str.charAt(i+1);
a=c;
b=d;
m=str.indexOf(' ');
n=str.indexOf(' ',(i+1));
if(d==' ')
{
m=str.indexOf(' ',(i-1));
n=str.indexOf(' ',(i+1));
}
if(a==b)
{
r=str.substring(m,n);
res=res +" "+ r;
}
}
System.out.println(res);
}
}
It gets compiled, but it does not give correct output.
If I enter the above example, it returns:
an apple an apple a day keeps
What do I need to do?
You can do something like this to achieve the result,
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = sc.nextLine();
String str = s.toLowerCase();
String[] words = str.split(" "); // Split the sentence into an array of words.
for(String ss : words){
char previousChar = '\u0000';
for (char c : ss.toCharArray()) {
if (previousChar == c) { // Same character has occurred
System.out.println(ss);
break;
}
previousChar = c;
}
}
The problem is in the line:
m=str.indexOf(' ');
you start aat the beginning of the sentence every time, so you print the sentence from beginning to the word you want.
This is my proposal. :-D
Input: mi aasas es mass pp
Output: aasas mass pp
import java.util.*;
public class code10
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=sc.nextLine();
String str=s.toLowerCase();
String cadena = str;
String delimitadores= "[ .,;?!¡¿\'\"\\[\\]]+";
String[] palabrasSeparadas = cadena.split(delimitadores);
for(int x=0; x<palabrasSeparadas.length; x++)
{
char[] tmpstr = palabrasSeparadas[x].toCharArray();
for(int y=0; y<tmpstr.length; y++)
{
if((y+1) < tmpstr.length)
{
if(tmpstr[y] == tmpstr[y+1])
{
System.out.print(palabrasSeparadas[x] + " ");
}
}
}
}
System.out.println("");
}
}
hi am trying to write a palindrome checker code but if i enter "madam" it still tells me its not a palindrome please help. tell me whats causing it
import java.util.Scanner;
public class parlindrome
{
String original, reverse = "";
public void checkpalindrome(){
Scanner h = new Scanner(System.in);
System.out.println("enter a word : ");
original = h.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 word is a palindrom ");
}
else
{
System.out.println("entered word is not a palindrome ");
break;
}
}
}
}
public static void main(String[]args)
{
parlindrome k=new parlindrome();
k.checkpalindrome();
}
}
You should finish the loop that reverses the String before checking if it's a palindrome :
for(int i=length-1;i>=0;i--) {
reverse=reverse+original.charAt(i);
}
if(original.equals(reverse)) {
System.out.println("entered word is a palindrom ");
}
Also, if you want this method to work more than once, you should make reverse a local variable and initialize it to an empty String inside the method.
You could do it in a more effective way, using Java´s reverse.
public void checkpalindrome(){
Scanner h = new Scanner(System.in);
System.out.println("Enter a word: ");
String original = h.nextLine();
if(original.equals(new StringBuilder(original).reverse().toString()))
System.out.println("Entered word is a palindrom");
else
System.out.println("Entered word is not a palindrom");
}
try this:
import java.util.Scanner;
public class parlindrome {
public boolean checkpalindrome(String original) {
String reverse = "";
int length = original.length();
for (int i = length - 1; i >= 0; i--) {
reverse += original.charAt(i);
}
if (reverse.equals(original)) {
System.out.println("entered word is a palindrom ");
return true;
}
System.out.println("entered word is not a palindrom ");
return false;
}
public static void main(String[] args) {
Scanner h = new Scanner(System.in);
System.out.println("enter a word : ");
String original = h.nextLine();
parlindrome k = new parlindrome();
k.checkpalindrome(original);
}
}
Just remove validation part from for loop. Your code should be as below:
for (int i = length - 1; i >= 0; i--)
reverse += original.charAt(i);
if (original.equals(reverse))
System.out.println("entered word is a palindrom ");
else
System.out.println("entered word is not a palindrome ");
h.close();