java控制程序流程

/**
 * 
 * 控制程序流程
 */
public class ControlFlow
{
	/**目标数字*/
	public static int TAGEET_NUMBER = 10;
	
	/**
	 * 通过if条件语句和递归方法将n
	 * 的值逐步变成TAGEET_NUMBER
	 * @param n
	 */
	public void ifstatement(int n)
	{
		System.out.print(n + " ");
		if(n == TAGEET_NUMBER)
		{
			System.out.println();
		}
		else if(n < TAGEET_NUMBER)
		{
			this.ifstatement(++n);
		}
		else
		{
			this.ifstatement(--n);
		}
	}
	
	/**
	 * 通过for循环语句将n的值逐步变成TAGEET_NUMBER
	 * @param n
	 */
	public void forstatement(int n)
	{
		for(;n>TAGEET_NUMBER;n--)
		{
			System.out.print(n + " ");
		}
		for(;n<TAGEET_NUMBER;n++)
		{
			System.out.print(n + " ");
		}
		System.out.println(n);
	}
	
	/**
	 * 通过while循环语句将n的值逐步变成TAGEET_NUMBER
	 * @param n
	 */
	public void whilestatement(int n)
	{
		while(n > TAGEET_NUMBER)
		{
			System.out.print(n-- + " ");
		}
		while(n < TAGEET_NUMBER)
		{
			System.out.print(n++ + " ");
		}
		System.out.println(n);
	}
	
	/**
	 * 通过do...while循环语句将n的值逐步变成TAGEET_NUMBER
	 * @param n
	 */
	public void dowhilestatement(int n)
	{
		if(n>TAGEET_NUMBER)
		{
			do
			{
				System.out.print(n-- + " ");
			}
			while (n > TAGEET_NUMBER);
		}
		else if(n < TAGEET_NUMBER)
		{
			do
			{
				System.out.print(n++ + " ");
			}
			while(n < TAGEET_NUMBER);
		}
		System.out.println(n);
	}
	
	/**
	 * switch....case选择语句示例
	 * @param n
	 */
	public void switchcasestatement(int n)
	{
		switch (n) {
		case 10:
			System.out.println("n=10");
			break;
		case 9:
			System.out.println("n=9");
			break;
		case 8:
			System.out.println("n=8");
			break;
		default:
			System.out.println("n!=8且n!=9且n!=10");
			break;
		}
	}
	
	public static void main(String[] args)
	{
		ControlFlow test = new ControlFlow();
		int n =0 ;
		System.out.println("ifstatement方法输出:");
		test.ifstatement(n);
		System.out.println("forstatement方法输出:");
		test.forstatement(n);
		System.out.println("whilestatement方法输出:");
		test.whilestatement(n);
		System.out.println("dowhilestatement方法输出:");
		test.dowhilestatement(n);
		System.out.println("switchcasestatement方法输出:");
		test.switchcasestatement(n);
	}
}

你可能感兴趣的:(java)