Java and conditional loop

Java is a very popular web-side development language, conditional and looping constructs is a very important part of Java, Java following a brief usual conditional and looping constructs.

Conditional statement

if the judge sentences

public class Demo {
	public static void main(String[] args) {
			if (/*判断条件*/) {
				// 逻辑代码块
			}
	}
}

determining if-else statements

public class Demo {
	public static void main(String[] args) {
		if (/*条件判断*/) {
			// 逻辑代码块
		} else {
		 	// 逻辑代码快
		}
	}
}

if-else if-else statement Analyzing

public class Demo {
	public static void main(String[] args) {
		if (/*条件判断*/) {
			// 逻辑代码块
		} else if(/*条件判断*/) {
		 	// 逻辑代码块
		} else {
			// 逻辑代码块
		}
	}
}

switch-case

We are here to write a simulation of a system of ordering

  • switch-case supported data types are:
  • Basic data types: byte, short, int, char
  • Packaging data types: Byte, Short, Character, Integer
  • Enumerated types: Enum
  • String type: String (jdk1.7 began to support)
  • Precautions:
    1. switch case statement must end with a break statement, otherwise the program will continue to be performed until the execution to break statements or}.
    2. switch-case selection structure, code only allowed to write in the switch-case and write it in other places, there will be an error.
    3. default dispensable, but only one default
import java.util.Scanner;

public class Demo {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("欢迎进入点餐系统,请尽情的点菜吧!!!");
		menu();
		int num = sc.nextInt();
		int price = price(num);
		System.out.print(price);
	}

	/**
	* 输出一个菜单
	*/
	public static void menu() {
		System.out.print("1. 红烧羊排 50rmb");
		System.out.print("2. 土豆丝 10rmb");
		System.out.print("3. 空心菜 15rmb");
		System.out.print("4. 红烧鱼 30rmb");
		System.out.print("5. 红烧肉 20rmb");
		System.out.print("6. 下单");
	}
	
	/**
	* 返回用户下单的总价
	*
	* @param num 用户输入的指令
	*/
	public static int price(int num) {
		int price = 0;
		while (true) {
			switch (num) {
			case 1:
				price += 50;
				break;
			case 2:
				price += 10;
				break;
			case 3:
				price += 15;
				break;
			case 4:
				price += 30;
				break;
			case 5:
				price += 20;
				break;
			default:
			    price += 0;
			    break;
			}
			if (num == 6) {
				break;
			}
		}
		return price;
	}
}

Loop structure

while loop

public class Demo {
	public static void main(String[] args) {
		while (/*判断条件*/) {
			// 逻辑代码块
		}
	}
}

do-while loop

This loop will execute the first time

public class Demo {
	public static void main(String[] args) {
		while (/*判断条件*/) {
			// 逻辑代码块
		}
	}
}

for loop

public class Demo {
	public static void main(String[] args) {
		for (/*变量初始化*/;/*循环条件判断*/;/*变量变更*/) {
			// 逻辑代码块
		}
	}
}
Released seven original articles · won praise 3 · Views 279

Guess you like

Origin blog.csdn.net/justLym/article/details/104227133