Michał Bała
Michał Bała

Reputation: 45

how to print number of stars depending on user choose

I've been trying practiceIt problems and expand them a little - and I'm stuck. The code will give results in as many stars as it's necessary, but I do not know how to make user decide the value for n.

I've tried adding to both methods (main/starString) those code lines: "Scanner input = new.Scanner(System.in); int n = input.next();" [also input.nextInt]

but the code will note allow any input from console. Not to mention I've got no idea where shoud I add second println command to actually print result from this code... help me please

import java.util.*;
public class printStars {

    public static void main(String[]args) {

        System.out.println("choose number and I wil show you 2^number stars");

    }
        public static String starString(int n) {
            if (n < 0) {
                throw new IllegalArgumentException();
            } else if (n == 0) {
                return "*";
            } else {
                return starString(n - 1) + starString(n - 1);
            }
        }
}

Upvotes: 1

Views: 2566

Answers (2)

WJS
WJS

Reputation: 40062

You should also be checking the input before you enter the method. Here is one approach that allows for improper input and reprompts the user to enter the correct value. This way, no exceptions need be caught.


        Scanner in = new Scanner(System.in);
        String prompt = "Choose number (or a char to end) \nand I will show you 2^number stars: ";
        System.out.print(prompt);
        while (in.hasNextInt()) {
            int n = in.nextInt();
            if (n > 0) {
                System.out.println(starString(n));
            } else {
                System.out.print("Input must be greater than 0, try again: ");
                continue;
            }
            System.out.print(prompt);
        }
        System.out.println("Bye!");



        public static String starString(int n) {
            if (n == 0) {
                return "*";
            } else {
                return starString(n - 1) + starString(n - 1);
            }
        }

Upvotes: 0

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79395

Do it as follows:

import java.util.Scanner;

public class Main {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Choose number and I wil show you 2^number stars: ");
        System.out.println(starString(in.nextInt()));
    }

    public static String starString(int n) {
        if (n < 0) {
            throw new IllegalArgumentException();
        } else if (n == 0) {
            return "*";
        } else {
            return starString(n - 1) + starString(n - 1);
        }
    }
}

A sample run:

Choose number and I wil show you 2^number stars: 5
********************************

Upvotes: 1

Related Questions