Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Question 1

Source Code
import java.util.Scanner

public class Question1 {

public Question1() {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Please enter a string: ");

String str = input.nextLine();

System.out.println("Please enter a character: ");

char a = input.next().charAt(0);

System.out.println("The character '" + a + "' occurences in \"" + str + "\" is : " + count(str, a));

input.close();

public static int count(String str, char a) {

int count = 0;

if (str.isEmpty()) {

return 0;

} else {

if (str.charAt(0) == a) {

++count;

return count + count(str.substring(1), a);

}
Sample Output
Question 2
Source Code
import java.util.Scanner;

public class Question2 {

public Question2() {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Please enter a character to be printed: ");

char charToPrint = input.next().charAt(0);

System.out.println("Please enter the number to be printed: ");

int n = input.nextInt();

printChar(n, charToPrint);

input.close();

public static void printChar(int n, char charToPrint) {

if (n > 0) {

for(int i = 0; i < n; ++i) {

System.out.print(charToPrint);

System.out.println();

printChar(n - 1, charToPrint);

}
Sample Output

You might also like