java条件选择学习

时间:2022-10-06 17:38:29

boolean类型用于声明布尔型变量,只能是true或false中的一个

boolean lightOn = true;

一个简单的数学学习工具:

public class Main
{
public static void main(String args[])
{
int num1 = (int)(System.currentTimeMillis() % 10); //产生随机数1
int num2 = (int)(System.currentTimeMillis() * 7 % 10); //产生随机数2
Scanner input = new Scanner((System.in));
System.out.print("What is " + num1 + " + " + num2 + "? ");
int ans = input.nextInt();
System.out.println(num1 + " + " + num2 + " = " + ans + " is " + (num1 + num2 == ans)); }
}

格式化控制台输出:

如果希望浮点值小数后两位,那么可以编写如下代码:

double x = 2.0 / 3;
System.out.println((int)(x * 100) / 100.0);

但是使用printf更好的控制,printf的使用和C语言相似,多了布尔值的格式控制“%b”

编程练习:

1、解一元二次方程

public class Main
{
public static void main(String args[])
{
double a, b, c, ans;
Scanner input = new Scanner(System.in);
System.out.print("Enter a, b, c:");
a = input.nextDouble();
b = input.nextDouble();
c = input.nextDouble();
ans = 0.0;
double delta = b * b - 4 * a * c;
if(delta > 0) {
double x1, x2;
x1 = (-1 * b + Math.pow(delta, 0.5)) / (2 * a);
x2 = (-1 * b - Math.pow(delta, 0.5)) / (2 * a);
System.out.println("The roots are " + x1 + " and " + x2);
} else if(delta == 0) {
double x;
x = -1 * b / (2 * a);
System.out.println("The root is " + x);
} else {
System.out.println("The equation has no real roots");
}
}
}

2、输入一个整数,判断它是不是偶数

Scanner input = new Scanner(System.in);
int n = input.nextInt();
System.out.printf("Is %d an even number? %b", n, (n % 2 == 0));