User defined function for String? - java

I have following code in Java:
public class StringSearch
{
public static void main(String[] args)
{
String s = new String("I love my school. I love to play basketball. It is lovely weather. Love is life.");
System.out.println(s);
int i = -1;
int count = 0;
System.out.print("Counting love:");
do{
i = s.findW("love");
if(i != -1){
count++;
System.out.print(count+" ");
}
}while(i != -1);
System.out.println("The word \"love\" appears "+count+" times.");
}
}
I know that s.findW() is incorrect because findW() is not defined for Class String. However, is it possible to add user defined function in the class String and fix this?
Any alternative to fix this?
Hint for this problem is to read JDK documentation and fix the code. :/

I would the use the indexOf method as follows:
String s = new String("I love my school. I love to play basketball. It is lovely weather. Love is life.").toLowerCase();
System.out.println(s);
int i = 0;
int count = 0;
System.out.print("Counting love:");
while(i != -1)
{
i = s.indexOf("love");
if(i != -1){
count++;
s = s.substring(i+1);
System.out.print(count+" ");
}
}
System.out.println("The word \"love\" appears "+count+" times.");
Depending on whether you expect the answer to be 3 or 4, you would need to have the toLowerCase in there so that Love either matches or does not match.

The Java String class is final and cannot be altered. You could write your own but that would be crazy. There is generally enough funtionality on String already. If it doesn't do what you want, write a helper class with some methods.

Java regex is your friend!
String s = "I love my school. I love to play basketball. It is lovely weather. Love is life.".toLowerCase();
int count = (s.length() - s.replaceAll("love", "").length()) / 4;
System.out.println("The word \"love\" appears " + count + " times.");

Related

Show Characters shared between two strings

For a Java exercise I'm writing a program where the user enters two strings. The program then checks to see if the two strings share any similar characters and outputs them to the screen.
For example is Terrarium and Terraform are the two strings it should print t e r r a r. However when I run my program it always simply outputs all the characters in the first string. (In this case T e r r a f o r m.)
I suspect I'm creating a logical error based on a limited understanding of loops. But when I search for answers people seem to always use a similar method to my own.
Here is the code for your viewing:
import java.util.Scanner;
public class CountMatches
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println(" Please enter a String >> ");
String stringA = keyboard.nextLine();
System.out.println(" Please enter another String >> ");
String stringB = keyboard.nextLine();
for(int counter = 0; counter < stringA.length(); counter++ )
{
char compareA = stringA.charAt(counter);
char compareB = stringB.charAt(counter);
//System.out.println(compareA);
//System.out.println(compareB);
//System.out.println("");
if(compareA != compareB)
{
System.out.println("");
}
else if(compareA == compareB);
{
System.out.println(compareA);
System.out.println("");
}
}
}
}
else if(compareA == compareB);
Get rid of the semicolon on this line and it should work. I would also get rid of the first if statement just keep the second one.
You have two problems with this code.
First,
for(int counter = 0; counter < stringA.length(); counter++ )
If the two string are of different length, you could get an exception by going off the end of the other string. So, do this:
int len = stringA.length();
if (len > stringB.lengh()) len = stringB.length();
Next, the reason you code fails is because you have a ; at the end of your else. Your code should be:
if(compareA != compareB)
{
System.out.println("");
}
else // Don't need the == here
{
System.out.println(compareA);
System.out.println("");
}
Good luck with this.

Using methods to check for palindromes

I have to use methods to test a sentence for palindromes and I have got most of it done but it will only do the first word in the string and won't move on to the next one. I believe its something got to do with the spaces, if anyone could help that'd be great. Also I haven't studied arrays so I'd appreciate if arrays were not used.
class palindromeTesting
{
public static void main(String[] args)
{
String userInput;
String goodWords;
String palindromes;
System.out.println("Please enter a sentance to be tested for palindrome: ");
userInput = EasyIn.getString();
userInput += " " ;
goodWords = charsCheck(userInput); //Calling a method to check if any word contains more than letters.
palindromes = palinCheck(goodWords); //Checking the good words to see if they're palindromes.
System.out.println("The valid palindromes are " + palindromes);
} //Main
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
public static String charsCheck(String userInput)
{
String validWords;
String firstWord;
Boolean goodWord;
int spacePos;
char letter;
spacePos = userInput.indexOf(" ");
validWords = "";
while(spacePos > 0)
{
firstWord = userInput.substring(0 , spacePos);
goodWord = true;
for(int index = 0 ; index < firstWord.length() && goodWord == true ; index++)
{
spacePos = userInput.indexOf(" ");
letter = Character.toUpperCase(firstWord.charAt(index));
if(letter < 'A' || letter > 'Z' )
{
goodWord = false;
}
} //for
if(goodWord == true)
{
firstWord = firstWord + " ";
validWords = validWords + firstWord;
}
userInput = userInput.substring(spacePos + 1);
spacePos = userInput.indexOf(" ");
} //While
return validWords;
} //charsCheck main
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
public static String palinCheck(String goodWords)
{
String firstWord;
String validPalins = "";
String backward = "";
int spacePos;
spacePos = goodWords.indexOf(" ");
while(spacePos > 0)
{
firstWord = goodWords.substring(0 , spacePos);
for(int i = firstWord.length()-1; i >= 0; i--)
{
backward = backward + firstWord.charAt(i);
}
if(firstWord.equals(backward))
{
validPalins = validPalins + firstWord;
}
goodWords = goodWords.substring(spacePos + 1) ;
spacePos = goodWords.indexOf(" ") ;
}//While
return validPalins;
} //palinCheck main
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
} //Class
If you believe the issue are spaces, you could always remove all spaces (and any other unwanted characters) with the replaceAll() method (check out the API). Say you have word1 and word2 you'd like to compare to see if they are palindromes, then do the following:
String word1 = "du mb";
String word2 = "b,mu d";
word1 = word1.replaceAll(" ", "");//replace it with empty string
word1 = word1.replaceAll(",", "");//even if the comma doesn't exist, this method will be fine.
word2 = word2.replaceAll(" ", "");
word2 = word2.replaceAll(",", "");
Once you've gotten ridden of unnecessary characters or spaces, then you should do the check. Also, you could always use Regex expressions for this kind of task, but that may be a bit difficult to learn for a beginner.
Also, I recommend using for loops (can probably be done in one for loop, but nested loops will do) instead of while loop for this task. Check out this example.
Sidenote:
Also I haven't studied arrays so I'd appreciate if arrays were not
used.
Strings are essentially char arrays.
The problem you described is actually not what is happening; your code does indeed move on to the next word. For my test, I used the test input Hi my name is blolb.
The problem is in your palinCheck method. You are using the backward variable to reverse the word and check whether it and firstWord, are equal. However, you aren't resetting the backward variable back to a blank string in the loop. As a result, you're constantly adding to whatever was in there before from the previous loop. At the end of the method, if I examine the content of backward using my test string above, it actually looks like iHymemansiblolb.
To solve this, simply declare String backward inside the while loop, like so:
while(spacePos > 0) {
String backward = "";
// rest of loop
Quick side note:
During the run of the palinCheck method, you're changing the goodWords parameter each iteration when you do this:
goodWords = goodWords.substring(spacePos + 1) ;
While this is technically acceptable (it has no effect outside of the method), I wouldn't consider it good practice to modify the method parameter like this. I would make a new String variable at the top of the method, perhaps call it something like currentGoodWords or something like that, and then change your line to:
currentGoodWords = goodWords.substring(spacePos + 1) ;
Also, I assume this is homework, so if you are allowed to use it, I would definitely take a look at the StringBuilder#reverse() method that Elliot Frisch mentioned (I admit, I never knew about this method before now, so major +1s to Elliot).
I had this code written as a personal project quite a while ago on palindrome using the shortest amount of code. It basically strip every non-word character, put it to lower case just with 13 lines. Hope this help haha! Let's hope other guys would get lucky to find this too.
import java.util.Scanner;
public class Palindrome {
public static void main(String[]args){
if(isReverse()){System.out.println("This is a palindrome.");}
else{System.out.print("This is not a palindrome");}
}
public static boolean isReverse(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type something: ");
String line = ((keyboard.nextLine()).toLowerCase()).replaceAll("\\W","");
return (line.equals(new StringBuffer(line).reverse().toString()));
}
}

Making a hangman game [duplicate]

This question already has answers here:
Creating hangman game without arrays [closed]
(3 answers)
Closed 9 years ago.
Logic:
This is how the output should look like. http://prntscr.com/1is9ht i need to find the index of guess in the orginalString. If that's true then it should replace the question mark at the index with the character read in the string guess. After that it should take out that char from the string "abcdefghijklmnopqrstuvwxyz".
If originalString doesn't contain guess than it should only take out that char from the string "abcdefghijklmnopqrstuvwxyz" I looked up this question on google and found a bunch of codes, they were all using arrays or something that I have not learned in the classes. So please don't use arrays. I am stuck at the if else statement. Is there any way to solve this problem without using Arrays.
int count=1;
while (count<=24){
Scanner keyboard = new Scanner(System.in);
int length;
String originalString;
String guess;
String option= "abcdefghijklmnopqrstuvwxyz";
String questionmarks;
System.out.println("Please enter a string");
originalString=keyboard.nextLine();
length=originalString.length();
questionmarks = originalString.replaceAll(".", "?");
System.out.println("Original String: "+originalString);
System.out.println("Guessed String: "+questionmarks);
System.out.println("Characters to choose from: "+option);
System.out.println("Please guess a character");
guess=keyboard.nextLine();
if (originalString.contains(guess)){
count++;
}
else{
option.replace(guess, "_");
count++;
System.out.println(option);
}
Please suggest me some code that doesn't implement array concept for my problem,
Any help will be appreciated
A few things that I noticed from a cursory glance:
.replace() returns a String, it will not modify option unless you do:
option = option.replace(guess, "_");
Also, since you don't want to use Arrays, I highly suggest that you use StringBuilder
EDIT 1 (based off of comment from duplicate thread):
You can use a StringBuilder to have a String that's initialized to all -. Then when someone guess a correct letter, you can replace the - with the guess.
StringBuilder sb_word = new StringBuilder(lengthOfOriginalString);
for (int i = 0; i < length; i++)
sb_word.append('-'); //add hyphens to StringBuilder, StringBuffer would also work
You should really use something like:
final char blank = '-';
Then, after someone makes a guess, if you've determined that the character at position i should be replaced by guess, you could do:
sb_word.setCharAt(i, guess.charAt(0));
EDIT 2:
while (bodyparts > 0 && !win) //play game while you have bodyparts and haven't won
{
System.out.printf("Word to guess: %s\nEnter a letter or word guess: " , sb_word);
guess = keyboard.next();
if (guess.length() == 1)
{
for (int i = 0; i < length; i++) //loop to see if guess is in originalString
if (Character.toLowerCase(word.charAt(i)) ==
Character.toLowerCase(guess.charAt(0)))
{ //it is, so set boolean contains to be true and replace blank with guess
sb_word.setCharAt(i, guess.charAt(0));
contains = true;
}
if (!contains)
{
bodyparts--;
System.out.printf("Incorrect, you have %d bodyparts left.\n", bodyparts);
}
else if (sb_word.indexOf(String.valueOf(blank)) == -1)
{ //all the letters have been uncovered, you win
win = true;
System.out.println(word);
}
else
{
contains = false;
System.out.println("Good guess.");
}
}
else
{
if (guess.equals(word))
win = true;
else
{
bodyparts = 0;
System.out.printf("Incorrect, you have %d bodyparts left.\n" , bodyparts);
}
}
}

Java homework hangman [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
So for a class we are having to make a hangman game that can take a user input for a word and then have another person solve for it. It has to be able to recognize multiple repeating letters in the word or I would be done. Below is my code, it works great until I remove the break statement in my checkformatch method so that it goes past the initial finding of a letter. With the break in there it never finds the second third etc repeated letters, without it, it returns that each letter that is not the letter searched is a miss and reduces my life count. What I'm needing is some hints on how to search my array for the letter that is inputted as a guess and return their index positions in the array without it thinking each character in the array that is not the one guessed is a wrong input. Thank you in advance.
package hangman;
import java.util.Scanner;
class Game {
int livesRemaining;
String letterGuessed;
String wordInput;
char[] hiddenWord;
char[] aOfWord ;
Scanner input = new Scanner(System.in);
boolean isFound;
int a;
public Game()
{
this.setLives(8);
//this.output();
System.out.println("Player 1 please enter the word to be searched: ");
wordInput = input.nextLine();
aOfWord = wordInput.toCharArray();
hiddenWord = new char[aOfWord.length];
for(int j = 0; j < hiddenWord.length; j++)
hiddenWord[j] = '*';
this.output();
while(livesRemaining > 0)
{
System.out.println("Please choose a letter: ");
letterGuessed = input.nextLine();
this.checkForMatch(letterGuessed);
if(isFound == true)
{
hiddenWord[a] = letterGuessed.charAt(0);
}
else
{
System.out.println("Is not found!");
this.reduceLives();
}
this.output();
}
}
public void setLives(int a)
{
this.livesRemaining = a;
}
public void reduceLives()
{
livesRemaining = livesRemaining -1;
System.out.println("Lives remaining: " + this.getLives());
}
public int getLives()
{
return livesRemaining;
}
public void output()
{
System.out.println("Lives remaining: " + this.getLives());
System.out.println("Word found so far ");
for(int i = 0; i < hiddenWord.length; i++)
{
System.out.print(hiddenWord[i] + "\n");
}
}
public void checkForMatch(String l)
{
for(int i = 0; i < aOfWord.length; i++)
{
//System.out.println("Comparing " + l.charAt(0) + " To " + aOfWord[i]);
if(l.charAt(0) == aOfWord[i])
{
isFound = true;
a = i;
break;
}
else
{
isFound = false;
}
}
}
}
To start with, if you want to return the indices of the chars, you'll need to add them somewhere, I would recommend returning an ArrayList which would hold all of your values. This is because an ArrayList can grow in size if it is too small and you'll not really need to worry about an out of bounds issue.
Your current form of checkForMatch works for what you want, but consider returning a boolean instead of setting your isFound field to true/false. Also there is a contains method that the String class has which you can call, so an alternative to your checkForMatch would be possible sort of like
String yourString = "Hello";
String yourChar = "e";
System.out.println(yourString.contains(yourChar));
Which of course would print true!
Now, to get the indices, you already traverse the array and compare characters in your checkForMatch() method, why not simply create an ArrayList<Integer> matchedIndices = new ArrayList<Integer>(); at the top of your method, and instead of setting isFound to true, call matchedIndices.add(i); if the characters match, and then at the end return the ArrayList?
You would of course have to swap your return type from void to ArrayList, but there are many ways to go about this, this being just the first that came to my head!
Your algorithm seems fine. However, it will only get you the last matching character because a will be rewritten whenever he finds a matching character.
I think a really simple solution would be to do this in your checkForMatch method:
if(l.charAt(0) == aOfWord[i])
{
isFound = true;
hiddenWord[i] = l.charAt(0);
}
and also this in your game method...
if(!isFound)
{
System.out.println("Is not found!");
this.reduceLives();
}
You don't have to use this. by the way. That is only necessary in certain cases. Take a look at this.

How to sort the array list?

Hey Guys. thanx for the major help regarding my obstacles.
What my problem this time is, how can I sort the array list that is provided in my code basically dont know WhatI need to add in the provied code below, just to simplyfive it I got 3 arraylist that i want to make them into one arraylist, so they can be sorted in amont of guesses and tries( if 2 players have the same guesses then the time should determine) .
Pretty hard to explain it but i tried my best.............the best thing is to run it then you will figure it what whats the issue is?
Here is the code:
import java.util.*;
import java.util.Scanner.*;
import java.util.ArrayList.*;
public class Main {
public static String ToString(int a, double b, String c)
{
String aS = Integer.toString(a);
String bS = Double.toString(b);
String scoreList = (aS + "\t\t" + bS + "\t\t" + c);
return scoreList;
}
private static void start() {
int tries = 0 ;
int guess = -1;
String name ;
String quit = "quit";
String y = "yes";
String n = "no";
String currentGuess;
String another = ("y") ;
Scanner input = new Scanner (System.in);
ArrayList<String> scores = new ArrayList<String>();
boolean a=false;
do {
a=false;
int answer = (int) (Math.random() * 1000 + 1) ;
System.out.println( " Welcome to Guessing Game " ) ;
System.out.print("Please enter a number between 1 and 1000 : ");
currentGuess = input.nextLine();
long startTime = System.currentTimeMillis();
do
{
if (currentGuess.equalsIgnoreCase(quit))
{
System.out.println("Leaving Us So Soon?");
System.exit(0);
}
try {
guess = Integer.parseInt(currentGuess);
} catch (NumberFormatException nfe)
{
System.out.println(" Dude Can You Read, Only Digits ");
currentGuess = input.nextLine();
}
if (guess < 1 || guess > 1000)
{
System.out.println("Stupid Guess I Wont Count That.");
currentGuess = input.nextLine();
}
if (guess < answer )
{
System.out.println("too low "+answer);
currentGuess = input.nextLine();
tries++;
}
else if(guess > answer )
{
System.out.println("too high "+answer);
currentGuess = input.nextLine();
tries++;
}
else if (guess == answer)
{
//stop stop watch
long endTime = System.currentTimeMillis();
//calculate game time
long gameTime = endTime - startTime;
System.out.println("You Rock Dude, Good Job!");
System.out.println("You guessed " + tries + " times in " + (int)(gameTime/1000) + " seconds.");
System.out.println("Please enter your name.");
name = input.nextLine();
//create score object
String TOString =ToString(tries, gameTime, name);
//add score to arrayList
scores.add(TOString);
boolean s = false ;
while (s==false)
{
System.out.print("Want to go again?(y/n).....");
currentGuess = input.nextLine();
if (currentGuess.matches("y"))
{
System.out.println("HighScore: \nGuess \t Time in milisec\tName");
//print out high score list
for (int i = 0;i < scores.size(); i++)
{
System.out.println(scores.get(i));
}
// Main.start
s=true;
}
//if user doesn't want to play again
if (currentGuess.matches("n"))
{
System.out.println("HighScore:\nGuess \tTime in milisec\tName");
//print out high score list
for (int i = 0;i < scores.size(); i++)
{
System.out.println(scores.get(i));
}
System.out.println("Thanx For Playing.");
a=true;
s=true;
System.exit(0);
}
}
}
} while (guess != answer);
}while(a==false);
}
public static void main(String[] args) {
// ArrayList<Score> scores = new ArrayList<Score>();
Main.start();
}
}
Use Collections.sort() and make sure your class implements Comparable or use something like this:
Collections.sort(list, new Comparator<T>() {
public int compare(T o1, T o2) {
return o1.compareTo(o2);
}});
You can use something like input.nextInt() to read in the next integer instead of the next String. I can see no reason why you are storing Strings instead of ints in your code. Then you can use what everyone else has suggested to combine the lists and/or sort them.
I also think you should do some more reading by yourself. Some of the questions you've asked in your comments are answered in the Java documentation.
When someone posts a suggestion, at the very least look it up in the API and try to understand it. People won't be giving you all the code here, they will just give you hints that you need to follow.
To sort an ArrayList you can use the Collections.sort() method; either with only a List of Comparable elements or with a Comparator.
This is the simplest way.
In your case Collections.sort(scores) will do the thing.
To sort a list, use java.util.Collections.sort( list ).
To make one list out of three, you can use alist.addAll(anotherList). Then sort aList as suggested by Collin Hebert.
I helped to answer this in your previous post. However, I will add it here as well. I think you may want a List instead of a list of Strings. This will allow you to sort on the number of tries the end user has attempted, in a natural way. In addition to the other answers here, the simplest way is then to make a call to Collections.sort(list)
Additionally the toString() method is used for debugging purposes, or to provide human readable information. It shouldn't be used to create objects in the way that you are utilizing it. Just my .02
If you absolutely require a list to be sorted at all times, don't use an ArrayList, use a PriorityQueue. It can be constructed to use the content's natural sort order (i.e. via the Comparable interface on each object), or via a Comparator. The advantage of PriorityQueue is it is always sorted even after new items are added.

Categories