一、if语句练习
判断当前的天气,当外面下雨的时候:带雨伞然后判断性别,如果性别是男带一个黑伞,如果性别是女带一把花伞; 当外边使晴天的时候:判断天气的温度:如果天气在30度以上,性别为男戴墨镜,性别为女带防晒霜。(**注意:equals和==区别**)
public class Test1 {
public static void main(String[] args) {
System.out.println("请输入今天天气情况:下雨or晴天");
Scanner s = new Scanner(System.in);
String a = s.next();
if (a.equals("下雨")) {
System.out.print("请输入您的性别:");
Scanner s1 = new Scanner(System.in);
String b = s1.next();
if (b.equals("男")) {
System.out.println("带一把大黑伞");
} else {
System.out.println("带一把小红伞");
}
} else {
System.out.print("请输入天气温度:");
Scanner s2 = new Scanner(System.in);
int c = s2.nextInt();
if (c > 30) {
System.out.print("请输入您的性别:");
Scanner s3 = new Scanner(System.in);
String d = s3.next();
if (d.equals("男")) {
System.out.println("戴墨镜");
} else {
System.out.println("带防晒霜");
}
}
}
}
}
二、switch语句练习(实现计算器当中两位数的±*/%)
public class Test2 {
public static void main(String[] args) {
System.out.println("请输入第一个数字");
Scanner s1 = new Scanner(System.in);
int a = s1.nextInt();
System.out.println("请输入运算符");
Scanner s2 = new Scanner(System.in);
String b = s2.next();
System.out.println("请输入第二个数字");
Scanner s3 = new Scanner(System.in);
int c = s3.nextInt();
int d;
switch (b) {
case "+":
d = a + c;
System.out.println(a + "+" + c + "=" + d);
break;
case "-":
d = a - c;
System.out.println(a + "-" + c + "=" + d);
break;
case "*":
d = a * c;
System.out.println(a + "*" + c + "=" + d);
break;
case "/":
d = a / c;
System.out.println(a + "/" + c + "=" + d);
break;
case "%":
d = a % c;
System.out.println(a + "%" + c + "=" + d);
break;
default:
break;
}
}
}
三、for循环练习(判断100以内的数是否是素数)
public class Test3 {
public static void main(String[] args) {
int d = 0;
int a = 3;
for (a = 3; a <= 100; a++) {
boolean c = false;
for (int j = 2; j < (a - 1); j++) {
if ((a % j) == 0) {
c = true;
break;
}
}
if (c) {
System.out.println(a + "不是素数");
} else {
System.out.println(a + "是素数");
d++;
}
}
//因为1和2没有办法根据上述判断且1和2为素数所以(d+2)
System.out.println("100以内的素数有" + (d + 2) + "个");
}
}
本代码均为自己手写,如有错误,欢迎指出,不胜感激!