In: Computer Science
Question 1 Consider the method |
displayRowOfCharacters |
that displays any |
given character the specified number of times on one line. For example, the call: |
displayRowOfCharacters('*', 5);
produces the line: *****
Implement this method in Java by using recursion.
Question 2
Write a method that asks the user for integer input that is between 1 and 10, inclusive. If the input is out of range, the method should recursively ask the user to enter a new input value.
HELP ME PLEASE.
Question 1
Raw code:
//class name
class Main {
//main
public static void main(String[] args) {
//calling static method
displayRowOfCharacters('*', 5);
}
//method to display characters s of count k
public static void displayRowOfCharacters(char s,int k) {
//codition to reutrn nothing when k is 0
if (k ==0) {
return ;
}
//if k is greater than 0
else {
//print the characters
System.out.print(s);
//call the function recursively
displayRowOfCharacters(s, k-1);
}
}
}
Editor:
output:
Question 2
Raw code:
import java.util.Scanner;
//class name
class Main {
//main
public static void main(String[] args) {
//calling static method
ask_input();
}
//method to ask input between 1 and 10 inclusinve
public static int ask_input(){
//object to Scanner
Scanner sc = new Scanner(System.in);
//prompt
System.out.println("Entr value between 1 and 10 : ");
//get input from user
int input=sc.nextInt();
//checking input condition
if(input>=1 &&input<=10){
//if satisfied return input
return input;
}
//else recursively ask for the input
else{
System.out.print("Please enter between 1 and 10 ");
return ask_input();
}
}
}
Editor:
Hope this helps you! If you still have any doubts or queries please feel free to comment in the comment section.
"Please refer to the screenshot of the code to understand the indentation of the code".
Thank you! Do upvote.