Java 基础学习笔记(第五篇)
- 控制台输入(使用标准输入串System.in,使用Scanner取得一个字符串或一组数字)
在新增一个Scanner对象时需要一个System.in对象,因为实际上还是System.in在取得用户输入。Scanner的next()方法用以 取得用户输入的字符串;nextInt()将取得的输入字符串转换为整数类型;同样,nextFloat()转换成浮点型;nextBoolean()转 换成布尔型。
例: System.out.print(“输入”);
Scanner scan = new Scanner(System.in);
String read = scan.next ();
System.out.println(“输入数据:”+read);
(ps: 在使用Scanner对象时,需要在文件头带入 java.util.Scanner; 写法为: import java.util.Scanner;)
import java.util.Scanner;
//在使用Scanner包时,需要在函数头引入java.util.Scanner文件
public class Input_dome {
public static void main(String[] args) {
System.out.print("请输入年龄:");
//创建一个Scanner对象,传入一个输出流对象
Scanner scan = new Scanner(System.in);
//使用Scanner取得一个字符串或者一组数字
int age = scan.nextInt();
System.out.print("请输入姓名:");
String name = scanner.next();
System.out.println("姓名:" + name + " " + "年龄:" + age);
}
}
- 控制语句
- 条件语句(根据条件的不同,执行不同的语句)
- if( ) {}
- if() {} else{}
- if() {} else if() {}
- if() {} else if(){} …else if(){}else
- switch()
import java.util.Scanner;
public class If_Dome {
public static void main(String[] args) {
/*
if( ) {}
*/
boolean a = true;
if (a == true) {
System.out.print("TRUE");
}
/*
if() {} else{}
*/
if (a == true) {
System.out.print("TRUE");
} else {
System.out.println("FLASE");
}
/*
if() {} else if() {}
*/
if (a == true) {
System.out.print("TRUE");
} else if (a == false) {
System.out.println("FLASE");
}
/*
if() {} else if(){} ........else if(){}else
*/
int b = 85;
if (b >= 90) {
System.out.println("优秀");
} else if (b < 90 && b >= 70) {
System.out.println("良好");
} else if (b < 70 && b >= 60) {
System.out.println("及格");
} else if (b < 60 && b >= 0) {
System.out.println("不及格");
} else {
System.out.println("非法输入");
}
/*
switch(){}
*/
System.out.println("请输入您要执行的操作:1、叫爸爸,2、叫妈妈,3、叫爷爷,4、叫奶奶");
Scanner scanner = new Scanner(System.in);
int s = scanner.nextInt();
switch(s){
case 1:
System.out.println("我是你爸爸");
break;
case 2:
System.out.println("我是你妈妈");
break;
case 3:
System.out.println("我是你爷爷");
break;
case 4:
System.out.println("我是你奶奶");
break;
default:
System.out.println("脑残吗?有这个选项吗?");
break;
}
}
}
2.循环语句(重复执行某些动作)
- for() {}
- while() {}
- do{}…while(){}
public class While_Dome {
public static void main(String[] args) {
/*
while(){}
*/
int i = 1;
int fac = 1;
while (i<=4){
fac*=i;
i++;
}
System.out.println(fac);
//while死循环
while (true){
System.out.println("死循环");
}
//死循环
for (;;){
System.out.println("死循环");
}
/*
do{}.....while(){}
*/
do{
System.out.println("真特么好啊!");
i++;
}while(i<=100);
}
}
- break & continue
break 语句用于终止某个语句块的执行。用在循环语句体中,可以强行退出循环
continue 语句用在循环语句体中,用于终止某次循环过程,跳过循环体中 continue 语句下面未执行的循环,开始下一次循环过程 - 循环嵌套
将一个循环放在另一个循环体内,就形成了嵌套循环。其中,for ,while ,do…while均可以作为外层循环和内层循环。实质上,嵌套循环就是把内层循环当成外层循环的循环体。当只有内层循环的循环条件为false时,才会完全跳出内层循环,才可结束外层的当次循环,开始下一次的循环。如果需要从多层循环跳出,则需要使用标签,定义一个标签,如label,然后在需要跳出的地方,用break label就行了 - return 语句
return语句用于从当前执行的方法中退出, 返回到调用该方法的语句处继续执行。
有两种格式:1.return 表达式; //将表达式的值返回 2.return; //不返回任何值,当方法说明中用void声明无返回值时, 可以使用这种格式,此类return语句有时可省略