PDA

View Full Version : Quick help with Java please.


Xenos
02-13-2008, 11:00 PM
Currently stuck on an assignment.

Basically

A request box opens and asks for a number
the user will then enter a number, and the code will then output the amount the user inputted, into asterisks (*)

for example

Input box:
Please enter a number: 10
Output:
*
**
***
****

How is this done please?

Thanks

brad211987
02-13-2008, 11:31 PM
You will need to be more specific, we don't do homework assignments, but are willing to help you with them. Post what you have so far, and where your problems are.

There are numerous ways that you can do this, as an idea you could:

initialize a counter to 1, and print that number of * on the line, then increment the counter for the next line, comparing its value to the user input each time.

Xenos
02-13-2008, 11:39 PM
I don't expect you guys to complete my course work for me, that is why I've not posted the assignment :P

I Just need help with a specific bit.

basically I need a public instance method called generateRow().
It takes an integer, it then outputs asterisks to the amount the user inputted.
At the moment I currently have:

public int generateRow()
{
int userInput;
String result;
result = "";
userInput = Integer.parseInt(OUDialog.request("Enter Number"));
for (int count = 0; count < userInput; count++)
{
result = result + "*";
}
System.out.println(result);
return this.row;
}

I dunno if this works or not, and I dunno how to test it neither :(

brad211987
02-14-2008, 05:10 PM
You are close to your desired behavior. Based on what you said, that it takes an integer and outputs a row based on that integer, this is what I would conclude.

The method should have a void return type, as it is only performing output to the screen. And it should take an integer argument, that it will use to determine its output.

Modified your code just a bit:


public void generateRow(int numberOfStars)
{
String result;
result = "";
for (int count = 0; count < numberOfStars; count++)
{
result = result + "*";
}
System.out.println(result);
}
The parts in bold are what has changed. The method no longer returns anything as it has a void return type, because it only produces output as I mentioned. The integer argument "numberOfStars" is what is passed in to the method to determine the output. I also removed the part that gets the input from the user. You should get input from the user in your main method, and then call this method using generateRow(userInput).

JygzIsHere
02-15-2008, 05:46 AM
public void generateRow()
{
int userInput;
String result;
result = "";
userInput = Integer.parseInt(OUDialog.request("Enter Number"));


int numberofstarsoutputted = 1;

while (numberofstarsoutputted <= userInput)
{
for(int counter=1; counter<=numberofstarsoutputted;counter++)
{
result += "*";
numberofstarsoutputted++;
}
result += "\n";
}
System.out.println(result);
}