How do I extract words from a string? - java

I did some research and I could only find answers for search results. I am trying to extract a word from a String and adding a word from another String, replacing the one that was removed. Each situation is different, so I can't make it a constant. I'd really appreciate the help!
package rudolph;
import javax.swing.JOptionPane;
public class IfBlankWasBlank {
public static void main(String[] args) {
String charInput = "";
String thing = "";
String pun = "";
charInput = JOptionPane.showInputDialog(null,
"Enter the person or thing you'd like to make fun of:");
thing = JOptionPane.showInputDialog(null,
"Enter the thing that " + charInput +" is doing:");
pun = JOptionPane.showInputDialog(null,
"Enter the pun that " + charInput + " is doing:");
String msg = "If " + charInput + " was " + thing + ", then they'd be " + pun + ".";
JOptionPane.showMessageDialog(null, msg);
}
}
So if I enter in Rudolph the Red Nosed Reindeer in the CharInput String, energy efficient in the thing String, and LED in the pun String, I want the msg to be "If Rudolph the Red Nosed Reindeer was energy efficient, then they'd be Rudolph the LED Nosed Reindeer."
I know it's silly, but I'd like to know how to utilize it If I could! Thanks so much for the help!

you should use string split method.String#split()

Related

Find Word Count"- My code doesn't work properly

"Find Word Count"- Instructions:
Given an input string (assume it's essentially a paragraph of text) and a
word to find, return the number of times in the input string that the word is
found. Should be case agnostic and remove space, commas, full stops, quotes, tabs etc while finding the matching word.
=======================
My code doesn't work properly.
`
String input = " It can hardly be a coincidence that no language on" +
" Earth has ever produced the expression as pretty as an airport." +
" Airports are ugly. Some are very ugly. Some attain a degree of ugliness" +
" that can only be the result of a special effort. This ugliness arises " +
"because airports are full of people who are tired, cross, and have just " +
"discovered that their luggage has landed in Murmansk (Murmansk airport " +
"is the only known exception to this otherwise infallible rule), and architects" +
" have on the whole tried to reflect this in their designs. They have sought" +
" to highlight the tiredness and crossness motif with brutal shapes and nerve" +
" jangling colors, to make effortless the business of separating the traveller" +
" for ever from his or her luggage or loved ones, to confuse the traveller with" +
" arrows that appear to point at the windows, distant tie racks, or the current " +
"position of Ursa Minor in the night sky, and wherever possible to expose the " +
"plumbing on the grounds that it is functional, and conceal the location of the" +
"departure gates, presumably on the grounds that they are not.";
input = input.toLowerCase();
String whichWord = "be";
whichWord = whichWord.toLowerCase();
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = input.indexOf(whichWord,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += whichWord.length();
}
}
System.out.println(count);
`
In your code you are not checking complete word. So, its matching both 'be' and 'because'. You're checking if there are any sub-strings contains the word 'be'. Could you please try below solution using regex? It will solve your purpose:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WordCount {
public static void main(String[] args) {
String input = " It can hardly be a coincidence that no language on" +
" Earth has ever produced the expression as pretty as an airport." +
" Airports are ugly. Some are very ugly. Some attain a degree of ugliness" +
" that can only be the result of a special effort. This ugliness arises " +
"because airports are full of people who are tired, cross, and have just " +
"discovered that their luggage has landed in Murmansk (Murmansk airport " +
"is the only known exception to this otherwise infallible rule), and architects" +
" have on the whole tried to reflect this in their designs. They have sought" +
" to highlight the tiredness and crossness motif with brutal shapes and nerve" +
" jangling colors, to make effortless the business of separating the traveller" +
" for ever from his or her luggage or loved ones, to confuse the traveller with" +
" arrows that appear to point at the windows, distant tie racks, or the current " +
"position of Ursa Minor in the night sky, and wherever possible to expose the " +
"plumbing on the grounds that it is functional, and conceal the location of the" +
"departure gates, presumably on the grounds that they are not.";
input = input.toLowerCase();
String whichWord = "be";
whichWord = whichWord.toLowerCase();
int count = 0;
String regex = "(\\W|^)" + whichWord + "(\\W|$)";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
while(matcher.find()) {
count++;
}
System.out.println(count);
}
}

Is there an alternative way to generate quote marks without using the escape sequence?

I am trying to get my output to display double quotations around the abbreviations and also the translated abbreviations. However I have not covered escape sequences in my current class so I was wondering if there was another way to accomplish this. The workbook will not accept when I try with escape sequence.
I have tried escape sequence and using two single quotes ('' '') but neither have worked. Perhaps I am missing something and am fairly new to the java language. Just trying to learn the most efficient way from a fundamental standpoint.
import java.util.Scanner;
public class TextMsgExpander {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String txtMsg;
String BFF = "best friend forever";
String IDK = "I don't know";
String JK = "just kidding";
String TMI = "too much information";
String TTYL = "talk to you later";
System.out.println("Enter text: ");
txtMsg = scnr.nextLine();
System.out.println("You entered: " + txtMsg);
System.out.println();
if(txtMsg.contains("BFF")) {
txtMsg = txtMsg.replace("BFF", BFF);
System.out.println("Replaced BFF with " + BFF);
} // above line is where I tried escape sequence
if(txtMsg.contains("IDK")) {
txtMsg = txtMsg.replace("IDK", IDK);
System.out.println("Replaced IDK with " + IDK);
}
if(txtMsg.contains("JK")) {
txtMsg = txtMsg.replace("JK", JK);
System.out.println("Replaced JK with " + JK);
}
System.out.println();
System.out.println("Expanded: " + txtMsg);
return;
}
}
Your output
Enter text:
You entered: IDK how that happened. TTYL.
Replaced IDK with I don't know
Replaced TTYL with talk to you later
Expanded: I don't know how that happened. talk to you later.
Expected output
Enter text:
You entered: IDK how that happened. TTYL.
Replaced "IDK" with "I don't know".
Replaced "TTYL" with "talk to you later".
Expanded: I don't know how that happened. talk to you later.
Have you tried this:
\"example text\"
So you would have something like this:
System.out.println("Replaced \"BFF\" with " + "\"" + BFF + "\"");
or
System.out.println("Replaced \"BFF\" with \"" + BFF + "\"");
Normally it should work with escape characters.
Have u tried something like this:
System.out.println("\"These two semi colons are removed when i am printed\"");
I tested it and it worked for me.
If you cannot use \ escape sequences, for whatever reason, you can use the fact that an ' apostrophe doesn't need to be escaped in a "xx" string literal, and that a " double-quote doesn't need to be escaped in a 'x' character literal.
E.g. to print Replacing "foo" with 'bar' was easy, and foo and bar are from variables, you can do this:
String s = "Replacing " + '"' + foo + '"' + " with '" + bar + "' was easy"`;

2nd JOptionPane won't come up

I'm just starting out with Java and programming in general. Could someone please explain to me why the second dialog box won't show up after I've entered the information for the first one?
Thanks!
// Java Practice
import javax.swing.JOptionPane;
import java.util.Scanner;
public class DialogTest
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String firstname;
String lastname;
int age;
JOptionPane.showInputDialog("What is " +
"your first name?");
firstname = keyboard.nextLine();
JOptionPane.showInputDialog("What is " +
"your last name?");
lastname = keyboard.nextLine();
JOptionPane.showInputDialog("How old are you?");
age = keyboard.nextInt();
JOptionPane.showMessageDialog(null, "I see, so your name is: " + firstname + lastname + " and you are" + age + " years old.");
System.exit(0);
}
}
JOptionPane.showInputDialog() returns a String that contains the value entered by the user. Instead of using the Scanner class, store the return value of the method call into your variables:
String firstname, lastname, age;
firstname = JOptionPane.showInputDialog("What is " +
"your first name?");
lastname = JOptionPane.showInputDialog("What is " +
"your last name?");
age = JOptionPane.showInputDialog("How old are you?");
JOptionPane.showMessageDialog(null, "I see, so your name is: " + firstname + lastname + " and you are" + age + " years old.");
You don't need both JOptionPane and Scanner. You only need one (I highly recommend Scanner over the other).
What's happening is this: The call to JOptionPane is opening a dialog for your user to enter a value. That value is returned by this method call, which you do nothing with. Then after the dialog is finished, you call keyboard.nextLine() which blocks the program until the user enters another value into the command line window (or your IDE if you're running it through that).
If you want to see both options available to you, try commenting out the keyboard lines and setting firstname = JOptionPane... and so on. Once you've tried out that program, do the opposite: comment out the JOptionPane calls and replace them with System.out.println calls.
As someone who began learning input handling via JOptionPane, I believe Scanner is a much better utility.

Split String using split method

I have one String text that i would like to split,result i want to get is that when i take text/split output each part like for example: Name: John, Last Name: Davidson, Date of Birth: 05051968, Place of Birth: London. But i am not getting correct result. my code is following:
public class Person{
public String name;
public String lastName;
public String dateOfBirth;
public String placeOfBirth;
poblic void printDetails(){
String text = "John.Davidson/0505168/London Micheal.Bartson/06061680/Paris";
String[] newText = text.split("[./ ]");
for(int i=0; i<newText.length; i++){
String name = newText[i].split("")[0];
String lastName = newText[i].split("")[0];
String dateOfBirth = newText[i].split("")[0];
String placeOfBirth = newText[i].split("")[0];
System.out.println("Name: " + name + ", last name: " + lastName + ", date of birth: " + dateOfBirth + ", place of birth: " + placeOfBirth);
}
Result i am getting is following:
Name: J, last Name: J, date of birth: J, place of birth: J
Name: D, last name: D, date of birth: D, place of birth: D .......
and it goes like that for every first character in text. Please can some one look and tell me where i am mistaking?
The results of the split come in groups of four, so you need to set the step of your loop at 4, and get the individual parts through offsets 0, 1, 2, and 3, like this:
for(int i=0; i<newText.length; i+=4){
String name = newText[i];
String lastName = newText[i+1];
String dateOfBirth = newText[i+2];
String placeOfBirth = newText[i+3];
System.out.println("Name: " + name + ", last name: " + lastName + ", date of birth: " + dateOfBirth + ", place of birth: " + placeOfBirth);
}
Demo.
You're splitting using the "" which means split every character. Then you take the first character. I don't know why you're doing it that way.
In summary, what happens in every loop is it takes the first character ([0]) of element i of the array, then sets every single value that wil lbe printed in the string to that character. Instead, try this
String[] newText = text.split("[./ ]");
for(int i = 0; i < newText.length - 4; i+=4){
System.out.println("Name: " + newText[i] + ", last name: " + newText[i+1] + ", date of birth: " + newText[i+2] + ", place of birth: " + newText[i+3]);
}
However, this is a terrible solution, it relies on fixed sized entries and should not be used in practice. What if someone enters the string in a different order, or with one too many inputs or one too few? Try using more flexible designs, such as the usage of a csv format parser, so you always split using commas, and the rows can be something like
entry-type, entry
entry-type, entry2
entry-type, entry3
Or something like that. Try it out. Always try to aim for flexible solutions that don't rely on exact input to work, otherwise you will have exceptions and runtime issues like there's no tomorrow.
PS the point of the split() method is to split the string between occurences of the specified input, i.e. [./], so don't use it if you want to just give a "", that's no different than making a charArray (except instead of char[] it is String[])

How to use JOptionPane to display info

I need some help writing a program
Using this code I am able to enter in a track name, artist, etc.
I have a problem that I cannot now show this information in JOptionPane to display all of my info
import java.util.Scanner;
import javax.swing.JOptionPane;
public class TestTrack
{
public static void main(String[] args)
{
Scanner myScan = new Scanner(System.in);
System.out.println("Track name");
String name = myScan.nextLine();
System.out.println("Artist");
String Artist = myScan.nextLine();
System.out.println("Track length seconds");
String seconds = myScan.nextLine();
System.out.println("Album");
String Album = myScan.nextLine();
JOptionPane.showMessageDialog(null,"Trackinfo:")
}
}
So I guess I would want the pop out window to say
Track Name: "blank"
Artist: blank
Another question I have is how to ask this question multiple times by using "while" and asking if I would like to add another track
Sorry if I am using any terminology incorrectly I just started to learn Java
This line: JOptionPane.showMessageDialog(null,"Trackinfo:")
Contains what the pop-up window will contain. You pass in what you want its contents to be as the 2nd parameter, which is currently "Trackinfo".
To incorporate a while loop, you'll have to have a loop control variable, or a condition that will break the loop. In my example I used a string. My example uses a while loop that will continue as long as the string is not equal to "quit".
String test = "";
while( ! test.equals("quit") ) {
//use Scanner to get the next value the user enters
//ask for track info
//display that info in a message box
}
To obtain this:
Note: the texts of the OK and Cancel buttons are localized, if your computer is set to US locale you doesn't see 'Annuler"... ;-)
code this:
int answer = 0;
do {
/*----------------------------------------------------------------------------
Here you put the code which set the variables name, artist, seconds... (1)
----------------------------------------------------------------------------*/
final String title = "Track info";
final String message =
"<html><table>" +
"<tr><td>Track name" + "</td><td>" + name + "</td></tr>" +
"<tr><td>Artist" + "</td><td>" + artist + "</td></tr>" +
"<tr><td>Track length seconds</td><td>" + seconds + "</td></tr>" +
"<tr><td>Album" + "</td><td>" + album + "</td></tr>" +
"</table>";
answer =
JOptionPane.showConfirmDialog(
null, message, title, JOptionPane.OK_CANCEL_OPTION );
} while( answer == JOptionPane.OK_OPTION );
(1) You may choose Scanner or GUI whith JOptionPane.showInputDialog()
JOptionPane.showMessageDialog(null,"Trackinfo:" + "\nArtist: " + Artist + "\nseconds: " + seconds + "\nAlbum: " + Album)
Each '\n' means a new line. for doing this multiple times, you should place your code in a while loop, something like this:
while(!(Artist == "end")) {
//your code
}
Use myScan.next() instead of myScan.nextLine()
To output the information into the Message Dialog, use
String trackInfo = "Track Name: " + name + " | Artist : " +artist+ " | Track Length: " + seconds + " | Album: " + album;
JOptionPane.showMessageDialog(null, trackInfo, "Trackinfo", JOptionPane.INFORMATION_MESSAGE);

Categories

Resources