I am trying to create a method that will count number of zeros in a statement/numbers (numOfZero), that a string as input and returns the number of occurrence of ‘0’ in the string.
And if there is no zero it should return zero. I have used String.length() and String.CharAt(int index). but getting some errors. Any help?
public static int countOccurance(int num){
int count = 0;
String aux = Integer.toString(num); //conversion Integer to string.
for(int i= 0; i<aux.length(); i++){
if(aux.charAt(i) == '0'){
count++;
}
}
return count;
}
This is the method. It counts how many zeros there are in your number. Try it!
Related
My code is working fine and dispaly the count of maximum occuring character but not display the maximum character.
Also tell me smart way of writing code i am beginner
void checkMax1(String str1){
final int hash=256;
char max_occ=str1.charAt(0);
int asc[]=new int[hash];
int n=str1.length(),max_count=-1;
char Chars[]=str1.toCharArray();
for(int i=0;i<n;i++){
asc[Chars[i]]++;
}
for(int i=0;i<hash;i++){
if(max_count<asc[i]){
max_count=asc[i];
max_occ=(char)asc[i];
System.out.println(asc[i]);
}
}
System.out.println(max_count+""+max_occ);
}
}
Just change the line saving the character to
max_occ = (char) i;
the index is the code of the character, the value in asc the count for that character.
The variable names of your code are kind of hard to understand, maybe a bit better (IMHO):
final int MAX = 255;
int[] count = new int[MAX];
char maxChar = ...
int maxCount = -1;
and variables, by convention, start with lower case, Class and Interface names with upper case...
You just need an extra if
if(max_count<asc[i]){
max_count=asc[i];
System.out.println(asc[i]);
if(max_occ<(char)asc[i]){
max_occ=(char)asc[i]
}
}
you can catch it in same first loop
for (int i=0; i<n; i++)
if (++asc[Chars[i]] > max_occ) {
++max_occ;
max_char = Chars[i];
}
I have a function like the following:
int getIndex(String noisyString) {
String quietString = noisyString.replaceAll("[^a-z]", "");
int quietStringIndex = findIndexInQuietString(quietString);
return originalIndexInNoisyString; // ???
}
After stripping a string of all non alphabetical characters, I find an arbitrarily chosen index inside the stripped string. How can I convert this index back to one that can be used for the unstripped string?
It sounds like you are trying to get the index in the non-filtered string of the same character at the chosen index in the filtered string.
(ie. you have a String s1 = "abc123def" s1.replaceAll() = "abcdef". You want to get the original index of the character at index 4 in the filtered String.
The character at index 4 in the filtered String is e. Its index value in the unfiltered String is 7.)
The simplest brute force way to do this would be to use a counter to go through the string keeping track of what index you are up to, meanwhile having a separate counter variable to keep track of how many characters that have been passed that are valid for the filtered string.
public static int getOriginalIndex(String s, int index){
if (index > s.replaceAll("[^a-z]", "").length()) {
throw new IllegalArgumentException("index is invalid");
}
int counter;
int validCharCounter = 0;
for (counter = 0; counter < s.length() && validCharCounter < index; counter++) {
if (s.charAt(counter) >= 'a' && s.charAt(counter) <= 'z')
validCharCounter++;
}
return counter;
}
I'm trying to write a class and create accessors in Eclipse that I will have to use later on, however I'm having trouble doing so. I have the directions listed below but keep getting stuck on the last two.
Directions:
Write a class StringSet. A StringSet object is given a series of String objects. It stores these Strings (or a reference to them, to be precise) and can perform limited calculations on the entire series. A StringSet class has the following specification:
a single instance variable of type ArrayList<String>
a single default constructor
mutator that adds a String newStr to the StringSet object
void add(String newStr)
accessor that returns the number of String objects that have been added to this StringSet object
int size()
accessor that returns the total number of characters in all of the Strings that have been added to this StringSet object
int numChars()
accessor that returns the number of Strings in the StringSet object that have exactly len characters
int countStrings(int len)
My code so far:
import java.util.ArrayList;
public class StringSet {
ArrayList<String> StringSet = new ArrayList<String>();
public StringSet() {
}
public void add(String newStr) {
StringSet.add(newStr);
}
public int getsize() {
return StringSet.size();
}
public int getnumChars() {
return StringSet.length();
}
public int countStrings(int len) {
if (StringSet.equals(len)) {
return StringSet.size();
}
}
}
Your string set is an array of string objects. Think of it as though you've added each of the following to stringSet (indexes are to the left of the value).
0[Hello]
1[My]
2[name]
3[is]
5[Keith]
For simplicity I'm going to use a primitive String[] rather than an ArrayList
Question 5
Create a variable that will increment its value by the size of each String. Then use a for loop to evaluate each individual String's length and add it to that variable:
int totalCharsInStringSet = 0;
for (int i = 0; i < stringSet.size(); i++) { // loop through each index
// add the length of the string at this index to your running tally
totalCharsInStringSet += stringSet[i].length;
}
// you've read through all of the array; return the result
return totalCharsInStringSet;
Question 6
Calling stringSet.size() is just going to count how many elements are in the array; i.e., 5. So you need to create a tally of how many individual strings match the target length. Craete a variable to keep that tally. And again, use a for loop to iterate through the array, and compare each string's length to the target value. If it matches, increment your tally:
int numberOfMatches = 0;
for (int i = 0; i < stringSet.size(); i++) {
if (string[i].length == len) { // "len" is your input target length
numberOfMatches ++;
}
}
return numMatches;
Number 5: You iterate through your ArrayList and add up the length of the strings stored there.
Number 6: You iterate through you ArrayList and check if the length of the String matches the desired length, and keep track of the number of matching strings.
Well ArrayLists don't have a length() method, so what you need to do to count total number of chars in the string set is iterate through the StringSet list and find the length of each string and add it to a running total.
int sum = 0;
for(int i = 0; i < StringSet.size(); i++){
sum = sum + StringSet.get(i).length();
}
return sum;
For the countStrings you need to place this if statement in a for loop and increment a sum each time the if statement is triggered and return the sum
int sum = 0;
for(int i = 0; i < StringSet.size(); i++){
if(StringSet.get(i).length() == len){
sum = sum + 1;
}
}
return sum;
For Question 5:
public int getnumChars()
{
int countChar = 0;
for(String strSet: StringSet){
countChar += strSet.length();
}
return countChar;
}
For Question 6:
public int countStrings(int len)
{
int count = 0;
for(String strSet: StringSet){
if(strSet.length() == len){
count++;
};
}
return count;
}
Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. For instance a and b is respectively "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.
What is wrong with my solution?
int count=0;
for(int i=0;i<a.length();i++)
{
for(int u=i; u<b.length(); u++)
{
String aSub=a.substring(i,i+1);
String bSub=b.substring(u,u+1);
if(aSub.equals(bSub))
count++;
}
}
return count;
}
In order to fix your solution, you really don't need the inner loop. Since the index should be same for the substrings in both string, only one loop is needed.
Also, you should iterate till 2nd last character of the smaller string, to avoid IndexOutOfBounds. And for substring, give i+2 as second argument instead.
Overall, you would have to change your code to something like this:
int count=0;
for(int i=0; i < small(a, b).length()-1; i++)
{
String aSub=a.substring(i,i+2);
String bSub=b.substring(i,i+2);
if(aSub.equals(bSub))
count++;
}
}
return count;
Why I asked about the length of string is, it might become expensive to create substrings of length 2 in loop. For length n of smaller string, you would be creating 2 * n substrings.
I would rather not create substring, and just match character by character, while keeping track of whether previous character matched or not. This will work perfectly fine in your case, as length of substring to match is 2. Code would be like:
String a = "iaxxai";
String b = "aaxxaaxx";
boolean lastCharacterMatch = false;
int count = 0;
for (int i = 0; i < Math.min(a.length(), b.length()); i++) {
if (a.charAt(i) == b.charAt(i)) {
if (lastCharacterMatch) {
count++;
} else {
lastCharacterMatch = true;
}
} else {
lastCharacterMatch = false;
}
}
System.out.println(count);
The heart of the problem lies with your usage of the substring method. The important thing to note is that the beginning index is inclusive, and the end index is exclusive.
As an example, dissecting your usage, String aSub=a.substring(i,i+1); in the first iteration of the loop i = 0 so this line is then String aSub=a.substring(0,1); From the javadocs, and my explanation above, this would result in a substring from the first character to the first character or String aSub="x"; Changing this to i+2 and u+2 will get you the desired behavior but beware of index out of bounds errors with the way your loops are currently written.
String a = "xxcaazz";
String b = "xxbaaz";
int count = 0;
for (int i = 0; i < (a.length() > b.length() ? b : a).length() - 1; i++) {
String aSub = a.substring(i, i + 2);
String bSub = b.substring(i, i + 2);
if (aSub.equals(bSub)) {
count++;
}
}
System.out.println(count);
trying to further my comprehension of loops and I found some questions online that I'm trying to complete but I got stuck on the second last one.
The original question was :
loop4(int val). This method uses a loop (for or while?) to do the following. Generate a random number between 1 and 10 (including 1 and 10) 10 times and count how many times val is generated, then print that number out.
What I've managed to do so far:
public int Loop4(int val){
for(int i = Math.random()*10; i<= 10; val!=0){
if (i == val) {
System.out.println(//I cannot for the life of me think of how I could constantly increment a +1 to this value because I only want to end up with 1 number in the end)
}
}
}
Simply create an count value and increment it.
public int Loop4(int val){
int count = 0;
for(int i = 0; i< 10; i++){
if ((int)(Math.random()*10) == val) {
count++;
}
}
System.out.println(count);
return count;
}
This code will do the trick:)
public int Loop4(int val){
int totalCount = 0;
for(int i = 0; i<= 10; i++){
int generatedNumber = (int)(Math.random()*10);
if (generatedNumber == val){
totalCount++;
}
}
System.out.print(totalCount );
}
You may want to try something like this. From your question you only want to loop 10 times and count how many times val is generated. You should create a total variable and increment each time the new random number == val.
Ex:
public int Loop4(int val){
int total = 0;
for(int i = 0; i <= 10; i++){
if ((int)(Math.random()*10) == val) {
total++;
}
}
return total;
}
There are a couple things in your code that you need to consider.
First, Math.random() returns a double, not an int so you have to cast it: (int) Math.random() (However casting this will cause some issue with rounding so do some research on that).
Second, the third argument in a for loop needs to be an iteration, not a comparison.
Ex: i++, ++i, --i
Third, create another variable int count = 0 that will count the number of times a number appears and place: count++ inside of your inner if statement and then have the System.out print it after your iteration.