I am trying to find the number of unique hashtags in a tweet inputted by a user. for example, if someone inputs "#one #seven #one purple green #red", it would show 3 unique hashtags that would be "#one, #seven, #red". In my code, I can do that to one tweet, but I cannot figure out how to input multiple tweets and find all the unique hashtags from them.
package edu.bsu.cs121.jmgibson;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Tweet {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a tweet");
String tweet = scanner.nextLine();
Set<String> hashtags = getHashtags(tweet);
System.out.println(hashtags.toString());
}
public static Set<String> getHashtags(String tweet) {
String[] words = tweet.split(" ");
Set<String> hashtags = new HashSet<String>();
for (String word : words) {
if (word.startsWith("#")) {
hashtags.add(word);
}
}
return hashtags;
}
}
I don't want to do your homework for you, but I'll offer some suggestions:
In main(), you'll need a loop that asks for input and makes calls
to getHashtags().
Instead of creating a new HashSet inside of getHashtags(),
create one in main() (outside of the loop), and pass it in.
1.loop and get many tweet inputs
something like
for(int i=0;i<100;i++)
{
System.out.println("Please enter a tweet");
String tweet[i] = scanner.nextLine();
}
2.pass the tweetstring array instead of passing tweet string
3.loop through tweet array line by line and add tag if and only if not already added
public static Set<String> getHashtags(String[] tweet) {
Set<String> hashtags = new HashSet<String>();
//loop of tweet array starts
String[] words = tweet[i].split(" ");//i is loop variable
for (String word : words) {
if (word.startsWith("#")) {
//here add condition to check if hashings already doesnt have the word
hashtags.add(word);
}
}
}
//loop ends
return hashtags;
You need a loop in your main to gather multiple inputs.
I would gather your inputs into one string in order to work with your already defined getHashtags.
Something like this...
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a tweet");
String tweet = "";
while(!scanner.nextLine().equals("stop")){
tweet += scanner.nextLine();
}
Set<String> hashtags = getHashtags(tweet);
System.out.println(hashtags.toString());
}
So a loop and a += should do the trick.
Related
I'm trying to create a menu page that allows addition to the array, output of the array and to search by name. I'm struggling with the search part, as it is a multi-dimensional array. How do I search just the names part of each object?
I'm also not sure how to loop this so that they return to the main page after each request, and therefore the array remains updated with any new editions.
package qa.com.task;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import qa.com.task.Person;
public class Runner {
public static void main(String[] args) {
Person pp1 = new Person("Karen", 27, "DevOps Engineer");
Person pp2 = new Person("Jim", 24, "Software Engineer");
// Create array
ArrayList<Person> people = new ArrayList<Person>();
people.add(pp1);
people.add(pp2);
// Search array
Scanner scan = new Scanner(System.in);
System.out.println("---------------------MENU---------------------");
System.out.println("------Create--------Search-------Output All---");
System.out.println("------type c--------type s---------type o-----");
String request = scan.nextLine();
if (request.contains("c")){
//CREATE NEW PERSON
System.out.println("----------Create Request: Enter Name----------");
String newname = scan.nextLine();
System.out.println("-------------------Enter Age-------------------");
Integer newage = scan.nextInt();
scan.nextLine();
System.out.println("-------------------Job Title-------------------");
String newjobtitle = scan.nextLine();
Person ppnew = new Person(newname, newage, newjobtitle);
people.add(ppnew);
System.out.println("-----Updated Array with New Creation Request----");
System.out.println(Arrays.toString(people.toArray()));
}
if (request.contains("s")){
//SEARCH
System.out.println("----------Search Request: Enter Name----------");
String searchname = scan.nextLine();
}
if (request.contains("o")){
//OUTPUT DATABASE
System.out.println("----------------Output Request:----------------");
System.out.println(Arrays.toString(people.toArray()));
}
}}
You can filter your people list based on a person name.
List<Person> filteredPeople = people.stream()
.filter(person -> person.getName().contains(searchname)) // Filter condition
.collect(Collectors.toList()); // Get the result as list
Then you can do what you want with filteredPeople.
Otherwise you can use a traditional for loop to iterate over the list and "print" Persons who match the condition, something like below.
List<Person> people...;
boolean stop = false;
while(!stop) {
// print menu (with exit command)
// handle commands and if exit command, set stop = true.
}
I am trying to find an array in a two dimensional array using a string input from the user. But, I keep getting the "String[][] cannot be converted to to String" error. Can I do this with a keyboard scanner and strings or is there a more logical solution to this problem.
import java.util.Scanner;
public class QandA{
public static void main(String[] args){
String entry;
String[] Why = new String[]{"Because.", "Just Because.", "Why yourself."};
String[][] Questions = new String[][] { Why };
Scanner k = new Scanner(System.in);
entry = k.next();
for (int i=0 ; i < Questions.length ; i++){
if (entry.equalsIgnoreCase(Questions)){
System.out.println("Test");
break;
}
if (i == Questions.length){
if (!entry.equalsIgnoreCase(Questions)){
System.out.println("Test2");
}
}
}
}
}
EDIT:
I have changed my 2D array into a hashmap but am getting a "cannot find symbol, class Hashmap" even after importing java.util.HashMap; Help? [FIXED]
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.*;
public class QandA{
public static void main(String[] args){
String UE;
String[] Why = new String[]{"Because.", "Just Because.", "Why yourself."};
Map<String, String[]> Questions = new HashMap<>();
Questions.put("Why", Why);
Scanner k = new Scanner(System.in);
UE = k.next();
if(Questions.keySet().stream().filter(UE::equalsIgnoreCase).findFirst().isPresent()) {
System.out.println("Test");
} else {
System.out.println("Test2");
}
}
}
First you need to use a Map (instead of a String[][]) to map the name of the array variable to its instance:
String[] Why = new String[]{"Because.", "Just Because.", "Why yourself."};
Map<String, String[]> Questions = new HashMap<>();
Questions.put("Why", Why);
Next, you can perform the Test / Test2 check in many ways. Here is one way:
if(Questions.keySet().stream().filter(entry::equalsIgnoreCase).findAny().isPresent()) {
System.out.println("Test");
} else {
System.out.println("Test2");
}
As a side note, your variable names are very misleading. "Entry" has a different meaning in the context of maps, since it encapsulates a Key+Value Pair. You should use meaningful variable names and conform to existing Java conventions regarding case, etc.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
private static String[] nameArray;
public static void newPerson() {
Scanner scanner = new Scanner(System.in);
System.out.print("Name: ");
name = scanner.nextLine();
nameArray = new String[] {
name
};
}
public static void personInfo() {
System.out.print("Current Persons : \n");
StringBuilder arrayOutput = new StringBuilder();
for (String something: nameArray) {
arrayOutput.append(something);
}
String text = arrayOutput.toString();
System.out.println(text);
}
Hello all thanks in advance for your help I m having a problem I have a loop that call a method once a number is entered in that method is this:
So my question whenever I call the newPerson method and enter a name instead of having all the names stored and in the array and later printed, the personInfo method only prints the final name that I enter in the array why is it not displaying all the names?
You're replacing the nameArray entirely after each input. You have to add it to your array. But it is easier to use 'ArrayList's in this case.
Building on your provided code:
private static ArrayList<String> nameArray = new ArrayList<>();
public static void newPerson() {
Scanner scanner = new Scanner(System.in);
System.out.print("Name: ");
name = scanner.nextLine();
nameArray.add(name);
}
public static void personInfo() {
System.out.print("Current Persons : \n");
StringBuilder arrayOutput = new StringBuilder();
for ( String something : nameArray) {
arrayOutput.append(something);
}
String text = arrayOutput.toString();
System.out.println(text);
}
every time you are creating new string array with one element
nameArray = new String[]{name};
so the latest one will be preserved which is your last element. So make sure that you are appending your names to nameArray.
Better to use ArrayList if you are not sure the eventual size of the array.
private static List<String> nameList = new ArrayList<String>();
public static void newPerson() {
Scanner scanner = new Scanner(System.in);
System.out.print("Name: ");
nameList.add(scanner.nextLine());
}
public static void personInfo() {
System.out.print("Current Persons : \n");
StringBuilder arrayOutput = new StringBuilder();
for (String something: nameList) {
arrayOutput.append(something);
}
String text = arrayOutput.toString();
System.out.println(text);
}
You can still do it using array but you have to do lot of work during adding new element into array, probably you will need maintain the index for next insertion, provide initial size of array and in case it overflows then resize the array.
When you do
nameArray = new String[]{name};
you are overriding the contents of nameArray, thus losing all previously saved names. new String[]{name} creates a new String array.
Use a list of String instead of an array and just add the new names to it.
// use List<String> instead of String[]
private static List<String> names = new ArrayList<String>();
public static void newPerson() {
Scanner scanner = new Scanner(System.in);
System.out.print("Name: ");
name = scanner.nextLine();
// add new names to list, old names will not be deleted
names.add(name);
}
public static void personInfo() {
System.out.print("Current Persons : \n");
StringBuilder arrayOutput = new StringBuilder();
for(String something : names) {
arrayOutput.append(something);
}
String text = arrayOutput.toString();
System.out.println(text);
}
You are creating and replacing an existing every time you take input from user . Replace that add input in a list .
For an assignment I have to sort an ArrayList in alphabetical order and print it without using java.util.Collections, meaning I have to come up with my own algorithm to put it in ABC order. I haven't been able to figure it out on my own and everyone online uses Collections. Any help?
My code is not really needed to answer my question, but nevertheless here it is:
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
import java.util.ArrayList;
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
ArrayList <String> word = new ArrayList <String> ();
System.out.println("Enter the next name:");
String str = input.nextLine();
String compared = "STOP";
while (!compared.equalsIgnoreCase(str))
{
String action = str.toLowerCase();
action = str.substring(0,1).toUpperCase()+str.substring(1).toLowerCase();
word.add(action);
System.out.println("Enter the next name:");
str = input.nextLine();
}
System.out.println(word);
}
}
Thank you.
I'm messing around trying to learn to use HashSets to remove duplicate elements in my output but I'm running into some trouble.
My goal is to select a text file when the program is run and for it to display the words of the text file without duplicates, punctuation, or capital letters. All of it works fine except for removing the duplicates.
This is my first time using a Set like this. Any suggestions as to what I'm missing? Thanks!
Partial text file input for example: "Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation, so conceived and so dedicated, can long endure"
import java.util.Scanner;
import java.util.List;
import java.io.*;
import java.util.*;
import javax.swing.JFileChooser;
public class Lab7 {
public interface OrderedList<T extends Comparable<T>> extends Iterable<T>
{
public void add(T element);
public T removeFront();
public T removeRear();
public int size();
public boolean isEmpty();
public boolean contains(T element);
public Iterator<T> iterator();
}
public static void main(String[] arg) throws FileNotFoundException
{
Scanner scan = null;
JFileChooser chooser = new JFileChooser("../Text");
int returnValue = chooser.showOpenDialog(null);
if( returnValue == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
scan = new Scanner(file);
}
else
return;
int count = 0;
Set<String> set = new LinkedHashSet<String>();
while(scan.hasNext())
{
String[] noDuplicate = {scan.next().replaceAll("[\\W]", "").toLowerCase()};
List<String> list = Arrays.asList(noDuplicate);
set.addAll(list);
count++;
}
scan.close();
System.out.println(set);
System.out.println();
System.out.println(chooser.getName() + " has " + count + " words.");
}
}
Your problem is that you are creating a new HashSet every time you read a word using the Scanner, so there is no chance for it to do de-duplication. You can fix it with the following steps. Also, normal HashSet does not retain ordering.
Create the HashSet once, before the Scanner loop.
Use a LinkedHashSet, so that order is preserved in the same order that you added it.
Inside the loop, use set.add(item);. As the other answer mentions, you do not need to create a one-element list.
Adding the code for completeness.
public static void main(String[] arg) throws FileNotFoundException
{
Scanner scan = null;
scan = new Scanner(new File("Input.txt"));
int count = 0;
Set<String> set = new LinkedHashSet<String>();
while(scan.hasNext())
{
String word = scan.next().replaceAll("[\\W]", "").toLowerCase();
set.add(word);
count++;
}
scan.close();
// System.out.println(set);
System.out.println();
System.out.println("Input.txt has " + count + " words.");
// How do I print a set by myself?
for (String word : set) {
// Also remove commas
System.out.println(word.replaceAll(",",""));
}
}
I would do it this way:
Set<String> set = new LinkedHashSet<String>();
while(scan.hasNext())
{
String noDuplicate = scan.next().replaceAll("[\\W]", "").toLowerCase();
set.add(noDuplicate);
}
scan.close();
System.out.println("The text has " + set.size() + " unique words.");
Your solution (Creating a one element array, converting that to a List, and converting that to a HashSet) is extremely inefficient, in addition to being incorrect. Just use the String you're originally working with, and add it to the LinkedHashSet (which will preserve ordering). At the end set.size() will show you the number of unique words in your sentence.