In: Computer Science
Please answer with a fully detailed solution with examples.
In Java, write a method to determine if a string contains only
digit characters.
In Java, write a method on how to find each occurrence of a letter
given a string.
In Java, given a list of numbers, write an algorithm to find all
the triples and pairs of numbers in the list that equal exactly
13.
In Java, write a function to find the total number of each
character in a given string.
Java code for above problems
import java.util.*;
class Main
{
// testing main method
public static void main(String args[])
{
System.out.println("Does \"123\"
has all digit characters? "+allDigits("123"));
System.out.println("Does \"12a3c\"
has all digit characters? "+allDigits("12a3c"));
System.out.println();
countChars("alphabets");
System.out.println();
List<Integer> list=new
ArrayList<Integer>();
list.add(8);
list.add(2);
list.add(4);
list.add(13);
list.add(3);
list.add(5);
tripletsAndDoubles(list);
}
// method that returns true if given string has all
characters as digits
public static boolean allDigits(String str)
{
for(int
i=0;i<str.length();i++)
{
char
ch=str.charAt(i);
if(!(ch>='0'
&& ch<='9'))
{
return false;
}
}
return true;
}
// method that prints the occurences count of all the
characters of given string
public static void countChars(String str)
{
int [] count=new int[256];
for(int
i=0;i<str.length();i++)
{
count[str.charAt(i)]++;
}
for(int i=0;i<256;i++)
{
if(count[i]>0)
{
System.out.println((char)i+" --->
"+count[i]);
}
}
}
// method that prints the triplets and pairs of given
list whose sum is 13
public static void
tripletsAndDoubles(List<Integer> list)
{
System.out.println("Triplets:
");
printTriplets(list);
System.out.println();
System.out.println("Pairs:
");
printPairs(list);
System.out.println();
}
// method that prints the triplets whose sum is
13
public static void printTriplets(List<Integer>
list)
{
int len=list.size();
for(int i=0;i<len;i++)
{
for(int
j=i+1;j<len;j++)
{
for(int k=j+1;k<len;k++)
{
if(list.get(i)+list.get(j)+list.get(k)==13)
{
System.out.println(list.get(i)+"+"+list.get(j)+"+"+list.get(k)+"=13");
}
}
}
}
}
// method that prints the pairs whose sum is 13
public static void printPairs(List<Integer>
list)
{
int len=list.size();
for(int i=0;i<len;i++)
{
for(int
j=i+1;j<len;j++)
{
if(list.get(i)+list.get(j)==13)
{
System.out.println(list.get(i)+"+"+list.get(j)+"=13");
}
}
}
}
}
Sample output
Note: Question 2 and 4 are same. So same will be repeated for both.
Mention in comments if any mistakes or errors are found. Thank you.