Java Poem Palindrome Checker: Iterate through array matching elements in order - java

Currently trying to program a poem Palindrome checker. This is not for palindromes specifically, but that the array has words in the same order both ways. For example the following is a poem palindrome
Life-
imitates nature,
always moving, traveling continuously.
Continuously traveling, moving always,
nature imitates
life
My issue is iterating through the array to match the first and last elements, as currently it compares things in the wrong order.
My code is as follows:
import java.util.Scanner;
import java.io.*;
public class WordPalindromeTest {
public static void main(String[] args) {
System.out.println("This program determines if an entered sentence/word poem is a palindrome.");
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string to determine if it is a palindrome: ");
while(input.hasNextLine()) {
String palin = input.nextLine();
if(palin.equals("quit")) {
break;
}
else {
boolean isPalin = isWordPalindrome(palin);
if(isPalin == true) {
System.out.println(palin + " is a palindrome!");
}
else
System.out.println(palin + " is NOT a palindrome!");
}
}
System.out.println("Goodbye!");
input.close();
}
public static boolean isWordPalindrome(String s) {
boolean isWordPal = false;
String lowerCase = s.toLowerCase();
String replaced = lowerCase.replaceAll("[^a-zA-Z0-9\\s]", "");
String words[] = replaced.split(" ");
for(int i = 0; i < words.length; i++) {
for(int j = 0; j < words.length; j++) {
if (words[i].equals(words[j]) && i != j) {
isWordPal = true;
}
else
isWordPal = false;
}
}
return isWordPal;
}
}
With the specific point in question being
public static boolean isWordPalindrome(String s) {
boolean isWordPal = false;
String lowerCase = s.toLowerCase();
String replaced = lowerCase.replaceAll("[^a-zA-Z0-9\\s]", "");
String words[] = replaced.split(" ");
for(int i = 0; i < words.length; i++) {
for(int j = 0; j < words.length; j++) {
if (words[i].equals(words[j]) && i != j) {
isWordPal = true;
}
else
isWordPal = false;
}
}
return isWordPal;
}
I am confused on how to properly set up the loop to compare the right elements. It should compare the first element to the last, the second to the second to last, etc. until the loop is finished. I realize I have it compare the first to the entire array before moving on.

This seems like a homework assignment so I won't give you a working solution. But this of it like this:
-You don't need two loops. You only need to compare the first to the last, the second to the second to last, etc. (Hint: if you subtract i-1 from the length of the Array you'll get the corresponding element to i that you need to compare to). Also you only need to iterate over half of the length of the Array
-If ever isWordPal becomes false, you need to return false. Otherwise it might get overwritten and at the end it will return true.

Related

a program which identifies the differences between pairs of strings

My problem is that I need to identify characters which differ between the two given strings in a visually striking way. Output the two input strings on two lines, and then identify the differences on the line below using periods (for identical characters) and asterisks (for differing characters). For example:
ATCCGCTTAGAGGGATT
GTCCGTTTAGAAGGTTT
*....*.....*..*..
I have tried to write two string with each other but I dont know how to make the program check for every character in the string and see if those match
This is what I have done so far :/
System.out.println("String 1: ");
String var1 = Scanner.nextLine();
System.out.println("String 2: ");
String var2 = Scanner.nextLine();
if (same (var1, var2))
System.out.println(".........");
else
System.out.println("********");
public static boolean same (String var1, String var2){
if (var1.equals(var2))
{
return true;
}
else
{
return false;
}
Can anyone help me with this?
You need to loop through your Strings and compare characters one by one. To run through your list you can make a for-loop. Use an int as counter and use the method length() to obtain your string size.
for(int i=0; i<string1.length(); i++ {
// do stuff
}
Then since you have a counter going through all position of your string, you can obtain the character at a specific position in this string using the method charAt()
char char1 = string1.charAt(i);
Then compare the character to check if they are the same. If they are print a dot . if they're not print an asterisk *
if(char1 == char2) {
System.out.print(".");
} else {
System.out.print("*");
}
In the above part I supposed your two string have the same size. If it's not the case, you can first determine which one is the smallest (and so which is the biggest) :
String smallestString;
String biggestString;
if(string1.size() > string2.sise()) {
smallestString = string2;
biggestString = string1;
else {
smallestString = string1;
biggestString = string2;
}
Then make your for loop go through the smallest String, otherwise you will face IndexOutOfBoundsException.
for(int i=0; i<smallestString.length(); i++ {
// do stuff
}
And the end of this for loop print asterisks for the characters that left in the biggest String
for(int j=smallestString.length(); j<biggestString.length(); j++) {
System.out.print("*");
}
This is what I've come up with.Mind you there are better ways to do this and I've just written it with as much effort as you put in your question.
public class AskBetterQuestion{
public static void main(String[] args) {
// TODO Auto-generated method stub
String w1="ATCCGCTTAGAGGGATT";
String w2="GTCCGTTTAGAAGGTTT";
char[] first = w1.toCharArray();
char[] second = w2.toCharArray();
int minLength = Math.min(first.length, second.length);
char[] out=new char[minLength];
for(int i = 0; i < minLength; i++)
{
if (first[i] != second[i])
{
out[i]='.';
}
else out[i]='*';
}
System.out.println(w1);
System.out.println(w2);
System.out.print(out);
}
}

Increasing number sequence in a string java

Problem: Check if the numbers in the string are in increasing order.
Return:
True -> If numbers are in increasing order.
False -> If numbers are not in increasing order.
The String sequence are :
CASE 1 :1234 (Easy) 1 <2<3<4 TRUE
CASE 2 :9101112 (Medium) 9<10<11<12 TRUE
CASE 3 :9991000 (Hard) 999<1000 TRUE
CASE 4 :10203 (Easy) 1<02<03 FALSE
(numbers cannot have 0 separated).
*IMPORTANT : THERE IS NO SPACES IN STRING THAT HAVE NUMBERS"
My Sample Code:
// converting string into array of numbers
String[] str = s.split("");
int[] numbers = new int[str.length];
int i = 0;
for (String a : str) {
numbers[i] = Integer.parseInt(a.trim());
i++;
}
for(int j=0;j<str.length;j++)
System.out.print(numbers[j]+" ");
//to verify whether they differ by 1 or not
int flag=0;
for(int j=0;j<numbers.length-1;j++){
int result=Integer.parseInt(numbers[j]+""+numbers[j+1]) ;
if(numbers[j]>=0 && numbers[j]<=8 && numbers[j+1]==numbers[j]+1){
flag=1;
}
else if(numbers[j]==9){
int res=Integer.parseInt(numbers[j+1]+""+numbers[j+2]) ;
if(res==numbers[j]+1)
flag=1;
}
else if(result>9){
//do something
}
}
This is the code I wrote ,but I cant understand how to perform for anything except one-digit-numbers ( Example one-digit number is 1234 but two-digit numbers are 121314). Can anyone have a solution to this problem?. Please share with me in comments with a sample code.
I'm gonna describe the solution for you, but you have to write the code.
You know that the input string is a sequence of increasing numbers, but you don't know how many digits is in the first number.
This means that you start by assuming it's 1 digit. If that fails, you try 2 digits, then 3, and so forth, until you've tried half the entire input length. You stop at half, because anything longer than half cannot have next number following it.
That if your outer loop, trying with length of first number from 1 and up.
In the loop, you extract the first number using substring(begin, end), and parse that into a number using Integer.parseInt(s). That is the first number of the sequence.
You then start another (inner) loop, incrementing that number by one at a time, formatting the number to text using Integer.toString(i), and check if the next N characters of the input (extracted using substring(begin, end)) matches. If it doesn't match, you exit inner loop, to make outer loop try with next larger initial number.
If all increasing numbers match exactly to the length of the input string, you found a good sequence.
This is code for the pseudo-code suggested by Andreas .Thanks for the help.
for (int a0 = 0; a0 < q; a0++) {
String s = in.next();
boolean flag = true;
for (int i = 1; i < s.length() / 2; i++) {
int first = Integer.parseInt(s.substring(0, i));
int k=1;
for (int j = i; j < s.length(); j++) {
if (Integer.toString(first + (k++)).equals(s.substring(j, j + i)))
flag = true;
else{
flag=false;
break;
}
}
if (flag)
System.out.println("YES");
else
System.out.println("NO");
}
I would suggest the following solution. This code generates all substrings of the input sequence, orders them based on their start index, and then checks whether there exists a path that leads from the start index to the end index on which all numbers that appear are ordered. However, I've noticed a mistake (I guess ?) in your example: 10203 should also evaluate to true because 10<203.
import java.util.*;
import java.util.stream.Collectors;
public class PlayGround {
private static class Entry {
public Entry(int sidx, int eidx, int val) {
this.sidx = sidx;
this.eidx = eidx;
this.val = val;
}
public int sidx = 0;
public int eidx = 0;
public int val = 0;
#Override
public String toString(){
return String.valueOf(this.val);
}
}
public static void main(String[] args) {
assert(check("1234"));
assert(check("9101112"));
assert(check("9991000"));
assert(check("10203"));
}
private static boolean check(String seq) {
TreeMap<Integer,Set<Entry>> em = new TreeMap();
// compute all substrings of seq and put them into tree map
for(int i = 0; i < seq.length(); i++) {
for(int k = 1 ; k <= seq.length()-i; k++) {
String s = seq.substring(i,i+k);
if(s.startsWith("0")){
continue;
}
if(!em.containsKey(i))
em.put(i, new HashSet<>());
Entry e = new Entry(i, i+k, Integer.parseInt(s));
em.get(i).add(e);
}
}
if(em.size() <= 1)
return false;
Map.Entry<Integer,Set<Entry>> first = em.entrySet().iterator().next();
LinkedList<Entry> wlist = new LinkedList<>();
wlist.addAll(first.getValue().stream().filter(e -> e.eidx < seq
.length()).collect(Collectors.toSet()));
while(!wlist.isEmpty()) {
Entry e = wlist.pop();
if(e.eidx == seq.length()) {
return true;
}
int nidx = e.eidx + 1;
if(!em.containsKey(nidx))
continue;
wlist.addAll(em.get(nidx).stream().filter(n -> n.val > e.val).collect
(Collectors.toSet()));
}
return false;
}
}
Supposed the entered string is separated by spaces, then the code below as follows, because there is no way we can tell the difference if the number is entered as a whole number.
boolean increasing = true;
String string = "1 7 3 4"; // CHANGE NUMBERS
String strNumbers[] = string.split(" "); // separate by spaces.
for(int i = 0; i < strNumbers.length - 1; i++) {
// if current number is greater than the next number.
if(Integer.parseInt(strNumbers[i]) > Integer.parseInt(strNumbers[i + 1])) {
increasing = false;
break; // exit loop
}
}
if(increasing) System.out.println("TRUE");
else System.out.println("FALSE");

Java Beginner, comparing strings in nested for loop

Here is the problem statement: Write a function that compares 2 strings to return true or false depending on if both strings contain the same letters. Order doesn't matter.
I do not know how to properly compare the character arrays in my nested for loop. I wish I could be more specific with what my issue is, but I'm a really new learner and can't see why this isn't working. I do believe it's not doing what I would like in the nested for loops. Thanks in advance!
import java.util.Scanner;
public class PracticeProblems {
public static boolean stringCompare(String word1, String word2) {
char[] word1b = new char[word1.length()];
char[] word2b = new char[word2.length()];
boolean compareBool = false;
for(int i = 0; i < word1.length(); i++) {
word1b[i] = word1.charAt(i);
word2b[i] = word2.charAt(i);
}
for(int i = 0; i < word1.length(); i++) {
for(int j = 0; j < word2.length(); j++) {
if(word1b[i] == word2b[j]) {
compareBool = true;
break;
} else {
compareBool = false;
break;
}
}
}
return compareBool;
}
public static void main(String []args) {
Scanner scan = new Scanner(System.in);
System.out.println("Word 1?");
String word1 = scan.nextLine();
System.out.println("Word 2?");
String word2 = scan.nextLine();
if(PracticeProblems.stringCompare(word1, word2) == true) {
System.out.println("Same Letters!");
} else {
System.out.println("Different Letters...");
}
}
The code below will do the job. This is essentially an expansion of Frank's comment above. We convert the two strings to two sets and then compare.
import java.util.*;
public class SameChars {
// Logic to convert the string to a set
public static Set<Character> stringToCharSet(String str) {
Set<Character> charSet = new HashSet<Character>();
char arrayChar[] = str.toCharArray();
for (char aChar : arrayChar) {
charSet.add(aChar);
}
return charSet;
}
// Compares the two sets
public static boolean hasSameChars(String str1, String str2) {
return stringToCharSet(str1).equals(stringToCharSet(str2));
}
public static void main(String args[]){
// Should return true
System.out.println(hasSameChars("hello", "olleh"));
// Should returns false
System.out.println(hasSameChars("hellox", "olleh"));
}
}
I sorted arrays before comparing.
//import statement for Arrays class
import java.util.Arrays;
import java.util.Scanner;
public class PracticeProblems {
public static boolean stringCompare(String word1, String word2) {
char[] word1b = new char[word1.length()];
char[] word2b = new char[word2.length()];
boolean compareBool = true;
for(int i = 0; i < word1.length(); i++) {
word1b[i] = word1.charAt(i);
}
//sort the new char array
Arrays.sort(word1b);
// added a second loop to for the second world
for(int i = 0; i < word2.length(); i++) {
word2b[i] = word2.charAt(i);
}
Arrays.sort(word2b);
for(int i = 0; i < word1.length(); i++) {
//removed second for loop.
// for(int j = 0; j < word2.length(); j++) {
// if the two strings have different length, then they are different
if((word1.length()!=word2.length())){
compareBool = false;
break;
}
//changed to not equal
if( (word1b[i] != word2b[i]) ) {
compareBool = false;
break;
}
//removed else statment
// else {
// compareBool = false;
// break;
//
// }
}
return compareBool;
}
public static void main(String []args) {
Scanner scan = new Scanner(System.in);
System.out.println("Word 1?");
String word1 = scan.nextLine();
System.out.println("Word 2?");
String word2 = scan.nextLine();
if(PracticeProblems.stringCompare(word1, word2) == true) {
System.out.println("Same Letters!");
} else {
System.out.println("Different Letters...");
}
//resource leak. use close() method.
scan.close();
}
}
Allow me to rename your boolean variable to letterFound (or maybe even letterFoundInWord2) because this is what you are checking in your double loop. Explanatory naming makes it easier to keep the thoughts clear.
Since you are checking one letter from word1 at a time, you can move the declaration of letterFound inside the outer for loop and initialize it to false here since each time you take a new letter from word1 you haven’t found it in word2 yet. In your if statement inside the for loops, it is correct to break in the case the letters are the same and you set letterFound to true. In the opposite case, don’t break, just go on to check the next letter. In fact you can delete the else part completely.
After the inner for loop, if letterFound is still not true, we know that the letter from word1 is not in word2. So stringCompare() should return false:
if (! letterFound) {
return false;
}
With this change, after the outer for loop we know that all letters from word1 were found in word2, so you can type return true; here.
Except:
You seem to be assuming the strings have the same length. If they have not, you program will not work correctly.
As Andy Turner said, you should also check that all the letters in word2 are in word1; it doesn’t follow from the letters from word1 being in word2.
Should only letters be considered? Should you ignore spaces, digits, punctuation, …?
Hope you will be able to figure it out. Feel free to follow up in comments or ask a new question.

String Output Alignment in Java

practice question part 1
practice question part 2
This is a practice question which is rather hard for me. Below is my code for the static method(the main method is fixed -unchangeable, and signature of static method is given), and my intention is to get the matches between the characters and print them out.
But there are some concerns:
1) How do i ensure it doesn't print when all the strings are aligned but there are extra characters which makes the boolean false and the result to be not aligned instead? (e.g amgk as second string & first string is Java Programming Course)
2) How do i make it print right? currently the spaces are off and the letters aren't what is wanted.
3) If there is more than one character a in str1, which do i choose to put, and how do i omit the rest when there is already a match?
Would really appreciate a pseudocode to help guide a beginner like me in solving this problem.
public class Q3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first string:");
String input1 = sc.nextLine();
System.out.print("Enter the second string:");
String input2 = sc.nextLine();
System.out.println();
if (matchStrings(input1, input2)) {
System.out.println();
System.out.println("There is an alignment as shown above.");
} else {
System.out.println("No alignment can be found.");
}
}
public static boolean matchStrings(String str1, String str2) {
// Modify the code below to return the correct value.
boolean isMatch = false;
//int firstChar = str2.charAt(0);
//int lastChar = str2.charAt(str2.length()-1);
int prevIndex = 0;
System.out.println(str1);
for (int j = 0; j< str2.length(); j++) {
for (int i = 0; i<str1.length();i++) {
char charToSearch = str1.charAt(i);
int newIndex = i;
if (str2.charAt(j)== charToSearch) {
for (int k = prevIndex; k < newIndex-1; k++) {
System.out.print(" ");
}
System.out.print(charToSearch);
//prevIndex=newIndex+1;
isMatch = true;
}
}
}
return isMatch;
}
}
I think two of the first few structures you learn in a Data Structures course is the stack and queue. Thus, I will provide an implementation using a Stack. You can use a Stack to store the test String and pop each char element off the stack when it is matched up with a character in the first string. Otherwise you would output an empty space " " in the matched String object:
Stack s2 = new Stack();
String str1 = "Java Programming";
String str2 = "amg";
for(int i = str2.length()-1; i >= 0; i--){ //Need to populate the stack backwards...LIFO
s2.push(str2.charAt(i));
}
String match = ""; //Used to store the matching line
for(int i = 0; i < str1.length(); i++){
if(str1.charAt(i) == (char)s2.peek()){
match += s2.pop().toString();
}
else
{
match += " ";
}
}
System.out.println(str1);
System.out.println(match);
You can also use a Queue for this, but I will leave that for you to learn on your own. Also practice on creating your own Stack object using arrays and integer pointers to handle overflow/underflow.
The above code would print out:

What am I doing Wrong here [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I made a program to search for a certain string in another string and print Word found if the condition is true or print word not found if condition is false
The logic is as follows
enter word
length of word
for searching for letter [1]
if true
then for till length of word match with string to be searched
else continue loop
But I always get word not found no matter what the input, please help me over here!!!
The code is as follows :-
import java.util.Scanner;
class Search_i_String
{
public static void main(String args[])
{
int flag=0;
Scanner Prakhar=new Scanner(System.in);
System.out.println("Enter a String");
String ori=Prakhar.nextLine();
System.out.println("Enter the String to be Searched");
String x=Prakhar.nextLine();
char a[]=new char[ori.length()];
char b[]=new char[x.length()];
for(int i=0;i<ori.length();i++)
{
a[i]=ori.charAt(i);
}
for(int i=0;i<x.length();i++)
{
b[i]=x.charAt(i);
}
for(int i=0;i<a.length;i++)
{
if (a[i]==b[0])
{
for(int j=0;j<b.length;j++)
{
while(flag==0)
{
if(b[j]==a[i])
{
flag=0;
}
else if(b[j] != a[i])
{
flag=1;
}
i++;
}
}
}
}
if (flag==0)
{
System.out.println("Word Found !!!");
}
else
System.out.println("Word not Found");
}
}
P.S. : I know I can use the contains() function but I can as my professor suggests against it and could someone please correct the program I have written, because I could have scavenged off a program from the internet too if I had to, I just wanted to use my own logic
Thank You(again)
while(flag==0)
{
if(b[j]==a[i])
{
flag=0;
}
else if(b[j] != a[i])
{
flag=1;
}
i++;
j++; //add this and try once
}
If you are comparing strings in Java, you have to use equals();
So, stringA.equals(stringB);
Cheers!
Let me get this straight. You're looking for b array inside of a array? "Enter the string to be searched" means that you are searching the other way around, but I'll go with the logic your code seems to follow... Here's a naive way to do it:
if (a[i]==b[0])
{
flag = 0;
for(int j=0;j<b.length;j++)
{
if(b[j] != a[i+j]) // will array index out of bounds when its not foud
{
flag++; // you should probably break out of a named loop here
}
}
if(flag == 0){/*win*/}
}
You're modifying your first search loop with variable i when you don't have to. You can just add i to j. Also, you don't need the while loop inside if i'm understanding your problem. Like others have said, functions exist to do this already. This algorithm isn't even as efficient as it could be.
I know of an algorithm where you check starting in the last character in b instead of the first character in b to begin with. Then you can use that information to move your search along faster. Without resorting to full pseudo code, anyone know what that's called?
The simple way(but not the fastest way) is use double loop to check the chars in strings one by one, pls ref to my code and comments:
public class SearchString {
public static void main(String[] args) {
String a = "1234567890";
String b = "456";
// Use toCharArray() instead of loop to get chars.
search(a.toCharArray(), b.toCharArray());
}
public static void search(char[] a, char[] b) {
if (a == null || b == null || a.length == 0 || b.length == 0) {
System.out.println("Error: Empty Input!");
return;
}
int lenA = a.length, lenB = b.length;
if (lenA < lenB) {
System.out
.println("Error: search key word is larger than source string!");
return;
}
// Begin to use double loop to search key word in source string
for (int i = 0; i < lenA; i++) {
if (lenA - i < lenB) { // If the remaining source string is shorter than key word.
// Means the key word is impossible to be found.
System.out.println("Not found!");
return;
}
// Check the char one by one.
for (int j = 0; j < lenB; j++) {
if (a[i + j] == b[j]) {
if (j == lenB - 1) { // If this char is the last one of key word, means it's found!
System.out.println("Found!");
return;
}
} else {
// If any char mismatch, then right shift 1 char in the source string and restart the search
break;
}
}
}
}
}
You can just use String.contains();
If you really want to implement a method, try this one:
public static void main(String[] args) {
// Initialize values searchedWord and original by user
String original = [get original word from user] ;
String searchedWord = [get searched for word from user];
boolean containsWord = false;
int comparePosition = 0;
for(int i = 0; i < original.length() - searchedWord.length(); i++) {
if(original.charAt(i) == searchedWord.charAt(comparePosition)) {
comparePosition += 1;
} else {
comparePosition = 0;
}
if(comparePosition == searchedWord.length()) {
containsWord = true;
break;
}
}
return containsWord? "Word found!!" : "Word not found.";
}

Categories

Resources