Check out these links:
Basic tutorial on the for statement
The while and do-while statements
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* Uses scanner to ask user for a number [n] and a character input [c]. Outputs
* the character input [c], [n] times to console.
*
* @author Zobit
*
*/
public class Main
{
Scanner scan;
char c;
int n;
/**
* Constructor. Necessary to initialize the field variables and to work with
* the class in a non-static context.
*/
public Main()
{
scan = new Scanner(System.in); // System.in for console input.
c = 0;
n = 0;
}
/**
* Nothing special. Just the main method to execute our program
*
* @param args
*/
public static void main(String[] args)
{
Main m = new Main();
m.performPrintLoop();
}
// Public access method. Ensures all methods are called in correct order.
// Added in case we want to use this functionality outside of the class in
// the future
public void performPrintLoop()
{
askForNumber();
askForCharacter();
printLoop();
}
/**
* Uses a while-loop to get a number input from the user.
*/
private void askForNumber()
{
boolean hasNumber = false;
// while-loops run continually until their condition is no longer valid.
// Our condition states while not hasNumber, which was set to false, so
// by default it will be running as soon as the method has been invoked.
while (!hasNumber)
{
// Use a try-catch in case of bad user input.
try
{
System.out.println("Please input a non-decimal positive number greater than 0");
n = scan.nextInt();
if (n <= 0)
throw new InputMismatchException();
hasNumber = true;
} catch (InputMismatchException e)
{
scan.nextLine(); // advance the scanner past bad input
}
}
}
/**
* Same logic as askForNumber, but try to get a character.
*/
private void askForCharacter()
{
boolean hasCharacter = false;
while (!hasCharacter)
{
try
{
System.out.println("Please input a single character");
String in = scan.next();
if (in.length() > 1)
throw new InputMismatchException();
c = in.charAt(0);
hasCharacter = true;
} catch (InputMismatchException e)
{
scan.nextLine();
}
}
}
/**
* A simple for-loop to print out the character c, n times.
*/
private void printLoop()
{
System.out.println("Printing \"" + c + "\" " + n + " times\n\n");
for (int i = 0; i < n; i++)
{
System.out.println(c);
}
}
}