1丶if语句
比较两数的大小
import java.util.Scanner;
public class Demo2 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
maxTwo(a,b);
}
public static int maxTwo(int a,int b){
if(a<b){
System.out.println("a<b");
}else{
System.out.println("a>b");
}
return a>b ? a:b;
}
}
(1)if语句中的条件表达式可以是关系表达式丶逻辑表达式丶算术表达式等。
(2)语句/语句块可以是单个语句,也可以是多个语句。如果要执行多个语句,则需要使用花括号{}把这些语句组合为一个代码块。
2丶for语句
求1-10的和
public class Demo2 {
public static void main(String[] args) {
sum1(10);
}
public static void sum1(int n){
int sum = 0;
for (int i = 0; i < n; i++) {
sum +=i;
}
System.out.println(sum);
}
}
for语句的格式:for(初始化设置表达式;循环执行条件;循环变量的增减量){循环语句序列}
3丶switch语句
public class Demo2 {
public static void main(String[] args) {
char ch = 'A';
fun(ch);
}
public static void fun(char ch) {
switch (ch) {
case 'A':
System.out.println("80-100");
break;
case 'B':
System.out.println("60-80");
break;
case 'C':
System.out.println("<60");
break;
default:
System.out.println("不及格");
break;
}
}
}
switch(控制表达式){
case(常量表达式)1;
语句序列1
break;
case(常量表达式)2;
语句序列2
break;
:
case(常量表达式)n;
语句序列n
break;
default;
语句序列n+1
break;
}
作业
1丶求斐波拉契数列的前40项和
public static void fSum(){
int[] f= new int[40]; //定义出长度为40的数组
f[1] = 1;
f[0] = 1;
long sum = 0;
for(int i = 2;i < f.length;i++)
f[i] = f[i-2] + f[i-1]; //依次求出斐波那契数列后38项
for(int i = 0;i < f.length;i++){
sum = sum + f[i]; //对前40项求和
}
System.out.println("斐波那契数列前40项和为: "+sum);
}
2丶用for循环产生20个随机数(10-20)
public static void sJs(){
System.out.println("产生的随机数为");
for(int i = 1;i <= 20;i++){
double a=Math.random()*(20-10)+10; //调用Math.random方法,在10到20间产生随机数
System.out.println(a);
}
}
3丶输入一个数字,求它是几位数,并且顺序输出,逆序输出
public static int sZ(long x){
long save=0;
int b=0;
System.out.println(x); //顺序输出该数
while(Math.abs(x) % 10 > 0 || x / 10 != 0){ //调用绝对值函数
System.out.println("逆序输出为"+x % 10);//逆序输出该数
b++; //如果满足判别条件,则b+1
x = x / 10; //除以10再入循环
}
return b; //返回b的值,即为位数
}
4丶求一个数字的二进制数有几个1
public static int del(int n) {
int cout = 0;
while (n != 0) { //当输入数字不为0时进入循环
cout++; //只要该数不为0,则先记一个1,而后再有1时继续count++
n = (n - 1) & n; //按位与运算,直到这个数的二进制中的1都变为0为止
}
return cout;
}