How to add character amounts in an array? - java

So I have an array of strings and need to take the amount of characters in each string and add them together to get 1 total. How would I go about doing this?
Here is the array:
public class Final21 {
public static String getLongString(String[] array) {
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
}
}
I am not adding indexes, but the amount of characters in each string.
Example: bob has 3 characters, tomtomjack has 10 characters, if you add them it would be 13
Attempts:
public static int countAllLetters(String[] array) {
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
int sum = 0;
for(String s : array)
sum += s.length();
return sum;
int amountOfLetters = countAllLetters(names);
System.out.println(amountOfLetters);
}
Gives error:
Final21.java:62: error: unreachable statement
int amountOfLetters = countAllLetters(names);
^
Final21.java:65: error: missing return statement
}
^
2 errors

Using the stream API, it can be done as follows:
int sum = Arrays.stream(names)
.mapToInt(String::length)
.sum();

For a Java 8+ solution, refer to this answer by Aominè.
In the comments, you say you can't use Java 8. This answer exposes a solution for pre-Java 8 environments.
If you want to return an int containing the combined amount of characters from every String in the array, you need to change the return type of your method.
public static int countAllLetters(String[] array)
Notice how I changed the name to better express the behavior of this method.
To implement it, simply loop through the array and add together the length() of each String:
public static int countAllLetters(String[] array) {
int sum = 0;
for(String s : array)
sum += s.length();
return sum;
}
This would be used as:
public static void main(String[] args) {
String[] names = { "bob", "maxwell", "charley", "tomtomjack" };
int amountOfLetters = countAllLetters(names);
System.out.println(amountOfLetters);
}
So your finished result would be:
public class YourClass {
public static void main(String[] args) {
String[] names = { "bob", "maxwell", "charley", "tomtomjack" };
int amountOfLetters = countAllLetters(names);
System.out.println(amountOfLetters);
}
public static int countAllLetters(String[] array) {
int sum = 0;
for(String s : array)
sum += s.length();
return sum;
}
}
Click here to test using an online compiler
Also notice how I don't declare the names array inside the method. Instead, I declared it outside of the array, then passed it into the method as an argument. This allows the method to be reusable for different arrays, rather than a single hard-coded names array.
However, if you want to return a String of array's content combined (based on the name & return type you're showing in your question), you need to keep the return type of your method as String, and concat the items from the array:
public static String concat(String[] array) {
StringBuilder builder = new StringBuilder();
for(String s : array)
builder.append(s);
return builder.toString();
}

Related

How do i count how many words there are, and ignore same words in a string? (using method)

The code here only shows how many words they are, how do i ignore the words that are the same?
For example, "A long long time ago, I
can still remember", would return 8 instead of 9.
I want it to be a method which takes one parameter s of
type String and returns an int value. And im only allowed to use the bacics, so no hash keys or hash set and advance stuff.
public static int mostCommonLetter(String s){
int wordCount = 0;
boolean word = false;
int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
}
How do i ignore the words that are the same?
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String input = "A long long time ago, I can still remember";
String[] words = input.split(" ");
List<String> uniqueWords = new ArrayList<>();
for (String word : words) {
if (!uniqueWords.contains(word)) {
uniqueWords.add(word);
}
}
System.out.println("Number of unique words: " + uniqueWords.size());
}
}
Output: Number of unique words: 8
Basically, what you can do if you're allowed to use data structures like lists and so on, is create a list and put the words of the input sentence in the list if and only if they aren't already there.
General idea:
public int getUniqueWords(String input) {
// Split the string into words using the split() method
String[] words = input.split(" ");
// Create a Set to store the unique words
Set<String> uniqueWords = new HashSet<String>();
// Loop through the words and add them to the Set
for (String word : words) {
uniqueWords.add(word);
}
// Return unique words amount
return uniqueWords.size();
}
Same solution using StreamAPI:
public int getUniqueWords2(String input) {
// here we can safely cast to int, because String can contain at most "max int" chars
return (int) Arrays.stream(input.split(" ")).distinct().count();
}
If it is needed to handle multiple spaces between words, add some cleanup for input:
// remove leading and trailing spaces
cleanInput = input.trim();
// replace multiple spaces with a single space
cleanInput = cleanInput.replaceAll("\\s+", " ");
Considering the requirement "allowed to use the bacics":
hashtable (HashSet) is a basic data structure in algorithms
problem of counting unique items cannot be logically solved without a container holding "aready seen" items, so algorithm could check whether the next item is counted or not
in the role of container in the simplest case could be a list, but that would cause O(n^2) time complexity.
You can use a Set<T> collection type, that can only contains unique values:
public static int getTotalUniqueWords(String input) {
String[] words = input.split(" ");
Set<String> uniqueWords = new HashSet<>();
Collections.addAll(uniqueWords, words);
return uniqueWords.size();
}
or with Streams:
public static long getTotalUniqueWordsStream(String input) {
String[] words = input.split(" ");
return Arrays.stream(words).distinct().count();
}

Why an extra space is added to my Array List of String when I use split method on the string

I have attached my code and the output of the code. When I print the array elements, it is not showing any spaces but when these elements are transferred to the arrayList, I get these spaces before every element as if they are there because of the "/" in the actual string
This is my code
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
String n= "/www/abc/pqr/./com";
String arr[] = n.split("/");
ArrayList<String> list = new ArrayList<>();
for(int i=0;i<arr.length;i++)
{
if(arr[i]!=".")
{
list.add(arr[i]);
}
}
System.out.println(list);
}
output is this :
[, www, abc, pqr, ., com]
I have also used equals() method to compare the strings but no luck with that too.
this is my updated code
public class LTI {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
String n = "/www/abc/../pqr/./com";
String arr[] = n.split("/");
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
if (!arr[i].isEmpty()) {
if (!arr[i].equals(".")) {
if (arr[i].equals("..")) {
list.remove(i);
} else {
list.add(arr[i]);
}
}
}
}
}
}
But it shows index 3 out of bounds for length 2
So I am assuming your question is aimed at these whitespaces you get in your output:
[, www, abc, pqr, ., com]
^ ^ ^ ^ ^
These "spaces" you see are not actually part of the Strings inside your list, they are added when you implicitly call toString() on the ArrayList via System.out.println(list).
See AbstractCollection#toString():
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
So the actual Strings in your list do not contain these whitespaces, they are simply added for viewing convenience when printed.
Here is your updated code, that also fixes the issue of comparing the Strings correctly via equals instead of !=. I also included a isEmpty() check to remove the empty Strings from the list:
public static void main(String[] args) {
String n = "/www/abc/pqr/./com";
String arr[] = n.split("/");
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
if (!(arr[i].equals(".") || arr[i].isEmpty())) {
list.add(arr[i]);
}
}
System.out.println(list);
}
Output:
[www, abc, pqr, com]

Finding the Sum of a String of numbers seperated by operators

Given String = "128+16+8+2+1"
Answer should print out 155
The code is supposed to add all numbers in the string and the answer should be printed out as a string.
I attempted to write the code for this, however the last 2 numbers will not add and my current answer is printing out 153. Looking for help to lead me to the correct solution.
import java.util.stream.*;
public class add {
static void evalA(String s) {
int n = countChar(s,'+');
System.out.println(s);
int cnt = 0;
int[] data = new int[n];
for(int i=0;i<s.length();i++) {
if (s.charAt(i)=='+') {
System.out.println(s.substring(0,i));
data [cnt] = Integer.parseInt(s.substring(0,i));
cnt++;
s = s.substring(i+1,s.length()-1);
i=0;
}
}
String sum = ""+IntStream.of(data).sum();
System.out.println(sum);
}
}
You could do something like this:
public static void main(String[] args)
{
evaluate("128+16+8+2+1");
}
public static void evaluate(String equation)
{
String[] numbers = equation.split("\\+");
int sum = 0;
for (String number : numbers)
{
//could wrap this in a check incase of exception or errors
sum += Integer.parseInt(number);
}
System.out.println(sum);
}
It just splits the string up by the + to get the individual numbers as an array and then loop through the array and add each numbers value to a sum variable.

String Filtering .. Any one..Contains only either of the selected characters or both

I have a array from 0 to 10000.
problem
And i need to filter only the numbers containing either 3 or 4 or both and none other than that...
eg., 3,4,33,44,333,444,343,434,334
I tried the do while technique but I have made some mistake in the code..\
I'm not getting the output still..:(
the improved code is
import java.util.*;
import static java.lang.System.*;
public class numb {
public static void main(String[] args) {
int num,c,cum;
int i;
Scanner in = new Scanner(System.in);
out.println(3/10);
out.println("How many elements u need to put in this array?");
num=in.nextInt();
int[] ray1 = new int[num];
List<String> l1 = new LinkedList<String>();
for (c=0;c<num;c++)
{
ray1[c]=c;
}
for(i=1;i<num;i++)
{
boolean baabu=true;
do {
cum=ray1[i];
int lastdig = cum%10;
if(lastdig!=3||lastdig!=4)
{
baabu=false;
}
cum=cum/10;
}
while(cum>0&&baabu);
if(baabu)
{
String ad = String.valueOf(ray1[i]);
l1.add(ad);
}
}
printme(l1);
}
public static void print (int[] array)
{
for(int xc:array)
out.println(xc);
}
public static void printme (List<String> l1)
{
for(String yc:l1)
out.println(yc);
}
}
Check if the last digit is a 3 or a 4: if it is, divide the number by 10 and check the next digit; otherwise, discard the number.
boolean add = true;
do {
int lastDigit = num % 10;
if (lastDigit != 3 && lastDigit != 4) {
add = false;
}
num /= 10;
} while (add && num > 0);
if (add) {
// Add to list.
}
Think of the string as a list of characters, eg 3435 is 3,4,3,5 and 39 is 3,9. You need to iterate over the characters in the string and check that each one is a 3 or 4. Your code checks for specific combinations of 3 and 4 but cannot handle all possible enumerations.
Since you're treating the numbers as Strings already, the simplest way to find {3,4} strings is by matching the Regex "^[34]+$"
Pattern threeFourStrings = Pattern.compile("^[34]+$");
...
if (threeFourStrings.matcher(ad).matches()) {
l1.add(ad);
}
However, since you want all {3,4} strings up to 10000 (i.e. up to 4 digits), it would be far more efficient to construct them. You might start looking here: How to get all possible n-digit numbers that can be formed using given digits?
(Of course since you only have 2 digits, "3" and "4", it might be even more efficient to just list the binary numbers from 0 to 1111 and transpose "0" to "3" and "1" to "4".)
Use this method for every int in the array (it worked for me):
public static String myMethod(int num){
String str = String.valueOf(num);
String ns ="";
for (int i=0; i<str.length(); i++) {
if (str.substring(i, i+1).equals("3"))
{
ns += 3;
}
if (str.substring(i, i+1).equals("4"))
{
ns += 4;
}
}
return ns;
}

Summing the ints in a string using scanner.chopper: java

first post on this site, so, I essentially have to find a way to chop up the ints in a string, divided only by spaces, (example would be ("9 10 5 20 1 2 3") and then find the sum of all of the chopped up ints. I know i have to use chopper.nextInt(), but I am not sure how to format the totality of the code, along with summing the output after. Thanks so much!
import static java.lang.System.*;
import java.util.Scanner;
public class LineTotaller
{
private String line;
public LineTotaller()
{
setLine("");
}
public LineTotaller(String s)
{setLine(s);
}
public void setLine(String s)
{line = s;
}
public int getSum()
{
int sum = 0;
Scanner chopper = new Scanner(line);
while(chopper.hasNextInt())
{
out.print(chopper.nextInt());
sum+= //returned ints from above
}
}
public String getLine()
{
return "";
}
public String toString()
{
return getLine();
}
}
I think you want to do the following
public int getSum()
{
int sum = 0;
Scanner chopper = new Scanner(line);
while(chopper.hasNextInt())
{
int nextInt = chopper.nextInt();
System.out.print(nextInt);
sum += nextInt;
}
return sum;
}
You can only call nextInt once after you confirmed that there is something via hasNextInt. If you want to print it and add it to the sum, you have to store the value temporarily in a variable.
Consider using the string.split() method to place you numbers string into a string array then iterate through the array with a 'for loop', convert each element to a integer ( Integer.valueOf() )and maintain a ongoing total with each iteration.
Something like:
String yourString = "9 10 5 20 1 2 3";
String[] myNumbers = yourString.split(" ");
int total = 0;
for (int i = 0; i < myNumbers.length; i++) {
total+= Integer.valueOf(myNumbers[i]);
}
System.out.println("Total is: -> " + total);
That should get it done for you.

Categories

Resources