Java程序控制语句、字符串与数组

程序控制语句

1. 判断

if

if...else

编程:定义整数变量x,赋值为10,判断x的奇偶,如果是奇数在控制台打印“奇数”,否则打印“偶数”

public class Item0101 {
/**
* @param args
*/
public static void main(String[] args) {
int x=10;
if(x%2==0){
System.out.println("x是偶数");
}else{
System.out.println("x是奇数");
}
}
}
if...else if
switch...case(break)

编程: 定义一个变量x,赋值为2,根据x的值显示,如果x为0,在控制台显示“退出系统?”,如果x为1,显示“请输入用户名及密码:”,如果x为2,提示“Please input your name and password:”,其他显示“请输入0/1/2”。

public static void main(String[] args) {
int x=2;
switch(x){
case 0:
System.out.println("你将退出系统");
case 1:
System.out.println("请输入用户名及密码:");
case 2:
System.out.println("Pls input your name and password");
default:
System.out.println("请按照提示选择1/2/3进行操作");
}
}

2. 循环

for

编程:计算数字1-10的和。

public static void main(String[] args) {
int r=0;
for(int i=1;i<=10;i++){
r=r+i;
}
System.out.println(r);
}
while
do...while

3. 跳转

goto(不再使用)

作业:控制语句

题目:判断10-105之间有多少个素数,并输出所有素数。【素数又称为质数,定义为在大于1的自然数中,除了1和它本身以外不再有其他因数的数】

求1-100之间,有哪些数是完数。【完全数(Perfect number),又称完美数或完备数,是一些特殊的自然数。它所有的真因子(即除了自身以外的约数)的和(即因子函数),恰好等于它本身。例如:6=1+2+3】

题目:判断一个整数是几位数,并按照逆序输出。

字符串

概念

声明一个字符串

String a="Hello world!";
String a=new String("Hello world!");

不可变性

Immutable,一旦被创建以后,这个字符串值就被存在了 __ 常量池 __ 中,它的值就不会改变,修改字符串就是新建一个新的值。

请看下面的例子,判断s2、s3,s4、s5是否相等。

String s2="Hello";
String s3="Hello";
String s4=new String("Hello");
String s5=new String("Hello");

s2等于s3

s4不等于s5

Java传值的方式

Java中只有值传递。

String的常见方法

+:连接两个字符串

例:

public static void main(String[] args) {
String s1="Hello";
String s2="world";
System.out.println(s1+s2);
}

subString:截取

例:

public static void main(String[] args) {
String s="Hello world!";
System.out.println(s.substring(3));
System.out.println(s.substring(3, 6));
}

indexOf:索引

例:

public static void main(String[] args) {
String s="Hello world";
String searchContent="lo";
int i=s.indexOf(searchContent);
if(i>0){
System.out.println("lo在"+i+"个位置");
}
}

equals:判断相等

例:

public static void main(String[] args) {
String s1="Hello world";
String s2="Hello world";
System.out.println(s1==s2);
String s3=new String("Hello world");
String s4=new String("Hello world");
System.out.println(s3.equals(s4));
}

作业

数组

概念

用于将相同类型的数据存储在连续的存储单元中。

可以通过指定数组的名称和长度来声明数组。

数组一旦声明了大小,就不能再修改。

通过数组名和索引来访问,索引从 0 开始,如:array[0]

数组可以是1维的也可以是多维的。

数组声明

int[] array=new int[10];
int array[10]= new int[10];
int[] array={1,2,3,4};

数组长度

数组自带length属性记录了数组的长度。

如果数组下标越界,程序会抛出错误。

数组常用方法

需要使用Apache Common Lang包