Java void into an int array - java

how do I store a void in to an array?
for my example:
count (String text) into int[] letter.
is there a quick and easy opportunity to do it or should I rewrite it completely?
I really appreciate your help
my code:
public static void main (String [] args){
String text="E";
String[] words = split(text);
int[] letter = count(text);
someWords(words, letter);
}
public static int[] count(String text){
int count;
for (char letter=(char)65;letter<=90;letter++){
count=0;
for (int i=0; i<text.length(); i++){
if (letter==text.charAt(I) || (letter+32)==text.charAt(I)){
count++;
}
}
if (count>0){
System.out.println(letter+" = "+count);
}
}
}

I could be wrong, because your question is not very clear, but it seems that what you're trying to do is:
public static int[] count(String text){
int[] counts = new int[26];
// iterate over each letter:
for (char letter='A';letter<='Z';letter++){
int currentIndex = (int) letter - 'A';
// count the occurrences of the current letter:
for (int i=0; i<text.length(); i++){
if (letter==text.charAt(i) || (letter+32)==text.charAt(i)){
counts[currentIndex]++;
}
}
// print the count for the current letter if non-zero
if (counts[currentIndex]>0){
System.out.println(letter+" = " + counts[currentIndex]);
}
}
return counts;
}
There's surely a more efficient way to do this (iterating over the characters in text and incrementing the count index accordingly would be faster than checking all the chars in text 26 times), but the approach works.

I don't really understand why you want to do it like this, but you can just pass the int[] as a paramter.
...
int[] count = new int[1];
count(text, count);
...
public static void count(String text, int[] count){
...
count[0] = ..
}

Reading your code it seems like you just want to return and integer and not an integer array (the number of letters in a String as it seems)
public static int count(String text){
int count;
for (char letter=(char)65;letter<=90;letter++){
count=0; // are you sure you want to set the value of count to 0 every time you loop?
for (int i=0; i<text.length(); i++){
if (letter==text.charAt(i) || (letter+32)==text.charAt(i)){
count++;
}
}
if (count>0){
System.out.println(letter+" = "+count);
}
}
return count;
}
In your main method you write:
String[] words = split(text);
int letter = count(text);

public int count()
{
count = 0;
for ...
...
...
return count;
}
you should use RETURN word at the end of your function, and declare the return type (int, string, ...etc) next to the function name.

You only need to spin through the string once:
public static int[] count(String text) {
int[] totals = new int[26];
for (char c : text.toUpperCase().toCharArray()) {
int idx = (int)c - (int)'A';
if ((idx >= 0) && (idx <= 26)) {
totals[idx]++;
}
}
return totals;
}

Related

How do you print the highest and smallest number of ASCII value in string java

I found it, thank u mate. I actually too confuse yesterday, till i forget everything that i learnt. So here is my code, what do you think?
I just don't know why my minChar not working when i delete this code :
if(stringValue.charAt(i) != 32){
public class MyString {
public static void main(String[] args) {
String stringValue = "Hello World";
SearchMyString str = new SearchMyString(stringValue);
str.stringInfo();
}
}
class SearchMyString{
private char maxChar;
private char minChar;
String stringValue;
int ascii;
public SearchMyString(String stringValue){
this.stringValue = stringValue;
}
char getMinChar(String stringValue, int n){
minChar = 'z';
for(int i = 0;i<n-1;i++){
if(stringValue.charAt(i)<minChar){
if(stringValue.charAt(i) != 32){
minChar = stringValue.charAt(i);
ascii = (int)stringValue.charAt(i);
}
}
}
return minChar;
}
public void stringInfo(){
int size = stringValue.length();
System.out.println("Smallest char : "+getMinChar(stringValue,size) + "\tASCII : " + ascii);
}
}
Use this method:
public static char getMaxChar(String a){
char max = a.charAt(0);
for (int i=0; i<a.length(); i++){
if ((a.charAt(i) > max)){
max = a.charAt(i);
}
}
return max;
}
Test case:
ACBDEFG
Returns
G
So what did we change?
For starters, if we are trying to get the character in the String that has the highest char int value, we don't need n. We are looping through the String, so all we need is the length, which can already be supplied by the .length() method.
To call the method, just do:
SearchMyString search = new SearchMyString();
search.getMaxChar(nama);
EDIT: So to make the method more reliable, instead of automatically setting max to 'A', we can set it to the first char of a (e.g, a.charAt(0))

Count of of characters matched in sequence of two string

I want to match two string and get how many chars matched in sequence.
Like :
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
like you can see that it must return 5 chars in sequence matched because DEFGH are exist on both sequence.
Thanks
import java.io.*;
import java.util.*;
class happy {
public static void main(String args[])
{
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
int a=0,c=0;
if(one.length()<two.length())
a=one.length();
else
a=two.length();
for(int i=0;i<a;i++)
{
if(one.charAt(i)==(two.charAt(i)))
c++;
}
System.out.println(c);
}
}
public class Test {
public static void main(String[] args) {
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
int size1 = one.length();
int size2 = two.length();
int i = 0;
int j = (size1 >= size2 ? size2 : size1);
char[] oneTab = one.toCharArray();
char[] twoTab = two.toCharArray();
int k = 0;
for(i = 0; i< j; i++){
if((String.valueOf(oneTab[i])).equals(String.valueOf(twoTab[i]))){
k = k+1;
};
};
System.out.println(k);
}
}
try this
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
int cnt=0;
for (int i=0;i<one.length();i++){
for (int j=0;j<two.length();j++){
if(one.charAt(i) == two.charAt(j) ){
cnt++;
}
}
}
Toast.makeText(this, "count"+cnt, Toast.LENGTH_SHORT).show();
Maybe something like this will do it.
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
int counter = 0;
// Iterate over the string character by character - stop when reaching the
// end of the shortest string
for( int i=0; i<one.length() && i<two.length(); i++ ) {
// Compare the strings character at the current position/index
if(one.charAt(i) == two.charAt(i)) {
// The characters matched so increment the counter
counter++;
}
}

I want a java program to input a string and display the occurence of each unique word without any built in method

This program I wrote to display the number of words available in the given String.
Now I want the logic for occurenceof each word in the string without using any built in method.
import java.util.Scanner;
public class Test80
{
public static void main(String args[]){
Scanner in=new Scanner(System.in);
System.out.println("Enter your sentence:[Try to ignore space at end]");
String s=in.nextLine();
System.out.println("Size of the string is "+s.length());
int res=count(s);
System.out.println("No of words in the given String --->>"+" "+s+" :"+"is"+" :"+res);
}
private static int count(String s) {
int count=0;
if(s.charAt(0)!=' ')
{
count++;
}
for(int i=0;i<s.length();i++)
{
if((s.charAt(i)==' ')){
count++;
}
}
return count;
}
}
Instead of doing all that use the logic that if there are 'n' spaces in a sentence then the number of words will be n+1 simply;
Modify the program with if else .
In the count method do this
private static int count(String s) {
int count=0;
for(i=0;i<s.length();i++)
{
if(s.charAt(i)==' ') count++;
}
return (count+1);//returning the number of words
}
Depending on your definition of built in method you should use a Map for that task.
Map<String,Integer> = new HashMap<>();
int begin_pos = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == ' '){
int count = map.containsKey(s.substring(begin_pos, i)) ? map.get(s.substring(begin_pos, i)) : 0;
map.put(s.substring(begin_pos, i), count + 1);
begin_pos = i+1;
}
else if(i == s.length() -1){
int count = map.containsKey(s.substring(begin_pos)) ? map.get(s.substring(begin_pos)) : 0;
map.put(s.substring(begin_pos), count + 1);
}
}

How can I check character occurrence in a string?

My Question is-
Input is string. Return true if the String has exactly 1 character that appears twice in the string, 0 character that appear thrice in the string, and at least 1 character that appear four or more times in the string. There is a problem in my code and I am unable to find out the problem.
public class CheckCharacterOccurence {
static String testcase1 = "jjiiiiyy";
public static void main(String[] args) {
CheckCharacterOccurence testInstance = new CheckCharacterOccurence();
boolean result = testInstance.checkCharacterOccurence(testcase1);
System.out.println(result);
}
public boolean checkCharacterOccurence(String str) {
char ch=' ';
char ch1=' ';
int temp=0;
int temp1=0;
int temp2=0;
int count=0;
for(int i=0;i<str.length();i++){
ch=str.charAt(i);
for(int j=i;j<str.length();j++){
if(str.charAt(i)==str.charAt(j)){
ch1=str.charAt(i);
count++;
}
}
System.out.println(count);
if(count==2&&ch!=ch1){
temp++;
}
if(count==3&&ch!=ch1){
temp1++;
}
if(count>=4){
temp2++;
}
count=0;
}
if(temp==1&&temp1==0&&temp2>=1){
return true;
}
return false;
}
}
I would suggest using a map
For all characters in string, increment map[that_char]
At last iterate over map to find how many times each character appeared.
Alternatively you can use array also to keep count.
Something like
int [] ctr = new int[256]
ctr = all zeroes
for (ch : string)
ctr[ch]++
mxocc = 0
maxch = 'a'
for(ch = a, b, c, d, e...)
if(ctr[ch] > maxocc) maxocc = ctr[ch] and maxch = ch
Output require info
hey you can figure out the problem ... atleast i can give to some extend same code , you can check it and try to solve your problem... This program finds the pattern in the string, now you can go through this program, and try to solve ur problem in your program by your own self.and try to do it by your own then only ur coding skills will get improved.and vote this answer if u fing it really helpful
#include<stdio.h>
#include<string.h>
int occur(char[],char[]);
int occur(char sent[],char pattern[])
{
int count=0;
for(int i=0,j=i;sent[i]!='\0';)
{
if(sent[i+j]==pattern[j]&&pattern[j]!='\0')
{
j++;
}
else if(j==strlen(pattern))
{
count++;
i=i+j;
j=0;
}
else
{
i++;
j=0;
}
}
return count;
}
int main()
{
char sent[] = "aabaabaaabbbabababddfggaabbbasab";
char pattern[] = "aba";
int result = occur(sent,pattern);
printf("\nNo of Occurrences --- > %d",result);
return 0;
}
You should simplify your code. For example there is not need to use those complex for-loops, you can use a for-each.
This code finds out the frequency of characters in a string and stores it in a Map.
import java.util.*;
public class CheckCharacterOccurence {
public static void main(String[] args) {
Map<Character, Integer> counting = new HashMap<Character, Integer>();
String testcase1 = "Helloooo";
for(char ch: testcase1.toCharArray()){
Integer freq = counting.get(ch);
counting.put(ch, (freq == null) ? 1 : freq + 1);
}
System.out.println(counting.size() + " distinct characters:");
System.out.println(counting);
}
}

Sequence Count i.e suppose aabbbaaccd is string output should be a=2,b=3,a=2,c=2,d=1

As i have tried ,it gives ArrayIndexOutOfBounds Ecxeption and does not print last char
please help me to find bug in my code.or is there any alternate
public static void sequenceCount(String s) {
int counter;
int i=0;
char c;
char[] arr = s.toCharArray();
while(i<arr.length){
counter=0;
c = arr[i];
while(c==arr[i]){
counter++;
i++;
}
System.out.println("letter"+" "+c+":"+"number of times"+counter);
}
}
As i am a novice to java my code may be inefficient
Your inner loop is not bound by the length of the array. Try:
while(i < arr.length && c==arr[i]){
counter++;
i++;
}
This works - you need to ensure that your inner loop doesn't pass beyond the end of the string, and you need to always catch the last letter, too:
public static void sequenceCount(String s) {
char[] arr = s.toCharArray();
int i = 0, n = arr.length;
while (i < n) {
char c = arr[i];
int count = 0;
do {
++i; ++count;
} while (i < n && arr[i] == c);
System.out.println("letter "+ c +":"+"number of times " + count);
}
}
My approach would be to use two for loops.
The first for loop would run a loop with the decimal equivalent of A to Z.
The second for loop would run a loop that runs through the entire character array/string (I'd prefer a string rather than a char array here) and check to see if that given value at that index is equal the the value ran by the first for loop. If they are equal than add one to count. Print.
Don't forget to reset your counter after every run as well.
Similar Topic can be found here: Counting letters in a string using two for-loops
While many answers here are O(n^2), I tried to do it within O(n) time using recursion. This is modified from existing code that I already had so I know the method returns an int, but I don't use it (it's left over from copied code - fix it as you see fit)
public class CountCharSeqRecursive {
private String test = "AAABBA"; // (3)A(2)B(1)A
private StringBuilder runningString = new StringBuilder();
public static void main(String[] args) {
CountCharSeqRecursive t = new CountCharSeqRecursive();
System.out.println(t.getEncryptedValue(t.test));
}
public String getEncryptedValue(String seq){
int startIndex=0;
this.createCounterSeq(seq.charAt(startIndex), seq, startIndex);
return runningString.toString();
}
private int createCounterSeq(char prev, String sequence, int currentIndex){
return createCounterSeq(prev, sequence, currentIndex, 0);
}
private int createCounterSeq(char prev, String sequence, int currentIndex, int count){
if(currentIndex<sequence.length()){
char current = sequence.charAt(currentIndex);
if((prev^current) < 1){
++count;
}else {
this.addToSequence(count, prev);
count = 1;
}
return count += createCounterSeq(current, sequence, ++currentIndex, count);
}
this.addToSequence(count, prev);
return count;
}
private void addToSequence(int count, char ch){
runningString.append("("+count+")").append(ch);
}
}
My solution using HashSet, Works for all cases of a non-empty string.
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Character> set = new HashSet<Character>();
String input = "aabbcdeaab";
set.add(input.charAt(0));
int count = 1;
StringBuilder output = new StringBuilder("");
for(int i=1;i<input.length();i++) {
char next = input.charAt(i);
if(set.contains(next)) {
count++;
}else {
char prev = input.charAt(i-1);
output.append(Character.toString(prev) + count );
set.remove(prev);
set.add(next);
count=1;
}
}
output.append(Character.toString(input.charAt(input.length()-1)) + count );
System.out.println(output.toString());
}

Categories

Resources