123k views
0 votes
Given a variable n that is associated with a positive integer and a variable s that is associated with the empty string, write some statements that use a while loop to associate s with a string consisting of exactly n asterisks (*) . (So if n were associated with 6 then s would, in the end, be associated with "******" .

1 Answer

1 vote

Answer:

//Scanner class is imported to allow the program receive user input

import java.util.Scanner;

//Class Solution is created

public class Solution {

// The main method which is the beginning of program execution

public static void main(String args[]) {

//Scanner object 'scan' is created to accepted user input from the keyboard

Scanner scan = new Scanner(System.in);

//A prompt is displayed to the user to enter a positive number

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

//User input is stored as variable n

int n = scan.nextInt();

// An empty string is assigned to s

String s = "";

// Beginning of while loop

// The loop begin while n is a positive number

while(n > 0){

//s is concatenated with *

s+= "*";

// the value of n is reduced.

n--;

}

// The value of the string s is displayed to the screen

System.out.println(s);

}

}

Step-by-step explanation:

First the Scanner class is imported, then the class Solution is created. Inside the main method, a prompt is first displayed to the user to enter a positive number. After that, a scanner object scan is created to receive the user input and assigned to n. An empty string is assigned to s.

Then the while loop repeat for each value of n greater than 0 and concatenate "*" to s.

Finally, the value of s is displayed to the user.

User Khituras
by
7.1k points