I am writing a program to take in a tweet as input and return a value of the unique hashtags used in the tweet. However in the countUniqueHashtags method, my hashtagCount variable will only return a value of 1 if the input contains hashtags(even if there is more than one) and a value of 0 if the input doesn't contain any hashtags.
public class UniqueHashtagCounter
{
static ArrayList<String> uniqueHashTags = new ArrayList<String>();
int numberOfTweetsToFollow;
public String tweetSpace = "";
Scanner in = new Scanner(System.in);
public int getTweetsToFollow()
{
System.out.println("Enter the number of Tweets you wish to follow: ");
numberOfTweetsToFollow = in.nextInt();
return numberOfTweetsToFollow;
}
public String tweetsInput()
{
for(int i = 0; i <= numberOfTweetsToFollow ; ++i)
{
if(in.hasNextLine()){
tweetSpace = tweetSpace + in.nextLine();
}
}
return tweetSpace;
}
public ArrayList<String> populateArray()
{
uniqueHashTags.add(tweetSpace);
for(String s: uniqueHashTags)
s.toLowerCase().split(" ");
for(int x = 0; x < uniqueHashTags.size(); x++){
countUniqueHashtags(uniqueHashTags);}
return uniqueHashTags;
}
static void countUniqueHashtags(ArrayList<String> strings)
{
int hashtagCount = uniqueHashTags.size();
ListIterator<String> listIterator = strings.listIterator();
while(listIterator.hasNext())
{
String e = listIterator.next();
if(e.startsWith("#"))
hashtagCount = hashtagCount + 1;
}
System.out.println("The number of unique hashtags is: " + hashtagCount);
}
"My hashtagCount variable will only return a value of 1 if the input contains hashtags(even if there is more than one) and a value of 0 if the input doesn't contain any hashtags"
That's because you are using startsWith():
if(e.startsWith("#"))
hashtagCount = hashtagCount + 1;
You need to loop through the string and count the hashtag characters:
for(int i=0; e.length();i++){
if(e.charAt(i)=='#') hashtagcount++;
}
Related
In this program, I want the user to type in 20 product names. from the main method. which will pass down to the method named searchProducts. But for some reason, it doesn't work. It only let me type in once, and then it prints out all 16 products.
public static void main(String[] args) {
String[] products= {"Pencil pouch", "pen", "Pencil sharpener", "High lighters", "Markers", "Erasers",
"Binder", "Notebooks", "Index cards", "Folders", "Glue", "Ruler", "Scissors", "Calculator",
"Calendar", "Backpack"};
System.out.println("Unordered list");
displayProducts(products);
sortProducts(products, 16);
System.out.println("");
System.out.println("Ordered list");
displayProducts(products);
}
private static int searchProducts(String[] products) {
Scanner sc = new Scanner(System.in);
String x = sc.nextLine();
System.out.println("Enter name of product: ");
for (int i = 0; i < products.length; i++) {
if (products[i].equals(x))
return i;
}
return -1;
}
private static void sortProducts(String products[],int n) {
for(int i = 0; i < n - 1; i++) {
int minindex = i;
String minStr = products[i];
for(int j = i + 1; j < n; j++) {
if(products[j].compareTo(minStr) < 0)
{
minStr = products[j];
minindex = j;
}
}
if(minindex != i)
{
String temp = products[minindex];
products[minindex] = products[i];
products[i] = temp;
}
}
}
private static void displayProducts(String[] products) {
for(int i = 0; i < products.length; i++){
System.out.println(products[i] + " ");
}
}
The way you pass array parameter is just good.
There are several ways to pass arrays as parameter:
(/*Other params,*/ String[] param) // this way
(String[] param /*, Other params*/) // or
(/*Other params,*/ String param[]) // this way
(String param[] /*, Other params*/) // or
// special case
// only as unique or last param of the params
// because with it you can enter several String params as individuals
(/*Other params, */ String... param)
// arrays of arrays
(String[] param[])
(String[][] param)
(String param[][] )
This is your problem:
sortProducts(products, 20);
...
private static void sortProducts(String products[],int n) {
You pass 20 although your array is 16 sized. So error.
Change this way to not depend on the size.
sortProducts(products);
....
private static void sortProducts(String products[]) { // no size passed
int n = products.length; // read the size from the array
EDIT 1 -------------
In the code below, the user to type in N products. Then the array is printed, sorted and printed. (NOT TESTED)
public static void main(String[] args) {
int N = 20;
String[] products = new String[N];
Scanner sc = new Scanner(System.in);
for(int i=0; i < N; i++) {
System.out.println("Enter name of product "+ (i+1) +" : ");
String x = sc.nextLine();
products[i] = x;
}
System.out.println("Unordered list");
displayProducts(products);
sortProducts(products);
System.out.println("");
System.out.println("Ordered list");
displayProducts(products);
// search block
}
To search in the array, you can do something like that (NOT TESTED):
public static void main(String[] args) {
// ... previous code
// search block in main method
System.out.println("Enter name of product to search, or \"stop\" to stop : ");
String y = sc.nextLine();
while(y != "stop") {
int index = searchProducts(products, y);
if( index == -1 )
System.out.println("Product "+ y +" is not in array");
else
System.out.println("Product "+ y +" is at position "+ index);
System.out.println("Enter name of product to search, or \"stop\" to stop : ");
y = sc.nextLine();
}
}
private static int searchProducts(String[] products, String p) {
for (int i = 0; i < products.length; i++) {
if (products[i].equals(p))
return i;
}
return -1;
}
I want to get the sum of integers present in the String "abc22gh20fg4". I want my output as 22+20+4=46.
I have written the code as below but it gives 22+20=44. It is not considering the number present in the very end.
public static void main(String[] args) {
String str = "abc22gh20fg4";
String num = "";
int sum = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
num = num + str.charAt(i);
} else {
if (!num.equals("")) {
sum = sum + Integer.parseInt(num);
num = "";
}
}
}
System.out.println(sum);
}
I would go with split instead of deep for loop :
String str = "abc22gh20fg4";
String regex = "[^\\d]+"; // this will extract only digit
String[] strs = str.split(regex);
int sum = Arrays.stream(strs)
.filter(digits -> digits != null && !digits.equals(""))
.mapToInt(Integer::parseInt).sum();
System.out.println(sum);
If you want before java 8
String str = "abc22gh20fg4";
String regex = "[^\\d]+";
String[] strs = str.split(regex); // this will extract only digit
int sum = 0;
for (String digits:strs) { // iterate each digits
if (digits!=null && !digits.equals("")){ // check null or empty
sum += Integer.parseInt(digits); // parse and sum
}
}
System.out.println(sum);
Update:
Your actual problem is when you loop through all the character the last character is number . it exit the loop without sum so you need to check if it is last digit sum it .
public class Test {
public static void main(String[] args) {
String str = "abc22gh20fg4";
String num = "";
int sum = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
num = num + str.charAt(i);
if (i==str.length()-1){ // check if it is last
sum = sum + Integer.parseInt(num);
}
} else {
if (!num.equals("")) {
sum = sum + Integer.parseInt(num);
num = "";
}
}
}
System.out.println(sum);
}
}
You can iterate on integer by using regex:
String str = "abc22gh20fg4";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(str);
int sum = 0;
while (m.find()) {
sum += Integer.parseInt(m.group());
}
System.out.println(sum); // Output: 46
Append this line if character is digit
sum=sum+Integer.parseInt(num); one more time just after for loop
public static void main(String[] args) {
int totalIntegerValue=0;
String currentStringValue="";
String totalStringValue="";
Scanner s = new Scanner(System.in);
String input = s.nextLine();
for(int i=0; i<input.length(); i++) {
if(Character.isDigit(input.charAt(i))) {
currentStringValue+=input.charAt(i);
totalIntegerValue+=Integer.parseInt(currentStringValue);
totalStringValue+=currentStringValue+"+";
}
else
{
currentStringValue="";
}
}
System.out.println(totalStringValue.substring(0, totalStringValue.length()-1)+"="+totalIntegerValue);
s.close();
}
I want to read an file, and want to collect top n words depends on word frequency.
I have tried the following code to count every words in a string.
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader fr = new FileReader("txtFile.txt");
BufferedReader br = new BufferedReader(fr);
String text = "";
String sz = null;
while ((sz = br.readLine()) != null) {
text = text.concat(sz);
}
String[] words = text.split(" ");
String[] uniqueLabels;
int count = 0;
System.out.println(text);
uniqueLabels = getLabels(words);
for (String l: uniqueLabels) {
if ("".equals(l) || null == l) {
break;
}
for (String s: words) {
if (l.equals(s)) {
count++;
}
}
System.out.println("Word :: " + l + " Count :: " + count);
count = 0;
}
}
And I used the following code to collect unique lbels(words) get if from link,
private static String[] getLabels(String[] keys) {
String[] uniqueKeys = new String[keys.length];
uniqueKeys[0] = keys[0];
int uniqueKeyIndex = 1;
boolean keyAlreadyExists = false;
for (int i = 1; i < keys.length; i++) {
for (int j = 0; j <= uniqueKeyIndex; j++) {
if (keys[i].equals(uniqueKeys[j])) {
keyAlreadyExists = true;
}
}
if (!keyAlreadyExists) {
uniqueKeys[uniqueKeyIndex] = keys[i];
uniqueKeyIndex++;
}
keyAlreadyExists = false;
}
return uniqueKeys;
}
And this works fine, I want to collect top 10 ranked words depend on it's frequency in file.
First of all, if you want it to run moderately fast, don't loop trough all the Strings in an array...use a HashMap... or even find some map for primitives.
Then go through the words. If the words is in the map, increment the value, otherwise put a 1.
In the end, sort the map entries and fetch the first 10.
Not a total duplicate, but this answer pretty much shows how to get the counting done: Calculating frequency of each word in a sentence in java
I recommend using a Hashmap<String, Integer>() to count the word frequency. Hash uses key-value-pairs. That means the key is unique (your word) and the value variable. If you perform a put operation with a already existing key, the value will be updated.
Hashmap
Something like this should work:
hashmap.put(key, hashmap.get(key) + 1);
To get the top then words, I would implement sort the hashmap and retrieve the first ten entries.
I solved it as,
public class wordFreq {
private static String[] w = null;
private static int[] r = null;
public static void main(String[] args){
try {
System.out.println("Enter 'n' value :: ");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
w = new String[n];
r = new int[n];
FileReader fr = new FileReader("acq.txt");
BufferedReader br = new BufferedReader(fr);
String text = "";
String sz = null;
while((sz=br.readLine())!=null){
text = text.concat(sz);
}
String[] words = text.split(" ");
String[] uniqueLabels;
int count = 0;
uniqueLabels = getUniqLabels(words);
for(int j=0; j<n; j++){
r[j] = 0;
}
for(String l: uniqueLabels)
{
if("".equals(l) || null == l)
{
break;
}
for(String s : words)
{
if(l.equals(s))
{
count++;
}
}
for(int i=0; i<n; i++){
if(count>r[i]){
r[i] = count;
w[i] = l;
break;
}
}
count=0;
}
display(n);
} catch (Exception e) {
System.err.println("ERR "+e.getMessage());
}
}
public static void display(int n){
for(int k=0; k<n; k++){
System.out.println("Label :: "+w[k]+"\tCount :: "+r[k]);
}
}
private static String[] getUniqLabels(String[] keys)
{
String[] uniqueKeys = new String[keys.length];
uniqueKeys[0] = keys[0];
int uniqueKeyIndex = 1;
boolean keyAlreadyExists = false;
for(int i=1; i<keys.length ; i++)
{
for(int j=0; j<=uniqueKeyIndex; j++)
{
if(keys[i].equals(uniqueKeys[j]))
{
keyAlreadyExists = true;
}
}
if(!keyAlreadyExists)
{
uniqueKeys[uniqueKeyIndex] = keys[i];
uniqueKeyIndex++;
}
keyAlreadyExists = false;
}
return uniqueKeys;
}
}
And the sample output is,
Enter 'n' value ::
5
Label :: computer Count :: 30
Label :: company Count :: 22
Label :: express Count :: 20
Label :: offer Count :: 16
Label :: shearson Count :: 16
After hard searchig I still haven't found the proper answer for my question and there is it:
I have to write a java program that enters an array of strings and finds in it the largest sequence of equal elements. If several sequences have the same longest length, the program should print the leftmost of them. The input strings are given as a single line, separated by a space.
For example:
if the input is: "hi yes yes yes bye",
the output should be: "yes yes yes".
And there is my source code:
public static void main(String[] args) {
System.out.println("Please enter a sequence of strings separated by spaces:");
Scanner inputStringScanner = new Scanner(System.in);
String[] strings = inputStringScanner.nextLine().split(" ");
System.out.println(String.join(" ", strings));
ArrayList<ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
ArrayList<String> stringsSequences = new ArrayList<String>();
stringsSequences.add(strings[0]);
for (int i = 1; i < strings.length; i++) {
if(strings[i].equals(strings[i - 1])) {
stringsSequences.add(strings[i]);
} else {
System.out.println(stringsSequences + " " + stringsSequences.size());
stringsSequencesCollection.add(stringsSequences);
stringsSequences.clear();
stringsSequences.add(strings[i]);
//ystem.out.println("\n" + stringsSequences);
}
if(i == strings.length - 1) {
stringsSequencesCollection.add(stringsSequences);
stringsSequences.clear();
System.out.println(stringsSequences + " " + stringsSequences.size());
}
}
System.out.println(stringsSequencesCollection.size());
System.out.println(stringsSequencesCollection.get(2).size());
System.out.println();
int maximalStringSequence = Integer.MIN_VALUE;
int index = 0;
ArrayList<String> currentStringSequence = new ArrayList<String>();
for (int i = 0; i < stringsSequencesCollection.size(); i++) {
currentStringSequence = stringsSequencesCollection.get(i);
System.out.println(stringsSequencesCollection.get(i).size());
if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
maximalStringSequence = stringsSequencesCollection.get(i).size();
index = i;
//System.out.println("\n" + index);
}
}
System.out.println(String.join(" ", stringsSequencesCollection.get(index)));
I think it should be work correct but there is a problem - the sub array list's count isn't correct: All the sub arrayList's size is 1 and for this reason the output is not correct. I don't understand what is the reason for this. If anybody can help me to fix the code I will be gratefull!
I think it is fairly straight forward just keep track of a max sequence length as you go through the array building sequences.
String input = "hi yes yes yes bye";
String sa[] = input.split(" ");
int maxseqlen = 1;
String last_sample = sa[0];
String longest_seq = last_sample;
int seqlen = 1;
String seq = last_sample;
for (int i = 1; i < sa.length; i++) {
String sample = sa[i];
if (sample.equals(last_sample)) {
seqlen++;
seq += " " + sample;
if (seqlen > maxseqlen) {
longest_seq = seq;
maxseqlen = seqlen;
}
} else {
seqlen = 1;
seq = sample;
}
last_sample = sample;
}
System.out.println("longest_seq = " + longest_seq);
Lots of issues.
First of all, when dealing with the last string of the list you are not actually printing it before clearing it. Should be:
if(i == strings.length - 1)
//...
System.out.println(stringsSequences + " " + stringsSequences.size());
stringsSequences.clear();
This is the error in the output.
Secondly, and most importantly, when you do stringsSequencesCollection.add you are adding an OBJECT, i.e. a reference to the collection. When after you do stringsSequences.clear(), you empty the collection you just added too (this is because it's not making a copy, but keeping a reference!). You can verify this by printing stringsSequencesCollection after the first loop finishes: it will contain 3 empty lists.
So how do we do this? First of all, we need a more appropriate data structure. We are going to use a Map that, for each string, contains the length of its longest sequence. Since we want to manage ties too, we'll also have another map that for each string stores the leftmost ending position of the longest sequence:
Map<String, Integer> lengths= new HashMap<>();
Map<String, Integer> indexes= new HashMap<>();
String[] split = input.split(" ");
lengths.put(split[0], 1);
indexes.put(split[0], 0);
int currentLength = 1;
int maxLength = 1;
for (int i = 1; i<split.length; i++) {
String s = split[i];
if (s.equals(split[i-1])) {
currentLength++;
}
else {
currentLength = 1;
}
int oldLength = lengths.getOrDefault(s, 0);
if (currentLength > oldLength) {
lengths.put(s, currentLength);
indexes.put(s, i);
}
maxLength = Math.max(maxLength, currentLength);
}
//At this point, youll have in lengths a map from string -> maxSeqLengt, and in indexes a map from string -> indexes for the leftmost ending index of the longest sequence. Now we need to reason on those!
Now we can just scan for the strings with the longest sequences:
//Find all strings with equal maximal length sequences
Set<String> longestStrings = new HashSet<>();
for (Map.Entry<String, Integer> e: lengths.entrySet()) {
if (e.value == maxLength) {
longestStrings.add(e.key);
}
}
//Of those, search the one with minimal index
int minIndex = input.length();
String bestString = null;
for (String s: longestStrings) {
int index = indexes.get(s);
if (index < minIndex) {
bestString = s;
}
}
System.out.println(bestString);
Below code results in output as you expected:
public static void main(String[] args) {
System.out.println("Please enter a sequence of strings separated by spaces:");
Scanner inputStringScanner = new Scanner(System.in);
String[] strings = inputStringScanner.nextLine().split(" ");
System.out.println(String.join(" ", strings));
List <ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
List <String> stringsSequences = new ArrayList<String>();
//stringsSequences.add(strings[0]);
boolean flag = false;
for (int i = 1; i < strings.length; i++) {
if(strings[i].equals(strings[i - 1])) {
if(flag == false){
stringsSequences.add(strings[i]);
flag= true;
}
stringsSequences.add(strings[i]);
}
}
int maximalStringSequence = Integer.MIN_VALUE;
int index = 0;
List <String> currentStringSequence = new ArrayList<String>();
for (int i = 0; i < stringsSequencesCollection.size(); i++) {
currentStringSequence = stringsSequencesCollection.get(i);
System.out.println(stringsSequencesCollection.get(i).size());
if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
maximalStringSequence = stringsSequencesCollection.get(i).size();
index = i;
//System.out.println("\n" + index);
}
}
System.out.println(stringsSequences.toString());
i was wondering how can i create a method where i can get the single instance from a string and give it a numericValue for example, if theres a String a = "Hello what the hell" there are 4 l characters and i want to give a substring from the String a which is Hello and give it numeric values. Right now in my program it gets all the character instances from string so the substring hello would get number values from the substring hell too because it also has the same characters.
my code :
public class Puzzle {
private static char[] letters = {'a','b','c','d','e','f','g','h','i', 'j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z'};
private static String input;
private static String delimiters = "\\s+|\\+|//+|=";
public static void main(String[]args)
{
input = "help + me = please";
System.out.println(putValues(input));
}
//method to put numeric values for substring from input
#SuppressWarnings("static-access")
public static long putValues(String input)
{
Integer count;
long answer = 0;
String first="";
String second = "";
StringBuffer sb = new StringBuffer(input);
int wordCounter = Countwords();
String[] words = countLetters();
System.out.println(input);
if(input.isEmpty())
{
System.out.println("Sisestage mingi s6na");
}
if(wordCounter == -1 ||countLetters().length < 1){
return -1;
}
for(Character s : input.toCharArray())
{
for(Character c : letters)
{
if(s.equals(c))
{
count = c.getNumericValue(c) - 9;
System.out.print(s.toUpperCase(s) +"="+ count + ", ");
}
}
if(words[0].contains(s.toString()))
{
count = s.getNumericValue(s);
//System.out.println(count);
first += count.toString();
}
if(words[3].contains(s.toString())){
count = s.getNumericValue(s);
second += count.toString();
}
}
try {
answer = Long.parseLong(first)+ Long.parseLong(second);
} catch(NumberFormatException ex)
{
System.out.println(ex);
}
System.out.println("\n" + first + " + " + second + " = " + answer);
return answer;
}
public static int Countwords()
{
String[] countWords = input.split(" ");
int counter = countWords.length - 2;
if(counter == 0) {
System.out.println("Sisend puudu!");
return -1;
}
if(counter > 1 && counter < 3) {
System.out.println("3 sõna peab olema");
return -1;
}
if(counter > 3) {
System.out.println("3 sõna max!");
return -1;
}
return counter;
}
//method which splits input String and returns it as an Array so i can put numeric values after in the
//putValue method
public static String[] countLetters()
{
int counter = 0;
String[] words = input.split(delimiters);
for(int i = 0; i < words.length;i++) {
counter = words[i].length();
if(words[i].length() > 18) {
System.out.println("One word can only be less than 18 chars");
}
}
return words;
}
Program has to solve the word puzzles where you have to guess which digit corresponds to which letter to make a given equality valid. Each letter must correspond to a different decimal digit, and leading zeros are not allowed in the numbers.
For example, the puzzle SEND+MORE=MONEY has exactly one solution: S=9, E=5, N=6, D=7, M=1, O=0, R=8, Y=2, giving 9567+1085=10652.
import java.util.ArrayList;
public class main {
private static String ChangeString;
private static String[] ArrayA;
private static String a;
private static int wordnumber;
private static String temp;
public static void main(String[] args) {
// TODO Auto-generated method stub
a = "hello what the hell";
wordnumber = 0;
identifyint(a,wordnumber);
}
public static void identifyint (String a, int WhichWord){
ChangeString = a.split(" ")[WhichWord];
ArrayA = a.split(" ");
replaceword();
ArrayA[wordnumber] = ChangeString;
//System.out.print(ArrayA[wordnumber]);
a = "";
for(int i = 0; i<ArrayA.length;i++){
if(i==wordnumber){
a = a.concat(temp+ " ");
}
else{
a = a.concat(ArrayA[i]+" ");
}
}
System.out.print(a);
}
public static void replaceword(){
temp = "";
Character arr[] = new Character[ChangeString.length()];
for(int i = 0; i<ChangeString.length();i++){
arr[i] = ChangeString.charAt(i);
Integer k = arr[i].getNumericValue(arr[i])-9;
temp = temp.concat(""+k);
}
a = temp;
}
}
Change wordnumber to the word you want to replace each time. If this is not what you have asked for, please explain your question in more detail.