Debugging a simple console game for Java - java

import java.util.Scanner;
public class Project3 {
public static void main(String[] args) {
Scanner keys = new Scanner(System.in);
System.out.println("Welcome to mini mad libs!"); // word1-word3 are inputs that point out which words from the story need to be replaced.
System.out.printf("Please enter the story: ");
String story = keys.nextLine();
System.out.printf("Please enter the first word type that should be replaced:");
String word1 = keys.nextLine();
System.out.printf("Please enter the second word type that should be replaced:");
String word2 = keys.nextLine();
System.out.printf("Please enter the third word type that should be replaced:");
String word3 = keys.nextLine();
System.out.println();
System.out.println("Ok, the game is ready to play!"); //the replace strings are the new words that are replacing the original words in the story.
System.out.println("Please enter a word type to replace "+word1);
String replace1 = keys.nextLine();
System.out.println("Please enter a word type to replace "+word2);
String replace2 = keys.nextLine();
System.out.println("Please enter a word to replace "+word3);
String replace3 = keys.nextLine();
String storyV2 = story.toLowerCase();
String word1V2 = word1.toLowerCase();
String word2V2 = word2.toLowerCase();
String word3V2 = word3.toLowerCase();
storyV2=storyV2.replaceAll("[.,!]", " ");
int positionOf1= storyV2.indexOf(" "+word1V2+" ");
int positionOf2= storyV2.indexOf(" "+word2V2+" ");
int positionOf3= storyV2.indexOf(" "+word3V2+" ");
int length1 = word1.length();
int length2 = word2.length();
int length3 = word3.length();
String WordMod1 = story.substring(positionOf1,positionOf1+length1);
String WordMod2 = story.substring(positionOf2,positionOf2+length2);
String WordMod3 = story.substring(positionOf3,positionOf3+length3);
String lib = story.replaceFirst(WordMod1, replace1); //lib serves as a string that has a version of the original story replaced by the three words one by one in the next lines below.
lib = lib.replaceFirst(WordMod2, replace2);
lib = lib.replaceFirst(WordMod3, replace3);
System.out.println();
System.out.println("Here is your little mad lib: \n"+ lib);
}
}
Mad libz is a game that replaces selected words from a sentence with other words of your choice. I cannot use if/else statements, loops or anything that is not string methods. My problem seems to be in this part of the code. I'm not too experienced with Java so it might look terrible.
String WordMod1 = story.substring(positionOf1,positionOf1+length1);
String WordMod2 = story.substring(positionOf2,positionOf2+length2);
String WordMod3 = story.substring(positionOf3,positionOf3+length3);
This part is making a substrings that obtain the word in a sentence, for example if I want the word "noun", it looks the standalone word anywhere in the sentence instead of possible getting the word from other words like "pronoun" or "pronounced". PositionOf1 looks for the position between blank spaces and lenghtOf1 is the length of the original word we want to replace.
That is why this is also supposed to be case insensitive so that is why I made string storyV2, its a copy of the original set to lower case.

If you just want to replace one string with another, then why not using the replaceAll() method?
String story = "...";
String fromWord = "foo";
String toWord = "bar";
String newStory = story.replaceAll(" " + foo + " ", " " + bar + " ");
You could use more elaborate regex patterns for finding foo not only enclosed by spaces but all kinds of non-word characters, so you wouldn't need to remove characters like .,; etc. first as you currently do.

Related

How to replace character in string without using the replace function in Java?

So I am asking for a string to be inputted, then I am asking what the user wants to do to the string, in this case, I am trying to replace the first occurrence of a character. I can ask for what wants to be replaced and what to replace it with. I also know how to do the replacement somewhat, but say if the string has 2 of the same characters, I get a new String for both
(Change i to o: (input)"Find Dime" --->(output) "Fond Dime" & "Find Dome")
I only need the first one.
else if (UserCommand.equalsIgnoreCase("replace first"))
{
System.out.println("Enter the character to replace");
String Replace = input.next();
System.out.println("Enter the new character");
String Replacement = input.next();
for (int i = 0; i<String.length();i++)
{
if (String.charAt(i)==Replace.charAt(0))
{
StringEdit = String.substring(0,i) + Replacement + String.substring(i + Replace.length());
}
}
Output:
Enter the string
lump sum
Enter the character to replace
u
Enter the new character
o
lomp sumlump som
if you only need the first String use
break;
in the if statement

Removing a word in Java Program

I am having trouble getting my program to produce the exact output I would like it to. My program currently will remove any one instance of a string in a sentence the user inputs (Ex: Sentence- Hello there– String to be removed Hello and Output there).
What I would like to do is add something else so that the program will remove any and all instances of the string the user would like omitted (Ex: Hello there there in my current program, it would output Hello there. What I would like is it to simply print Hello). Can someone give me any idea on how to implement this. Thanks!
(Im also rather new to coding, so if you have an input on my code as is, please feel free to correct it)
Here is my current code:
import java.util.Scanner;
public class RemoveWord
{
Scanner scan = new Scanner(System.in);
String sentence;
String word;
public void removing()
{
System.out.println("Please enter a sentence");
sentence = scan.nextLine();
System.out.println("Please enter a word you would like removed from the sentence");
word = scan.nextLine();
int start = sentence.indexOf(word), end=0;
while(start!=-1)
{
sentence = sentence.substring(0, start) + sentence.substring(start+word.length());
end = start+word.length();
if(end>=sentence.length())
break;
start = sentence.indexOf(word, end);
}
System.out.println(sentence);
}
}
public class RemoveWordR
{
public static void main(String[]args)
{
RemoveWord r1 = new RemoveWord();
r1.removing();
}//main
}//class
Your problem is with end, because indexOf(x,y) check for occurrence of x after index y. It is int indexOf(String str, int fromIndex)
while(start!=-1)
{
sentence = sentence.substring(0, start) + sentence.substring(start+word.length());
end = start+word.length();
if(end>=sentence.length())
break;
start = sentence.indexOf(word, 0); //this line must be 0 or nothing
}
replaceAll() method provided by a string should replace all occurrences of a given word in the string
Example:
sentence.replaceAll("there","")
or
sentence.removeAll("there")

Creating a Java String array

I'm not sure how to get the program to understand there are three different strings in the text file, and how would I add this to my code? I've never created an array before although I'm fairly experienced with creating fun Java programs (like calculators and such) and want to move onto the next step
I've made a program which does the following:
Program Functions:
Asks user to enter a string.
Asks user to enter a second string which will replace the last two characters of each word of the first string.
Asks user to enter a third string who's first character will replace every letter "I" of each word of the first string.
*If the words in the first string are less than two characters and do not include an I- the string will be left alone.
And here is the working code (I'm running with Ready to Program - not sure why the first bit is not included in the code):
import java.io.*;
import java.util.*;
public class StringModifications
{
private String input1, input2, input3; // Values only used within this method
public String information;
// Constructor
public StringModifications ()
{
// Initialize class data to 0
this.input1 = "";
this.input2 = "";
this.input3 = "";
}
public void setInputStrings (String s1, String s2, String s3)
{
// Method to set class data
this.input1 = s1; // Equal to string 1
this.input2 = s2;
this.input3 = s3;
}
public String processStrings ()
{
StringTokenizer stok = new StringTokenizer (this.input1); // Splits first input string (word by word)
StringBuffer strBuff = new StringBuffer ("");
String outstring = ""; // Initialize variable to 0
while (stok.hasMoreTokens () == true) // As long as there are more words in the string:
{
String word = stok.nextToken ();
if (word.length () > 2)
{
word = word.substring (0, word.length () - 2); // Removes the last two letters of each word in the first string
word = word.concat (this.input2); // Adds the second input to the end of the first string
char letter = input3.charAt (0); // Finds the first letter of the third input
word = word.replace ('I', letter); // Replaces letter I in first string with first letter of third input
}
outstring = outstring + word + " "; // Adds a space between each word when output
}
return outstring;
}
public static void main (String[] args) throws IOException
{
String string1, string2, string3;
BufferedReader keyboard = new BufferedReader ( // // Define the input stream reader
new InputStreamReader (System.in));
System.out.println ("Enter first string"); // User inputs the first string
string1 = keyboard.readLine ();
System.out.println ("Enter second string"); // User inputs the econd string
string2 = keyboard.readLine ();
System.out.println ("Enter third string"); // User inputs the third string
string3 = keyboard.readLine ();
StringModifications strProc = new StringModifications ();
strProc.setInputStrings (string1, string2, string3); // Sends values to method (e.g. this.input1 = stirng 1)
PersonalInfo pi = new PersonalInfo();
String out = strProc.processStrings (); // String (e.g. this.input1) sent through processStrings method before output
System.out.println ("Original Input: " + string1); // Displays the original input
System.out.println ("Modified Input: " + out); // Displays the modified input
}
}
and what I am trying to do is create an array which takes three inputs (Strings, which would be string1, 2 and 3 in the code), as following in the text:
1
hello how are you (string 1)
i am good (string 2)
great (stirng 3)
I'm not sure how to get the program to understand there are three different strings in the text file, and how would I add this to my code? I've never created an array before although I'm fairly experienced with creating fun Java programs (like calculators and such) and want to move onto the next step
You use String[] str = new String[n] to declare and initialize a new String array. This is a static array with a fixed length of n, where n has to be known during the initialization. Individual elements are accessed through str[i], where i is the index of an element from interval [ 0,n ).
Example of usage:
String[] phrases = new String[3];
phrases[0] = "Hello, how are you?";
phrases[1] = "I am good";
phrases[2] = "Great";
System.out.println("What phrase would you wish to see?");
Scanner in = new Scanner(System.in);
System.out.println(phrases[in.nextInt()]);
in.close();
If you need a dynamic array with variable number of elements, I would suggest looking into ArrayList class.

What did I do wrong in my program?

I am writing a program where if someone types in the following two lines:
HELLO, I’D LIKE TO ORDER A FZGH
KID’S MEAL
The program will output it like this:
HELLO, I’D LIKE TO ORDER A KID’S MEAL
In other words, the "FZGH" the user inputs into the sentence will be replaced with the second line's words, as you can see: the "FZGH" is replaced by "KID'S MEAL." Kinda get what I mean? If not, I can elaborate more but this is the best I can explain it as.
I'm really close to solving this! My current output is: HELLO, I’D LIKE TO ORDER A FZGH KID’S MEAL
My program didn't replace the "FZGH" with "KID'S MEAL," and I don't know why that is. I thought that by using the .replaceAll() thingy, it would replace "FZGH" with the "KID'S MEAL," but that didn't really happen. Here is my program so far:
public static void main(String[] args) {
sentences();
}
public static void sentences() {
Scanner console = new Scanner(System.in);
String sentence1 = console.nextLine();
String sentence2 = console.nextLine();
//System.out.println(sentence1 + "\n" + sentence2);
String word = sentence1.replaceAll("[FZGH]", "");
word = sentence2;
System.out.print(sentence1 + word);
}
Where did I mess up, resulting in the FZGH still appearing in output?
Use
sentence1 = sentence1.replaceAll("FZGH", "");
String word = sentence2;
Your first (and primary) problem is that you're creating a new String named word, that you're setting to the value of sentence1.replaceAll("[FZGH]", ""). You're then changing the value of word to be sentence2 immediately afterward, so the replacement is lost.
Instead, setting sentence1 to sentence1.replaceAll("FZGH", ""); will change sentence1 to no longer contain the string "FZGH", which is what you're going for. You don't actually need a word value at all, so if you'd like to remove it, it wouldn't hurt.
In addition, using [FZGH] will replace all F's, Z's, G's, and H's from the string- you should use FZGH instead, as this will only remove instances of all four letters in a row.
I think you have a couple of mistakes. Maybe the following is close...
public static void main(String[] args) {
sentences();
}
public static void sentences() {
Scanner console = new Scanner(System.in);
String sentence1 = console.nextLine();
String sentence2 = console.nextLine();
String sentence3 = sentence1+sentence2;
String final = sentence3.replaceAll("FZGH", "");
System.out.print(final);
}
You are reassigning the string "word"
in place of lines :
String word = sentence1.replaceAll("[FZGH]", "");
word = sentence2;
System.out.print(sentence1 + word);
use the following lines
sentence1 = sentence1.replaceAll("[FZGH]", "");
System.out.print(sentence1 + sentence2);
Actually replace method return a string that should be assign again to sentence1. you can run this code its works fine.
public static void main(String[] args) {
sentences();
}
public static void sentences() {
Scanner console = new Scanner(System.in);
String sentence1 = "HELLO, I’D LIKE TO ORDER A FZGH";
String sentence2 = "KID’S MEAL";
//System.out.println(sentence1 + "\n" + sentence2);
sentence1 = sentence1.replace("FZGH", "");
String word = sentence2;
System.out.print(sentence1 + word);
}

Algorithm to output the initials of a name

I have just started the java programming and at the moment I am doing the basic things. I came across a problem that I can't solve and didn't found any answers around so I thought you might give me a hand. I want to write a program to prompt the user to enter their full name (first name, second name and surname) and output their initials.
Assuming that the user always types three names and does not include any unnecessary spaces. So the input data will always look like this : Name Middlename Surname
Some of my code that I have done and stuck in there as I get number of the letter that is in the code instead of letter itself.
import java.util.*;
public class Initials
{
public static void main (String[] args)
{
//create Scanner to read in data
Scanner myKeyboard = new Scanner(System.in);
//prompt user for input – use print to leave cursor on line
System.out.print("Please enter Your full Name , Middle name And Surname: ");
String name = myKeyboard.nextLine();
String initials1 = name.substring(0, 1);
int initials2 = name.
//output Initials
System.out.println ("Initials Are " + initials1 + initials2 + initials3);
}
}
Users will enter a string like
"first middle last"
so therefore you need to get each word from the string.
Loot at split.
After you get each word of the user-entered data, you need to use a loop to get the first letter of each part of the name.
First, the nextLine Function will return the full name. First, you need to .split() the string name on a space, perhaps. This requires a correctly formatted string from the user, but I wouldn't worry about that yet.
Once you split the string, it returns an array of strings. If the user put them in correectly, you can do a for loop on the array.
StringBuilder builder = new StringBuilder(3);
for(int i = 0; i < splitStringArray.length; i++)
{
builder.append(splitStringArray[i].substring(0,1));
}
System.out.println("Initials Are " + builder.toString());
Use the String split() method. This allows you to split a String using a certain regex (for example, spliting a String by the space character). The returned value is an array holding each of the split values. See the documentation for the method.
Scanner myKeyboard = new Scanner(System.in);
System.out.print("Please enter Your full Name , Middle name And Surname: ");
String name = myKeyboard.nextLine();
String[] nameParts = name.split(" ");
char firstInitial = nameParts[0].charAt(0);
char middleInitial = nameParts[1].charAt(0);
char lastInitial = nameParts[2].charAt(0);
System.out.println ("Initials Are " + firstInitial + middleInitial + lastInitial);
Note that the above assumes the user has entered the right number of names. You'll need to do some catching or checking if you need to safeguard against the users doing "weird" things.

Categories