Dan Mallon
Dan Mallon

Reputation: 11

java while loops with strings

I am trying to make a loop that prints "*" as a string a certain number of times, but I can't get it to work. Everything in the main method was given to me and must be used. Everything else I added and I don't know if I am on the right track or not. The end result is suppposed to print "*" seven times horizontally. Then each time it adds a "*", adds one to count, and compares to see if count is greater than or equal to the value I set. Then if it is true it ends the loop and if not it repeats the loop until true. I just don't know how express this in code.

    public class LoopPractice
    {
        public String ast = "*";    

        public static void main(String[] args)
        {

            LoopPractice lp = new LoopPractice();
            System.out.println(lp.getAstWhile(7));
        }   

        public String getAstWhile()  
        {
            int count = 0;
            while (count <= 6)
            {
                System.out.print(count++);
            }
            return ast;
        } 
    }

Upvotes: 1

Views: 211

Answers (2)

Sammy
Sammy

Reputation: 477

Use a StringBuffer.

public String getAstWhile()  
    {
        StringBuffer buf = new StringBuffer();
        int count = 0;
        while (count <= 6)
        {
            buf.append('*');
            count++;
        } 
        return buf.toString();
    } 

getAstWhile was not returning a String in your original code.

API documentation: http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html Tutorial on StringBuffer: http://www.tutorialspoint.com/java/java_string_buffer.htm

Upvotes: 0

Eliseo
Eliseo

Reputation: 416

You are passing a value "7" to a function that accepts no values, call lp.getAstWhile(); instead of lp.getAstWhile(7);

public String getAstWhile(int maxValue)
{ 
     int count = 0; 
     while (count < maxValue) 
     { 
         system.out.print(count++); 
      } 
}

Upvotes: 1

Related Questions