一、用户交互Sanner
想写出功能强大的程序不能只靠计算机的输出,人机交互是构成完整程序的重要部分。Java中的Scanner函数就承担了交互的功能,下面来进行详细的分析:
Scanner的输入有两种形式:next();和nextLine();
1、next();
a)不能得到带有空格的字符串;
b)只有输入有效字符之前遇到的空白,next()方法会自动将其去掉。
2、nextLine();
a)可以获得空白;
b)以Enter为结束符,nextLine();返回回车之前所有的值。
public static void main(String[] args) {
//创建一个扫描器对象,用于接收键盘的数据
Scanner scanner = new Scanner(System.in);
//提示性语句
System.out.println("请输入任意字符串:");
//以nextLine();形式接受
String str = scanner.nextLine();
//以next();形式接受
String Str =scanner.next();
System.out.println(str);
System.out.println(Str);
scanner.close();//关闭,IO流如果不关闭将会一直占用内存。
}
假设输入的字符串为“hello world”,当以next()形式接受时,输出的结果为:hello
当以nextLine()形式接受时,输出的结果为:hello world。
二、Java中常用的结构
1、顺序结构:Java中最基本的结构,代码从上到下一步步地执行。在这里不做详细解释。
2、选择结构
①if单选择结构:
if(条件表达式){
........语句
}
②if双选择结构:
if(条件表达式){
......语句1
}else{
......语句2
}
*流程图如下:
③if多选择结构:
if(条件表达式1){
......语句1
}else if(条件表达式2){
......语句2
}else if(条件表达式){
......语句3
}...else{
}
*流程图如图:
④if嵌套结构:
if(条件表达式){
if(条件表达式2){
}
.
n....
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int score= scanner.nextInt();
if(score<60){
System.out.println("不及格");
} else if (score>=60) {
System.out.println("及格");
}else{
System.out.println("输入错误!");
}
}
⑤switch多选择结构:
switch(选择对象){
case value:
语句
break; //要加break,防止case穿透发生
case value:
语句
break;
case value:
语句
break;
default:
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int score= scanner.nextInt();
switch (score){
case 1:
System.out.println("优秀!");
break;
case 2:
System.out.println("还行");
break;
case 3:
System.out.println("辣鸡");
break;
default:
System.out.println("输入不合法!");
}
}
3、循环结构
①while循环:
while(条件语句){
循环内容:
}
②do..while循环:
do{
代码语句
}while(条件表达式);
③for循环:
for(初始化;表达式;更新){
代码语句
}
*练习:计算1+2+3+4+...+100=?
a) By while循环:
public static void main(String[] args) {
int i=0;
int sum=0;
while(i<=100){
sum+=i;
i++;
}
System.out.println(sum);
}
b)By do...while循环:
public static void main(String[] args) {
int i=0;
int sum=0;
do {
sum+=i;
i++;
}while(i<=100);
System.out.println(sum);
}
c)By for循环:
public static void main(String[] args) {
int sum=0;
for(int i=0;i<=100;i++){
sum+=i;
}
System.out.println(sum);
}
*④增强for循环:
for(声明语句:表达式){
表达式...
}
public static void main(String[] args) {
int[]arry={10,20,30,40,50};
for(int x:arry){
System.out.println(x);
}
}
增强for循环用于简化输出数组的值,只适用于数组,属于偷懒的代码。