学习java的条件_java条件选择学习

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));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值