Count how many times a letter appears in 2d array JAVA - java

So I basically have an array that looks like this:
BG6001;1193;M;63;B+
BG6001;1124;M;41;C
BG6001;1121;F;FA;FA
BG6001;1143;M;26;FA
BG6001;1157;F;74;A
And what I've been trying to do is to count how many times the letter "M" appears in it, and add it into a counter
Any ideas?
What I have tried so far:
for (int i=0; i<name.length(); i++) {
if (name.charAt(i)=='M' ) counter++;
}
System.out.println("the string contains " + count + " times the letter M")

You should probably use a foreach loop. Try implementing something like this:
int counter=0;
String[][] array = something;
for(String[] subArray : array)
for(String string : subArray)
if(string.toLowerCase().equals("m"))
counter++;
//Counter has the value of the amount of 'm's in the array

#mike fischer please check the below code whoich gives you the count of "M" in an Array.
public class Arraycount {
public static void main(String args[]){
String[] a=new String[5];
a[0]="BG6001;1193;M;63;B+";
a[1]="BG6001;1124;M;41;C";
a[2]="BG6001;1121;F;FA;FA";
a[3]="BG6001;1143;M;26;FA";
a[4]="BG6001;1157;F;74;A";
int count=0;
for(int i=0;i<=a.length-1;i++){
for(int j=0;j<=a[i].length()-1;j++){
char c=a[i].charAt(j);
if(c=='M'){
count++;
}
}
}
System.out.println("Number of M present in an array is "+count);
}
}

My answer is very similar to 7H3_H4CK3R's answer with some variation. Specifically, if a particular letter (in this case, "M") could appear anywhere in the string, you can do the following (and I apologize for using C# rather than Java syntax here, I'm not sitting in front of a Java compiler, but hopefully the differences won't be too difficult to follow):
private static int Count(string[][] data, char letterToFind)
{
int count = 0;
// Loop over each array
foreach (string[] array in data)
{
// Each array is a collection of strings
foreach (string str in array)
{
// Loop through the characters in each string
for (int i = 0; i < str.Length; i++)
{
if (str[i] == letterToFind)
{
count++;
}
}
}
}
return count;
}
Alternatively, if you're looking for something where the entire string is "M" 7H3_H4CK3R's answer should do the trick.

Related

How to calculate the total number of characters in a 2D String array using enhanced for loop in java?

public class LoopPractice {
public static void main(String[] args) {
String[][] wordData = {{"study", "consider", "examine", "learn"}, {"ponder", "read", "think", "cogigate"}};
// Below is the question. Am trying to print the total number of characters in the wordData String array.
//Use nested enhanced for loops to calculate the total number of characters in the wordData 2D array and print the result to the console. (Get the string .length() of each element)
// Below is what I have but it keeps printing the characterCount of 0 and the total number of each word character in the console.
// I don't know how to get the String.length() of the nested String array using the enhanced for loop.
int characterCount = 0;
for(String[] characters: wordData) {
for(String totalNumber : characters) {
System.out.println(totalNumber.length();
}
}
System.out.println(characterCount);
}
}
While your code correctly iterates through the 2D array, you aren't actually incrementing your total character count.
Simply change the following line:
System.out.println(totalNumber.length();
to:
characterCount+= totalNumber.length();
You have the right idea, except instead of printing to the console in the nested for loop, you need to add the length of the string to your characterCount. so you would do:
characterCount = characterCount + totalNumber.length();
or for short
characterCount += totalNumber.length();
You could write it a little cleaner:
int count = 0;
for (String[] arr: wordData) {
for (String str: arr) {
count += str.length();
}
}
System.out.println(count);
int characterCount = 0;
for (String[] wordRow : wordData) {
enter code herefor (String word: wordRow) {
enter code herecharacterCount += word.length();
}
}
System.out.println(characterCount);

Looping through arraylist of arraylists

I have this code below to count the frequency of a string in an ArrayList
public static int count (ArrayList<String> c, String str){
int num = 0;
num = Collections.frequency(c, str);
return num;
}
What I have to do now is to improve this so that the function takes in ArrayList<ArrayList<String>> and can loop through the set of Arraylists and Count the occurrences of the String. Any ideas would be great.
You need to use two nested for loops, looping through each list with the first one and looping through each element of the current list with the second, i.e.:
int count = 0;
for (ArrayList<String> list : lists) {
for (String string : list) {
if (list.equals("something")) count++;
}
}
To compute the frequency you'll also need to count the total number of elements in all the lists, but I'll leave that to you as it should be straightforward now.
Dude, you described the algorithm, it won't get simpler than that. Just code the thing.
Keep in mind that Collections::frequency is misnamed (IMHO), it should be count.
In java 8 use the stream
public void findOccurenceInLists(ArrayList<ArrayList<String>> lists, String myStr) throws Exception {
int occurence = 0;
lists.stream().forEach((list) -> {
occurence += list.stream().filter((str) -> str.equals(myStr)).count();
});
System.out.println(occurence + " occurence found");
}

When I pass a character array in java then the array passed is different.For example if I pass an array aqdf the passed array is actually aqqq

I am trying to implement an algorithm to determine if a string has all unique characters without using any additional datastrutures.
Here is my code:
package CTCI;
import java.util.Scanner;
public class ArrStrng1 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter the number of characters in the string?");
int l=s.nextInt();
char[] ca=new char[l];
System.out.println("Enter the characters in the string?");
for(int i=0;i<l;i++)
{
char c=s.next().charAt(0);
ca[i]=c;
}
if(unique(ca,l))
System.out.println("YES");
else
System.out.println("NO");
s.close();
}
public static boolean unique(char[] str,int l)
{
//using insertion sort to sort the character array
char c;
for(int i=1;i<l;i++)
{
c=str[i];
int j=i;
while(j>0 && c<str[j-1])
{
str[j]=str[j-1];
j--;
}
}
//Now checking if any two consecutive characters are same
for(int j=0;j<l-1;j++)
{
if(str[j]==str[j+1])
return false;
}
return true;//If no two consecutive characters are same then the character array is unique
}
}
This solution is not working since the passed character array to the function unique gets modified e.g. abcd becomes abbb.
Am I missing out on something?What is the bug in my code?
Any help is appreciated.Thank you.
There is problem with your insertion sort, you forgot to insert the value of c in smaller index(j-1). Hence the correct soring is:
char c;
for(int i=1;i<l;i++)
{
c=str[i];
int j=i;
while(j>0 && c<str[j-1])
{
str[j]=str[j-1];
str[j-1]=c;
--j;
}
}
Rest is fine.
i assume you wish to implement the insertion sort yourself.
because java has sort which you can use on Arrays.
any way the issue is in the insertion sort implementation you forgot to switch between the numbers and you just assign the bigger character try this:
char c;
char tmp;
for(int i=1;i<l;i++)
{
c=str[i];
int j=i;
while(j>0 && c<str[j-1])
{
tmp = str[j];
str[j]=str[j-1];
str[j-1] = tmp;
j--;
}
}
// Arrays.sort(str);
//Now checking if any two consecutive characters are same
on another note I suggest giving meaningful names to your variables ( even in these tutorials ) it really helps in the future.
hope it helps.

Sorting Strings as inserted into array in Java

I'm trying to create a program that takes user input and sorts it alphabetically as it comes in using compareTo String operations (not array.sort) and prints the final sorted array at the end. I've got most of the body of this problem down but am lost once I get to the sort function. Does anyone have any ideas on how I might be able to finish out the SortInsert method?
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int array_size = GetArraySize();
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String nextString = GetNextString();
String[] sortedArray = SortInsert(nextString, myArray);
}
PrintArray(sortedArray);
}
input.close();
}
}
public static String[] SortInsert(String nextString, String[] myArray){
for(int i = 0; i < myArray.length;)
if (nextString.compareToIgnoreCase(myArray[i]) > 0) {
i++;
//if current text is less(alphabetically) than position in Array
}else if (nextString.compareToIgnoreCase(myArray[i]) < 0){
}
}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
return next_string;
}
}
There are a number of problems with this code. First I'll answer your immediate question, then enumerate some of the other problems.
The SortInsert method takes a String[] that will have been initialized with null values, so you will need to take that into account. The for loop would look something like this. (I'm using comments instead of writing the actual code since I'm not doing the project)
for (int i=0; i<myArray.length; ++i) {
if (myArray[i] == null) {
// we found a blank spot. use it to hold nextString.
break;
} else if (nexString.compareToIgnoreCase(myArray[i]) < 0) {
// nextString should be in spot i, so make room for it
// by shuffling along whatever is in the array at "i" and later
// by one place, then put nextString into position "i"
break;
}
// otherwise we'll just move to the next position to check
}
Now for the other issues.
You have a Scanner object in main that is never used. There's no point in having it and closing it at the end if your other methods make their own.
myArray will always be the sorted array so there's no point in making a local variable called sortedArray and return it from SortInsert. Note that your attempt to print sortedArray would fail anyway because that local variable is only in scope within the for loop.
When printing it should be myArray being passed to PrintArray.
If you're going to sort as you go, the TreeMap data structure is what you should be using, not an array. However, if you want to sort as you go with an array, you need to add some lines into your else if clause in SortInsert (should be sortInsert, BTW). (Another question: why is it else if rather than just else?)
The lines should create a new array of size one greater than the existing array, copy the first i-1 elements of the old array to the new array, put the new element in position i, then copy the remaining elements of the old array into positions one greater in the new array.
Once you find the position you wish to insert at, you have to shift all of the following elements down by one. Something like the following:
String temp = array[position];
for (int j = position+1; j < array_size-1; j++) {
String temp2 = array[j];
array[j] = temp;
temp = temp2;
}
array[array_size-1] = temp;

Read text file for integers and storing to array using scanner and exceptions

I'm trying to loop through a text file for integers and store integers found into an array.
Using a try-catch to determine which words are integers and which are not using InputMismatchException, removing the non-int strings from the input stream. As well as a NoSuchElementException for blank lines in the file.
My main issue is storing the integers and printing those integers in the array, in my second method :o . It also appears my loop is also recording non-ints as null as well. They aren't suppose be stored into the array.
public static void main(String[] commandlineArgument) {
Integer[] array = ReadFile6.readFileReturnIntegers(commandlineArgument[0]);
ReadFile6.printArrayAndIntegerCount(array, commandlineArgument[0]);
}
public static Integer[] readFileReturnIntegers(String filename) {
Integer[] array = new Integer[1000];
// connect to the file
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
}
// If file not found-error message
catch (FileNotFoundException Exception) {
System.out.println("File not found!");
}
// if connected, read file
if (inputFile != null) {
// loop through file for integers and store in array
while (inputFile.hasNextLine()) {
for(int i = 0; i<array.length; i++)
{
try{
array[i] = inputFile.nextInt();
}
catch(InputMismatchException excep1)
{
String word = inputFile.next();
}
catch(NoSuchElementException excep2){
}
}
}
}
return array;
}
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
//prints number of integers from file
//prints each integer in array
}
}
The approach taken in the first method is a bit flawed, since you're incrementing the i variable whether or not an integer is read.
So for example, if the file looked like this:
4
Hello
5
e
7
The beginning of your array would look like
[4, null, 5, null, 7...]
So you will end up with an array of size 1000, which has nulls at unpredictable places in there.
A slightly better approach would be this:
Keep a separate count variable that says how many integers you actually read.
Add items to the array at index count and not at i (since i just says how many lines you've looked at, whereas count will tell you how many integers you've come across).
When you're finished reading them, either
pass the count variable to the method that prints the array (so it knows only to look at the first count items), or
just copy the entire array into a new array of size count.
Example incorporating this into your code:
if(inputFile != null) {
// the number of integers we've read so far
int count = 0;
// loop through file for integers and store in array
while(inputFile.hasNextLine()) {
for(int i = 0; i < array.length; i++) {
try {
array[count] = inputFile.nextInt();
count++;
} catch(InputMismatchException excep1) {
String word = inputFile.next();
} catch(NoSuchElementException excep2) {
}
}
}
}
Then to copy into a correctly sized array,
Integer[] newArray = new Integer[count];
for(int i = 0; i < count; i++) {
newArray[i] = array[i];
}
and just return newArray instead of array.
Your print method will then simply have the same signature and functionality you'd expect:
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
for(int i = 0; i < array.length; i++) {
// print the number at array[i], and whatever else you want to print
}
}
This is probably the better approach, as you can still keep all the method signatures the same, and don't need to mess around with returning multiple variables or changing global state.
Or alternatively, if you don't want to copy the relevant bits into a new array, then you could just pass the count variable somehow to your second method, and do something like
for(int i = 0; i < count; i++) {
System.out.println("\tindex = " + i + ", element = " + array[i]);
}
Key difference there is you're iterating up to count, and not up to array.length.
You would need to find a way to return that from your first method along with the array (or maybe set a static variable somewhere), and you would then need to change the signature of your second method to be
public static void printArrayAndIntegerCount(Integer[] array, int count, String filename) {
...
}
Assuming all you logic for reading integers from file are correct and also hoping this is kind of home work. Though the following implementation is not the right approach, it just solves your purpose. All we are doing here is iterating all the elements in the array until it reaches the null and keep writing them into a buffer.
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
StringBuilder sb = new StringBuilder();
int count = 0;
for(Integer i : array) {
if(i != null) {
count++;
sb.append("index = ").append(i).append(", element = ").append(array[i]).append("\n");
} else {
break;
}
}
System.out.println("number of integers in file \""+filename+"\" = "+count);
System.out.println(sb);
}
Replace your catch statement with:
catch(InputMismatchException excep1)
{
String word = inputFile.next();
i-=1;
}
You were incrementing the array counter if it found a word. I have run my own test and this worked for me to fix your issue.
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
String message = "";
int i = 0;
while(i < array.length && array[i]!=null){
message = message + "index = "+i+", element = "+array[i]+"\n";
i+=1;
}
System.out.println("number of integers in file \""+filename+"\" = "+i);
System.out.println(message);
}

Categories