需要帮助将字符串添加到数组列表,直到使用循环输入**。然后在数组列表中搜索具有特定#tag的字符串,并将它们添加到另一个数组列表并打印它们。
import java.io.*;
import java.util.*;
public class Program
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while ()
System.out.println ("Enter a tweet");
String Tweet = sc.nextLine();
System.out.println("Enter a hashtag");
String hashtag = sc.nextLine();
ArrayList<String> ListOfTweets = new ArrayList<>();
ArrayList<String> TweetsWithTag = new ArrayList<>();
if ((Tweet.contains(hashtag)) == true)
TweetsWithTag.add (Tweet);
}
public static boolean searchTweet (String Tweet, String hashtag) {
return (Tweet.contains(hashtag));
}
}
答案 0 :(得分:1)
将其细分为更小的部分,然后继续努力。
首先,收到你的推文:
String tweet = sc.nextLine();
将此添加到您的List
:
listOfTweets.add(tweet);
环绕这个;我建议do...while
。阅读该链接,但请注意do...while input is not equal to **
然后,当循环完成后,得到你的推文:
String hashtag = sc.next();
请注意,我使用sc.next()
作为推文是一个单词(或者更确切地说,没有空格)。
然后,如果推文包含您的主题标签,则重复您的List
搜索,然后将其返回。如果用户将实际#
添加到主题标签的开头,您可能需要查看substring
。甚至是startswith
方法。
您可以在类似于推文标签的循环中围绕主题标签部分,让他们搜索不同的推文。
答案 1 :(得分:0)
您可以尝试这样的代码段
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class HelloWorld{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> listOfTweets = new ArrayList<>();
ArrayList<String> tweetsWithTag = new ArrayList<>();
while (true){
System.out.println ("Enter a tweet");
String tweet = sc.nextLine();
if (tweet.equals("**"))break;
listOfTweets.add(tweet);
}
System.out.println("Enter a hashtag");
String hashtag = sc.nextLine();
for(String tweet:listOfTweets){
if (tweet.contains(hashtag)){
tweetsWithTag.add (tweet);
}
}
System.out.println("Tweets:" +listOfTweets);
System.out.println("Tweets with #"+hashtag+": "+tweetsWithTag);
}
答案 2 :(得分:0)
你已经拥有了点点滴滴。只需要重新安排你的代码。
//move the lists up to before the loop, so they do not get replaced
//each time
ArrayList<String> ListOfTweets = new ArrayList<>();
Scanner sc = new Scanner(System.in);
boolean userWantsToExit = false; //you use this to check for exit condition.
do{ //your loop begins here...
System.out.println ("Enter a tweet (or ** to exit)");
String Tweet = sc.nextLine();
if(Tweet.equals("**"){
userWantsToExit =true;
}else {
ListOfTweets.add(Tweet);
}
} while( ! userWantsToExit ); //keep repeating until ** is entered
System.out.println("Enter a hashtag");
String hashtag = sc.nextLine();
List<String> TweetsWithTag =
ListOfTweets.stream().filter( tweet -> tweet.contains(hashtag))
.collect(Collectors.toList());
//to print them just call
System.out.println("list of tweets:");
ListOfTweets(System.out::println);
System.out.println("list of tweets with hash tag:");
TweetsWithTag.forEach(System.out::println);