攻城狮凌风

Java探索之旅(3)——选择与循环

1.选择结构与输出

   ❶Switch语句:

      Switch表达式必须算出 char,byte,short,int类型数值之一,总是括号括住;Value1----ValueN,对应有相同数据类型且为常量或者常量表达式(1+2,‘A’+2),不能包含变量(如1+x);

      从某个匹配语句开始向后执行。break和默认情况default可选

   ❷条件表达式:System.out.println((a>b)?:a:b);

   ❸格式化控制台输出Printf

         %b   布尔值                 %6b        输出布尔值,false前增加一个空格,true增加2个
         %c   字符                   %5c        输出宽度为5,即字符前添加4个空格
         %d   十进制                 %5d        同理,但若数字位数大于5,自动增加宽度
         %f   浮点数                 %10.2f     宽度为10,包括2位小数,即整数部分宽度为7,倘若不够,自动增加宽度
         %e   标准科学计数法         %10.2e     浮点条目宽度至少为10,含小数点,小数点后2位和指数部分。若宽度不够,增加空格
         %s   字符串                 %12s       宽度至少为12,可以自动增加宽度

    可以在标识符前置'-'表示左对齐,如%-10.2f。switch表达式和case常量表达式类型应该匹配,在格式字符串中倘若要输出%,应该使用%%。使用方法如:

System.out.printf("%8d%-8s%8.1e",1234,"JAVA",3856.7);

   布尔类型的值不能与其他类型数值相互转换  

   ❺随机数[0 1]产生函数,Math.random()

   ❻运算符优先级:“+,-”左结合(从左到右),所有之外的二元运算符右结合。运算符优先级如下:

后置运算符(++,--) > 前置运算符(++,--)> ! > 比较运算符(小于优先大于,开区间优先闭区间) > 逻辑运算符 > 赋值运算符

2.循环结构

    ❶循环结构中,不能用浮点数比较相等作为循环控制条件,因为浮点数均为近似。

    ❷while和for为pretest loop,先判断再执行,do-while则至少执行一步在循环。while和do-while一般用来控制迭代未知的情况,for则是控制已知较多。

    ❸break控制跳出循环体(包含break的内层循环体),continue则跳出本次循环。

3.GUI对话框

    首先 import javax.swing.JOptionPane

    ❶输入对话框,返回String:

String string=JOptionPane.showInputDialog(null,"Enter a double number","输入圆的半径",JOptionPane.QUESTION_MESSAGE)

    ❷显示对话框,不返回有效值: 

 JOptionPane.showMessageDialog(null"wlecom to Java","Display Window",JOptionPane_INFORMATION_MESSAGE

    ❸确认对话框,返回int,  0--yes,1-no, 2-cancel

int answer=JOptionPane.showConfirmDialog(null,"how do you do?")。 

4.Switch循环和GUI对话框测试

import java.util.Scanner;
import javax.swing.JOptionPane;
public class ChoiceStudy {
	public static void main(String[] args) 
	{
		//switch使用方法
		Scanner input=new Scanner(System.in);
		System.out.print("input a number---");
		byte data=input.nextByte();
		switch(data+1)
		{
		case 1*2:System.out.println("hello world");
		    break;
		case 2+1:System.out.println("Happy Coding");
		    break;
		default:
			System.out.println("Welcome to JAVA");
		}
		input.close();
		
		//GUI确认对话框
		int answer=JOptionPane.showConfirmDialog(null, "What a nice day!\n");
		if(answer==JOptionPane.YES_OPTION)//0
		     System.out.println("Love Life,love youself");
		else if(answer==JOptionPane.NO_OPTION)//1
		     System.out.println("No pains,No gains");
		
		//GUI之确认对话框,输入对话框,显示对话框
		//GUI对话框控制循环
		int option=JOptionPane.YES_OPTION;
		int sum=0;
		while(option==JOptionPane.YES_OPTION)
		{
			String intString=JOptionPane.showInputDialog(null,"Input an int value","Input Window",JOptionPane.QUESTION_MESSAGE);
			int number=Integer.parseInt(intString);
			sum+=number;
			option=JOptionPane.showConfirmDialog(null, "Continue Input?");
		}
		JOptionPane.showMessageDialog(null, "The sum of all Input number is\n "+sum,"Show Sum Window",JOptionPane.INFORMATION_MESSAGE);
		
	}
}

posted on 2014-10-23 10:36  攻城狮凌风  阅读(194)  评论(0编辑  收藏  举报

导航