43.0k views
5 votes
TASK: Write a static method called repeatString that takes as input a String parameter word followed by an int parameter num. It should return a String that would be the result of repeating word exactly num times. If num is 0 or negative, the method should output an empty string.

HINT: Don't print out anything! Your method should return a string, not print it. print the output of your method behind the scenes to check that your method returns the right string; if you add your own print statements then the output won't be correct.


HINT: Make use of String concatenation!

1 Answer

2 votes

Answer:

Follows are the method definition to this question:

public static String repeatString(String word, int num)//defining a String method repeatString that takes two parameters

{

String Val= "";//defining String variable Val

for(int x = 0;x<num;x++)//defining for loop to calculate number of string

{

Val=Val+word;//hold calculated value in Val

}

return Val;//return Val value

}

Step-by-step explanation:

Follows are the full code to this question:

import java.util.*;//import package for user input

public class Main//defining class Main

{

public static String repeatString(String word, int num)//defining a String method repeatString that takes two parameters

{

String Val= "";//defining String variable Val

for(int x = 0;x<num;x++)//defining for loop to calculate number of string

{

Val=Val+word;//hold calculated value in Val

}

return Val;//return Val value

}

public static void main(String[] ar)//defining main method

{

int num;//defining integer variable

String word; //defining String variable

Scanner on=new Scanner(System.in);//creating Scanner class Object

System.out.print("Enter numeric value: ");//print message

num=on.nextInt();//input value

System.out.print("Enter String value: ");//print message

word=on.next();//input value

System.out.print(repeatString(word,num));//call method and print its return value

}

}

Output:

Enter numeric value: 3

Enter String value: data

datadatadata

Description:

Inside the main class, a static string method "repeatString" is defined that accepts two parameters "word and num", in which one is a string and one is an integer.

Inside the method, the string variable "Val" is defined, which uses the "for" loop to calculate the number of string and store its value in the variable.

In the main class, the above two variables are defined, that uses the Scanner class object for input the value and pass into the method and print its value.

User Stuartd
by
4.3k points