I am having difficulty trying to code a part of a program in which I check to see if certain input is in an array/string (I can convert the array to an string). It also does not stop their, i need to figure out how many times the value I entered is in that array. For example: I have an array of 2 2 3 1 2. I enter in 2 and I want my program to count the number of twos I have in the array and store it to an integer value. Here is the code I have thus far, but it does not seem to work, when I try to store it to a space in a 2d array.
if (sv1==1)
{
int onesValue=0;
int answer;
v1=p1.charAt(0);
v2=p1.charAt(1);
v3=p1.charAt(2);
v4=p1.charAt(3);
v5=p1.charAt(4);
if (v1==1)
{
onesValue++;
}
if (v2==1)
{
onesValue++;
}
if (v3==1)
{
onesValue++;
}
if (v4==1)
{
onesValue++;
}
if (v4==1)
{
onesValue++;
}
if (v5==1)
{
onesValue++;
}
scoreSheet[0][0] =onesValue;
}
sv1, is a string that was converted to a double, p1 is a string converted to an array If anyone could help me with this it would be greatly appreciated.
To my understand I think this should count the occurrence of required character .
String find="2";
String[] array = {"2", "2", "3", "1", "2"};
Arrays.stream(array)
.collect(Collectors.groupingBy(s -> s))
.forEach((k, v) -> System.out.println(k.equals(find)?k + " - " + v.size()+" times":""));
Update:
If its an int array you can simply go with this:
String find=2;
long count = Arrays.stream(array).filter((s)-> s == find).count();
System.out.println("count of "+find+ " is - "+count);
Will it help ?
int i[] = {2,5,4,23,7,2,4,2};
int occurnce = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the number :");
int number = s.nextInt();
for (int n=0;n<i.length;n++){
if(i[n] == number)
occurnce++;
}
if(occurnce>0)
System.out.println("Number of occurance : " +occurnce);
else
System.out.println("Number doesnt exist");
Use Collections.frequency method
http://www.tutorialspoint.com/java/util/collections_frequency.htm
Integer arry[] = {2,5,4,23,7,2,4,2};
Map<Integer, Integer> resultMap = new HashMap<Integer, Integer>();
for (int index=0; index < arry.length;index++ ) {
int counter = 1;
Integer valueTobeChecked = arry[index];
if (!resultMap.containsKey(valueTobeChecked)) {
resultMap.put(valueTobeChecked, counter);
} else {
counter = resultMap.get(valueTobeChecked);
resultMap.put(valueTobeChecked, ++counter);
}
}
System.out.println(resultMap);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.