I am new in Java Programming! So tried to solve a problem to find the shortest and longest word in a sentence. My program is shown below . I hope you people can show me the right direction about my program -
public class StringProblems {
void shortAndLongWord(String str) {
String sw = "", lw = "";
int s = str.length(), l = 0;
String words[] = str.split(" ");
for(String word:words) {
if(word.length()<s)
sw = word;
else if(word.length()>l)
lw = word;
}
System.out.println("LONGEST WORD : "+lw);
System.out.println("SHORTEST WORD : "+sw);
}
public static void main(String[] args) {
Scanner scr = new Scanner(System.in);
StringProblems obj = new StringProblems();
System.out.printf("Enter a line to get shortest and longest word:");
String str = scr.nextLine();
str += " ";
obj.shortAndLongWord(str);
}
}
Output of this program is :
*Enter a line to get shortest and logest word:This is Sentence
LONGEST WORD :
SHORTEST WORD : Sentence**
I dont know where my logic went wrong! Please help me to solve!
You have to keep updating the length of the current shortest and longest word:
public class StringProblems {
void shortAndLongWord(String str)
{
if (str == null)
return;
String sw="",lw="";
int s=str.length(),l=0;
String words[]=str.split(" ");
for(String word:words)
{
if(word.length()<s)
{
sw=word;
s = word.length();
}
if(word.length()>l)
{
lw=word;
l = word.length();
}
}
System.out.println("LONGEST WORD : "+lw);
System.out.println("SHORTEST WORD : "+sw);
}
public static void main(String[] args) {
Scanner scr=new Scanner(System.in);
StringProblems obj=new StringProblems();
System.out.printf("Enter a line to get shortest and longest word:");
String str=scr.nextLine();
str+=" ";
obj.shortAndLongWord(str);
}
}
You need to keep updating l (length of the longest word) and s (length of the smallest word)
if(word.length()<s)
{
sw=word;
s = word.length();
}
if(word.length()>l)
{
lw=word;
l = word.length();
}
Also, there are boundary conditions that you need to take care of.
For example, what happens if the string is a single word. What happens when the input string is null etc.
import java.util.Scanner;
public class ShortestAndLongestWordInALine {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter any sentence : ");
String line = sc.nextLine();
sc.close();
int shortestWordLength = 0;
int longestWordLength = 0;
String shortestWord = "";
String longestWord = "";
int tempLength = 0;
String[] eachWordArray = line.split(" ");
boolean firstTime = false;
for (String eachWord : eachWordArray) {
tempLength = eachWord.length();
if (firstTime == false) {
firstTime = true;
shortestWordLength = tempLength;
shortestWord = eachWord;
longestWordLength = tempLength;
longestWord = eachWord;
}
if (tempLength > 0) {
if (tempLength < shortestWordLength) {
shortestWordLength = tempLength;
shortestWord = eachWord;
} else if (tempLength > longestWordLength) {
longestWordLength = tempLength;
longestWord = eachWord;
}
}
}
System.out.println("shortestWordLength = " + shortestWordLength + " shortestWord = " + shortestWord);
System.out.println("longestWordLength = " + longestWordLength + " longestWord = " + longestWord);
}
}
You are not updating values of l and s during iteration. You should try something like this:
if (word.length() < s) {
sw = word;
s = word.length();
} else if (word.length() > l) {
lw = word;
l = word.length();
}
import java.util.*;
class lw
{
public static void main()
{
Scanner in=new Scanner(System.in);
String z=" ",lw="";
int q=0,o=0;
System.out.println("Enter string");
String str=in.nextLine()+" ";
int l=str.length();
for(int i=1;i<l;i++)
{
char ch=str.charAt(i);
if(ch!=' ')
z=z+ch;
else
{
q=z.length();
if(q>o)
lw=z;
o=q;
z="";
}
}
System.out.println("lw= "+lw);
System.out.println("length="+q);
}
}
Related
I am trying to get my program to print out "(ABC,1) (BCD,1) (CDB,1) (DBC,1)" if I have a .txt file that shows ABCDBCD but the error code states The local variable hentSub may not have been initialized Java(536870963) on my subsequence getSub. Any tips? The reason it states (ABC,1) is because the 1 is a person, and a subseq of their DNA
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("C:\\Users\\Public\\File1.txt"));
String currentLine, subString;
int subSize = 3;
HashMap<String, subsequence> subSeqHashNy = new HashMap<String, subsequence> ();
subsequence getSub;
int count = 0;
while (scanner.hasNextLine()) {
currentLine = scanner.nextLine();
currentLine = currentLine.trim();
if (currentLine.length() < subSize) {
break;
}
for (int i = 0; i + subSize <= currentLine.length(); i++) {
subString = currentLinje.substring(i, i + subSize);
System.out.print(subString + " ");
for(subsequence sub1: subSeqHashNy.values()) {
if (hetSub == null) {
subSeqHashNy.put(sub1.key(), sub1);
}
else {
int num = getSub.getNum();
sub1.leggTil(num);
subSeqHashNy.put(sub1.key(), sub1);
}
}
}
System.out.print("\n");
}
scanner.close();
}
This question already has answers here:
How do I remove repeated elements from ArrayList?
(40 answers)
Closed last year.
I want to remove/ delete duplicate words. I tried this but it wont work.
Does someone have a solution for this?
public static void main(String[] args) {
List<String> words = sw("This is is an example");
System.out.println(words); // => [an, example, is, This]
}
public static List<String> sw(String s) {
List<String> words = new ArrayList<String>(Arrays.asList(s.trim().split(" +")));
int size = words.size();
for(int i = 0;i < size;i++) {
for(int k = i+1;k < size;k++) {
if(size == 1) {
break;
}
if(k < size -1 && words.get(i).equals(words.get(k))) {
words.remove(k);
k = k -1;
} if(size == 1) {
break;
}
}
}
Collections.sort(words);
return words;
}
}
you can solve this problem using LinkedHashSet or Regex.
1. LinkedHashSet
public static void main(String[] args) {
String sentence, result = "";
String allWords[];
Scanner sc = new Scanner(System.in);
System.out.print("Enter your sentence: ");
sentence = sc.nextLine().toLowerCase(); //convert to lower case
allWords = sentence.split(" ");
LinkedHashSet<String> set = new LinkedHashSet<String>( Arrays.asList(allWords) );
for(String word: set) {
result = result + word + " ";
}
System.out.println("Sentence after removing duplicate words: " + result);
}
2.Regex
Required regex = "\\b(\\w+)(?:\\W+\\1\\b)+";
public static void main(String[] args) {
String sentence, regex;
Scanner sc = new Scanner(System.in);
System.out.print("Enter your sentence: ");
sentence = sc.nextLine();
// Define regex
regex = "\\b(\\w+)(?:\\W+\\1\\b)+";
// Define pattern to compile regex
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
// Match whether regex matching with sentence or not
Matcher match = pattern.matcher(sentence);
// Use while loop to find and replace duplicate words
while(match.find()) {
sentence = sentence.replace(match.group(), match.group(1));
}
System.out.println("Sentence after removing duplicate words: " + sentence);
}
this should be the solution :)
public static List<String> sw(String s) {
List<String> words = new ArrayList<String>(Arrays.asList(s.trim().split(" +")));
int size = words.size();
for(int i = 0;i < size;i++) {
for(int k = i+1;k < size;k++) {
if(k <= size -1 && words.get(i).equals(words.get(k))) {
words.remove(k);
k--;
size--;
}
}
}
Collections.sort(words);
return words;
}
}
input is :levelmm
output is: the given string is palindrome because the given string contains level is a palindrome remain character like mm is neglected.
package example;
import java.util.Scanner;
public class exp2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("enter the string");
Scanner scan=new Scanner(System.in);
String s=scan.nextLine();
String t="";
String s1=s.substring(0, s.length()-1);
for(int i=s1.length()-1;i>=0;i--)
{
t=t+s.charAt(i);
}
if(t.equalsIgnoreCase(s1))
{
int count=t.length();
System.out.println("is palindrome"+(count-1));
}else
{
System.out.println("not a palindrome");
}
}
}
but its not working completely..
First of all, the line String s1 = s.substring(0, s.length() - 1); removes one character from your word, which is not something that looks like it's supposed to happen.
What it looks like is that you want to create every possible substring of an input and see if that is a palindrome. To see whether something is a palindrome I propose this:
private static boolean isPalindrome(String word) {
String reverseWord = "";
for (int i = word.length() - 1; i > -1; i--) {
reverseWord += word.toCharArray()[i];
}
return reverseWord.equalsIgnoreCase(word);
}
Getting every single substring is more difficult, but can be done like this:
private static String[] allSubstrings(String word) {
int amount = 0;
for (int i = 0; i < word.length() + 1; i++) {
amount += i;
}
String[] res = new String[amount];
int index = 0;
for (int i = 0; i < word.length(); i++) {
for (int j = i + 1; j < word.length() + 1; j++) {
res[index] = word.substring(i, j);
index++;
}
}
return res;
}
Now, since every word that is 1 long is a palindrome, we don't want that, so in the main method we can say a word has to be more than 1 long. This results in a main method like this:
public static void main(String[] args) {
System.out.println("enter the string");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
boolean isPal = false;
for (String word : allSubstrings(s)) {
if (word.length() > 1 && isPalindrome(word)) {
isPal = true;
}
}
if (isPal) {
System.out.println("Is palindrome");
} else {
System.out.println("Is not palindrome");
}
}
I hope this answers your question and I wish you happy coding.
For my program I want to reverse letters in a line of text. However I don't want to reverse the order of the words in the sentence.
For example when I input: "This is a string"
I get: gnirts a si siht
But I want: siht si a gnirts
public static String reverseWordCharacters(String text1) {
String reverse = "";
int length = text1.length();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + text1.charAt(i);
System.out.println();
}
return reverse;
}
}
String sentence = "This is a string";
String[] words = sentence.split(" ");
String invertedSentece = "";
for (String word : words){
String invertedWord = "";
for (int i = word.length() - 1; i >= 0; i--)
invertedWord += word.charAt(i);
invertedSentece += invertedWord;
invertedSentece += " ";
}
invertedSentece.trim();
Commons Lang's StringUtils class has method to do this:
http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#reverse(java.lang.String)
This may be the easiest way
import java.util.*;
public class ReverseString{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter any Sentence: ");
String sentence = sc.nextLine();
String[] stringArray = sentence.split(" ");
for(int i = 0; i<stringArray.length; i++){
String temp = new StringBuilder(stringArray[i]).reverse().toString();
System.out.print(temp+" ");
}
}
}
private static String revWrord(String s) {
LinkedList word = new LinkedList();
Scanner scanfs = new Scanner(s);
while(scanfs.hasNext()) {
word.add(scanfs.next());
}
StringBuilder output = new StringBuilder();
StringBuilder temp = new StringBuilder();
while(true) {
temp.append(word.poll()).reverse();
output.append(temp);
temp.delete(0,temp.length() );
if(word.isEmpty()) {
break;
} else {
output.append(" ");
}
}
return output.toString();
}
public static void main(String[] args) {
String s= "This is a string";
System.out.println(s);
String finalrevresestring = "";
String wordreverse = "";
String[] a = s.split(" ");
for (int i = 0; i<=a.length-1; i++) {
for (int x=a[i].length()-1; x>=0; x--) {
wordreverse += a[i].charAt(x);
}
finalrevresestring += wordreverse;
finalrevresestring += " ";
wordreverse = "";
}
System.out.println("This is reverse: "+finalrevresestring);
}
{
String sentence="This is String";
String[] words=sentence.split(" ");
String inverted=" ";
for(String eachWord : words){
for(int i=0;i<eachWord.length();i++){
inverted+=eachWord.charAt(eachWord.length()-1-i);
}
inverted+=" ";
}
System.out.println("Inverted words in the given sentence is :"+inverted);
}
StringBuffer s=new StringBuffer("I live in India");
int i=0,j=0,w=0;
//w is first position of word
//j is last position of word
while(i<s.lenght){
if(s.charAt[i]==" "||i==s.lenght()-1)
{
j=i;
if(i==s.length-1)
j=i;
else
j--;
swapMethod(w,j);
w=i+1;
}
i++;
}
Hi I've been doing this java program, i should input a string and output the longest palindrome that can be found ..
but my program only output the first letter of the longest palindrome .. i badly need your help .. thanks!
SHOULD BE:
INPUT : abcdcbbcdeedcba
OUTPUT : bcdeedcb
There are two palindrome strings : bcdcb and bcdeedcb
BUT WHEN I INPUT : abcdcbbcdeedcba
output : b
import javax.swing.JOptionPane;
public class Palindrome5
{ public static void main(String args[])
{ String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
String subword = "";
String revword = "";
String Out = "";
int size = word.length();
boolean c;
for(int x=0; x<size; x++)
{ for(int y=x+1; y<size-x; y++)
{ subword = word.substring(x,y);
c = comparisonOfreverseword(subword);
if(c==true)
{
Out = GetLongest(subword);
}
}
}
JOptionPane.showMessageDialog(null, "Longest Palindrome : " + Out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}
public static boolean comparisonOfreverseword(String a)
{ String rev = "";
int tempo = a.length();
boolean z=false;
for(int i = tempo-1; i>=0; i--)
{
char let = a.charAt(i);
rev = rev + let;
}
if(a.equalsIgnoreCase(rev))
{
z=true;
}
return(z);
}
public static String GetLongest(String sWord)
{
int sLength = sWord.length();
String Lpalindrome = "";
int storage = 0;
if(storage<sLength)
{
storage = sLength;
Lpalindrome = sWord;
}
return(Lpalindrome);
}
}
modified program..this program will give the correct output
package pract1;
import javax.swing.JOptionPane;
public class Palindrome5
{
public static void main(String args[])
{
String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
String subword = "";
String revword = "";
String Out = "";
int size = word.length();
boolean c;
String Lpalindrome = "";
int storage=0;
String out="";
for(int x=0; x<size; x++)
{ for(int y=x+1; y<=size; y++)
{ subword = word.substring(x,y);
c = comparisonOfreverseword(subword);
if(c==true)
{
int sLength = subword.length();
if(storage<sLength)
{
storage = sLength;
Lpalindrome = subword;
out=Lpalindrome;
}
}
}
}
JOptionPane.showMessageDialog(null, "Longest Palindrome : " + out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}
public static boolean comparisonOfreverseword(String a)
{ String rev = "";
int tempo = a.length();
boolean z=false;
for(int i = tempo-1; i>=0; i--)
{
char let = a.charAt(i);
rev = rev + let;
}
if(a.equalsIgnoreCase(rev))
{
z=true;
}
return(z);
}
}
You have two bugs:
1.
for(int y=x+1; y<size-x; y++)
should be
for(int y=x+1; y<size; y++)
since you still want to go all the way to the end of the string. With the previous loop, since x increases throughout the loop, your substring sizes decrease throughout the loop (by removing x characters from their end).
2.
You aren't storing the longest string you've found so far or its length. The code
int storage = 0;
if(storage<sLength) {
storage = sLength;
...
is saying 'if the new string is longer than zero characters, then I will assume it is the longest string found so far and return it as LPalindrome'. That's no help, since we may have previously found a longer palindrome.
If it were me, I would make a static variable (e.g. longestSoFar) to hold the longest palindrome found so far (initially empty). With each new palindrome, check if the new one is longer than longestSoFar. If it is longer, assign it to longestSoFar. Then at the end, display longestSoFar.
In general, if you're having trouble 'remembering' something in the program (e.g. previously seen values) you have to consider storing something statically, since local variables are forgotten once their methods finish.
public class LongestPalindrome {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String S= "abcdcba";
printLongestPalindrome(S);
}
public static void printLongestPalindrome(String S)
{
int maxBack=-1;
int maxFront = -1;
int maxLength=0;
for (int potentialCenter = 0 ; potentialCenter < S.length();potentialCenter ++ )
{
int back = potentialCenter-1;
int front = potentialCenter + 1;
int longestPalindrome = 0;
while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
{
back--;
front++;
longestPalindrome++;
}
if (longestPalindrome > maxLength)
{
maxLength = longestPalindrome+1;
maxBack = back + 1;
maxFront = front;
}
back = potentialCenter;
front = potentialCenter + 1;
longestPalindrome=0;
while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
{
back--;
front++;
longestPalindrome++;
}
if (longestPalindrome > maxLength)
{
maxLength = longestPalindrome;
maxBack = back + 1;
maxFront = front;
}
}
if (maxLength == 0) System.out.println("There is no Palindrome in the given String");
else{
System.out.println("The Longest Palindrome is " + S.substring(maxBack,maxFront) + "of " + maxLength);
}
}
}
I have my own way to get longest palindrome in a random word. check this out
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));
}
static String longestPalSubstr(String str) {
char [] input = str.toCharArray();
Set<CharSequence> out = new HashSet<CharSequence>();
int n1 = str.length()-1;
for(int a=0;a<=n1;a++)
{
for(int m=n1;m>a;m--)
{
if(input[a]==input[m])
{
String nw = "",nw2="";
for (int y=a;y<=m;y++)
{
nw=nw+input[y];
}
for (int t=m;t>=a;t--)
{
nw2=nw2+input[t];
}
if(nw2.equals(nw))
{
out.add(nw);
break;
}
}
}
}
int a = out.size();
int maxpos=0;
int max=0;
Object [] s = out.toArray();
for(int q=0;q<a;q++)
{
if(max<s[q].toString().length())
{
max=s[q].toString().length();
maxpos=q;
}
}
String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max;
return output;
}
this method will return the max length palindrome and the length of it. its a way that i tried and got the answer. and this method will run whether its a odd length or even length.
public class LongestPalindrome {
public static void main(String[] args) {
HashMap<String, Integer> result = findLongestPalindrome("ayrgabcdeedcbaghihg123444456776");
result.forEach((k, v) -> System.out.println("String:" + k + " Value:" + v));
}
private static HashMap<String, Integer> findLongestPalindrome(String str) {
int i = 0;
HashMap<String, Integer> map = new HashMap<String, Integer>();
while (i < str.length()) {
String alpha = String.valueOf(str.charAt(i));
if (str.indexOf(str.charAt(i)) != str.lastIndexOf(str.charAt(i))) {
String pali = str.substring(i, str.lastIndexOf(str.charAt(i)) + 1);
if (isPalindrome(pali)) {
map.put(pali, pali.length());
i = str.lastIndexOf(str.charAt(i));
}
}
i++;
}
return map;
}
public static boolean isPalindrome(String input) {
for (int i = 0; i <= input.length() / 2; i++) {
if (input.charAt(i) != input.charAt(input.length() - 1 - i)) {
return false;
}
}
return true;
}
}
This approach is simple.
Output:
String:abcdeedcba Value:10
String:4444 Value:4
String:6776 Value:4
String:ghihg Value:5
This is my own way to get longest palindrome. this will return the length and the palindrome word
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));
}
static String longestPalSubstr(String str) {
char [] input = str.toCharArray();
Set<CharSequence> out = new HashSet<CharSequence>();
int n1 = str.length()-1;
for(int a=0;a<=n1;a++)
{
for(int m=n1;m>a;m--)
{
if(input[a]==input[m])
{
String nw = "",nw2="";
for (int y=a;y<=m;y++)
{
nw=nw+input[y];
}
for (int t=m;t>=a;t--)
{
nw2=nw2+input[t];
}
if(nw2.equals(nw))
{
out.add(nw);
break;
}
}
}
}
int a = out.size();
int maxpos=0;
int max=0;
Object [] s = out.toArray();
for(int q=0;q<a;q++)
{
if(max<s[q].toString().length())
{
max=s[q].toString().length();
maxpos=q;
}
}
String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max;
return output;
}
this method will return the max length palindrome and the length of it. its a way that i tried and got the answer. and this method will run whether its a odd length or even length.