What am I doing Wrong here [duplicate] - java

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.";
}

Related

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

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.

To find smallest word in a string in java

This is the code that i have written for finding the smallest word in a string but whenever i try to run it in eclipse it shows me an (String index out of range -2147483648) error in nested while statement, that i had marked , i do not understand the cause of it since my program seems to be running well in the range i.e less than length of the input string.
Thanks in advance!!
import java.util.Scanner;
public class Minword {
public static String minLengthWord(String input){
// Write your code here
int count[]=new int[50],i,j=0,len=input.length();
String output = "";
for(i=0;i<len;i++)
{
if(input.charAt(i)!=' ')
{
count[j]++;
}
else
j++;
}
int minidx=0;
for(i=1;i<j;i++)
{
if(count[minidx]>count[i])
minidx=i;
}
int words=0;
i=0;
while(words<=minidx)
{
if(words==minidx)
{
***while(i<len && input.charAt(i)!=' ')***
{
output+=input.charAt(i);
i++;
}
}
else if(i<len && input.charAt(i)==' ')
words++;
i++;
}
return output;
}
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String input,output;
input=s.nextLine();
output=minLengthWord(input);
}
}
I have problems following your code, but to get the shortest word's length, you can use a Stream and min(). Your minLengthWord method could be like:
String f = "haha hah ha jajaja";
OptionalInt shortest = Arrays.stream(f.split(" ")).mapToInt(String::length).min();
System.out.println(shortest.getAsInt());
You are using the variable i, which is a signed int, so it ranges from -2147483648 to 2147483647.
The following case shows your problem:
i = 2147483647;
i++;
After the increment, i's value will be -2147483648 due to a int overflow. Check this question.
It seems you are getting a huge input, thus it is causing the problem.
Well, -2147483648 is the maximal integer + 1. You have a wrap around. The variable i got so big that it start on the negative side again.
You have to use a long if you want to process texts that are larger than 2 GB.
while(words<=minidx)
{
if(words==minidx)
{
***while(i<len && input.charAt(i)!=' ')***
{
output+=input.charAt(i);
i++;
}
}
else if(i<len && input.charAt(i)==' ')
words++;
i++;
}
Your problem is you when words and minidx are both 0, your outer while loop is always true and words are always equal to minidx, and i keeps increasing until reaches its maximum number.
you need to add break after your inner while loop and secondly, you need to change i<j to i<=j
Below is the corrected code:
int minidx = 0;
for (i = 1; i <= j; i++) { //-------------------------> change i<j to i<=j
if (count[minidx] > count[i])
minidx = i;
}
int words = 0;
i = 0;
System.out.println(minidx);
while (words <= minidx) {
if (words == minidx) {
while (i < len && input.charAt(i) != ' ') {
output += input.charAt(i);
i++;
}
break; //-------------------------> add break statement here.
} else if (i < len && input.charAt(i) == ' ') {
words++;
}
i++;
}
When I tried running your code with an input of "Hello World", minidx was 0 before the while loop. words is also 0, so words<=minidx is true and the loop is entered. words==minidx is true (they're both 0), so the if statement is entered. Because it never enters the else if (which is the only place words is changed), words is always 0. So the loop becomes an infinite loop. In the meantime, i just keeps growing, until it overflows and becomes negative.
Here's a version that makes use of Java 8's Stream API:
Remove all your code from minLengthWord Method and paste below code it will work and resolve your runtime issue too
List<String> words = Arrays.asList(input.split(" "));
String shortestWord = words.stream().min(
Comparator.comparing(
word -> word.length()))
.get();
System.out.println(shortestWord);

How do I do palindromes in java? [duplicate]

This question already has answers here:
Check string for palindrome
(42 answers)
What's the simplest way to print a Java array?
(37 answers)
Closed 9 years ago.
First time posting here! Yeah I kind of just need some help with this assignment. We had to read an input file, go through a loop for each character in a line of the input file, and store that info in a char array, and then finally write an isPalindrome method and call it to determine if that line is a palindrome and print it to the console.
This is what I have so far, sorry if I didn't format correctly, it was kind of confusing.
I'm still kind of a beginner and I'm not sure where I'm going wrong. My output is essentially "[C#91bee48 is not a palindrome!" over and over again with some variation on whether or not its a palindrome.
public class Palindromes {
public static void main(String[] args) {
int k = 0;
try {
Scanner inF = new Scanner(new File("palindromes.txt"));
String aString;
while (inF.hasNextLine()) {
aString = inF.nextLine();
k++;
for (int i = 0; i < k; i++) {
char[] phrases = new char[aString.length()];
if (Character.isLetter(aString.charAt(k))) {
phrases[i] = aString.charAt(i);
}
isPalindrome(phrases);
}
}
}
catch (FileNotFoundException e) {
System.err.println("palindromes.txt not found!");
}
}
public static void isPalindrome(char[] phrases) {
boolean isPalindrome = false;
int i1 = 0;
int i2 = phrases.length - 1;
while (i2 > i1) {
if (phrases[i1] != phrases[i2]) {
isPalindrome = false;
System.out.println(phrases + " is not a palindrome!");
} else {
isPalindrome = true;
System.out.println(phrases + " is a palindrome!");
}
i1++;
i2--;
}
}
}
Use Arrays.toString() to get the string representing the array.
For example:
System.out.println(Arrays.toString(phrases) + " is not a palindrome!");
Otherwise you get the default toString() for an array object - which is not what you are after.
The logic of your while loop is faulty. This kind of loop is a common idiom: you have to check a number of things, and if any check fails, you want the result to be false. If no check fails, you want the result to be true. The thing is, you can't tell if the result is true until the loop is completely finished. Your code is:
while (i2 > i1)
{
if(phrases[i1] != phrases[i2])
{
isPalindrome = false;
System.out.println(phrases + " is not a palindrome!");
}
else
{
isPalindrome = true;
System.out.println(phrases + " is a palindrome!");
}
i1++;
i2--;
}
The problem is that you're printing "is a palindrome" before you've checked all the characters, and you can't possibly know that. The way to write this kind of loop is something like this:
isPalindrome = true;
while (i2 > i1)
{
if(phrases[i1] != phrases[i2])
{
isPalindrome = false;
break; // get out of the loop, it's pointless to continue
}
i1++;
i2--;
}
// *** NOW you can check isPalindrome and display your output

Palindrome Program

I'm trying to write a program which will output what Palindromes will work from entering in a string and how many there are. I keep getting a lot of errors and I'm still trying to get my head around some of the harder topics in Java!
Here's what I have already, as always, all answers are greatly appreciated!
public static boolean Palindrome(String text) {
int index;
int palindrome;
System.out.println("Please enter your text ");
text = EasyIn.getString();
for(index = 0; index < amount.length() / 2; index++) {
if(text.charAt(index) != text.charAt(text.length() - index - 1)) {
return false;
}
}
System.out.println("The number of valid palindrome(s) is " + amount);
amount = EasyIn.getString();
}
I think the problem is in amount.length(), you should use text.length(), since you are looping over the half of text. The algorithm works fine. Here is a reduced example:
public static boolean palindrome(String text)
{
for (int index = 0; index < text.length() / 2; index++) {
if (text.charAt(index) != text.charAt(text.length() - index - 1)) {
return false;
}
}
return true;
}
Note:
You forgot to add a return true statement, if you don't add one, is possible that the for loop finishes and no return statement is reached, which will cause an error.
I would recommend you to follow Java naming conventions. You method should be called like someMethodName instead of SomeMethodName. This last is used for class names.
Edit:
As #bobbel commented, you could improve this code by assigning text.length() to a variable and using it inside the for.
There can be two things:
ammount variable that you used either it could be a string array that you are maintaining strings inside it, if this is the case than you have to loop first through array of strings and then maintain one nested loop to check that strings inside it are palindrom or not
or second case is that you have used the variable incorrect it may be text instead of ammount
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("enter string to check for palidrome");
String orginal = in.next();
int start = 0;
int middle = orginal.length()/2;
int end = orginal.length() - 1;
int i;
for(i=start; i<=middle; i++) {
if(orginal.charAt(start) == orginal.charAt(end)) {
start++;
end--;
} else {
break;
}
}
if(i == middle+1) {
System.out.println("palidrome");
} else {
System.out.println("not palidrome");
}
}
This is the Simplest way of Checking Palindrom number.
package testapi;
public class PalindromNumber {
public static void checkPalindrom(Object number) {
StringBuilder strNumber = new StringBuilder(number.toString());
String reverseNumber = strNumber.reverse().toString();
if (number.toString().equals(reverseNumber)) {
System.out.println(number + " is palindrom number");
} else {
System.out.println(number + " is not palindrom number");
}
}
public static void main(String[] args) {
checkPalindrom(101);
checkPalindrom(10.01);
checkPalindrom("aanaa");
}
}

Deleting Duplicate Characters in a String

Hi I need to fix this code to delete characters that repeat immediately in the string. For example: If I type aaabbbcccdeeff, it has to return abcdef at the end. However on the computer in class it returns something of a, "out of range (number)", the number being dependent on how many characters I used. On my mac however it just returns a number like 3 as an output and gives no error message. I am on Eclipse.
Please help, I didn't understand what the professor said and he rarely helps. The code is (somewhat helped by professor):
package firstProgramSimple;
import java.awt.Toolkit;
import java.util.Scanner;
public class SimpleVersion {
public static void main(String[] args) {
Scanner kb = new Scanner(System. in );
System.out.println("Entre String");
String string = kb.nextLine();
//System.out.println(string);
int length = string.length();
for (int i = 1; i < length; i++) {
if (string.charAt(i) != string.charAt(i - 1)) {
System.out.print(i);
} else if (string.charAt(i) != string.charAt(i)) {
System.out.print(i);
}
}
}
}
You need to print string.charAt(i) and not i.
Also, this piece of code is unnecessary since it will always return false:
//string.charAt(i) is always equal to itself
else if ( string.charAt(i) != string.charAt( i )) {
System.out.print(i);
Since you start at i = 1, the char at index 0 will never be printed. Before the for-loop, you should add this line:
System.out.print(string.charAt(0));
You are printing your loop counter and not the value of the char at the position of the counter:
System.out.print(i);
Should be:
System.out.print(string.charAt(i));
You will get an arrayOutOfBoundsException for inputs of size < 2. You might want to add this line once you have the string initialised:
if(string == null || string.length() < 2){
System.out.println(string);
return;
}
Something like this:
public static void main(String[] args) {
Scanner kb = new Scanner(System. in );
System.out.println("Entre String");
String string = kb.nextLine();
//System.out.println(string);
int length = string.length();
if(length < 2) {
System.out.println(string);
return;
}
System.out.print(string.charAt(0));
for (int i = 1; i < length; i++) {
if (string.charAt(i) != string.charAt(i - 1)) {
System.out.print(string.charAt(i));
}
}
}
Just replace your for loop like bellow:
System.out.print(string.charAt(0));
for (int i = 1; i < length; i++) {
if (string.charAt(i) != string.charAt(i - 1)) {
System.out.print(string.charAt(i));
}
}
The idea is, print the beginning character first, then print the character at i th position, only if its different then its previous character. Simple!

Categories

Resources