Intro to Java Programming(Liang.10th)--03

本文深入探讨了Java编程中的关键概念,包括布尔数据类型、随机数生成、逻辑运算符、条件表达式、操作符优先级及开关语句等。通过实例讲解,如计算身体质量指数和减法测验,帮助读者理解如何使用嵌套if语句和switch语句进行条件判断和流程控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

3.1 Introduction

The program can decide which statements to execute based on a condition
Boolean value: true or false.

3.2 boolean Data Type

The boolean data type declares a variable with the value either true or false.

//3.2.1
boolean b = true;
i = (int)b;
int i = 1;
boolean b = (boolean)i;

代码段3.2.1不可行,cannot csat from boolean to int.

3.7 Generating Random Numbers

You can use Math.random() to obtain a random double value between 0.0 and 1.0,
excluding 1.0.

import java.util.Scanner;

 public class SubtractionQuiz {
 public static void main(String[] args) {
 // 1. Generate two random single-digit integers
 int number1 = (int)(Math.random() * 10);
 int number2 = (int)(Math.random() * 10);

 // 2. If number1 < number2, swap number1 with number2
 if (number1 < number2) {
 int temp = number1;
  number1 = number2;
 number2 = temp;
 }

 // 3. Prompt the student to answer ”What is number1 – number2?”
 System.out.print
 ("What is " + number1 + " - " + number2 + "? ");
 Scanner input = new Scanner(System.in);
 int answer = input.nextInt();

 // 4. Grade the answer and display the result
 if (number1 - number2 == answer)
 System.out.println("You are correct!");
 else {
 System.out.println("Your answer is wrong.");
 System.out.println(number1 + " - " + number2 +
 " should be " + (number1 - number2));
 }
 }
 }

3.8 Case Study: Computing Body Mass Index

You can use nested if statements to write a program that interprets body mass index.

3.10 Logical Operators

The logical operators !, &&, ||, and ^ can be used to create a compound Boolean
expression.

3.13 switch Statements

A switch statement executes statements based on the value of a variable or an
expression.

3.14 Conditional Expressions

A conditional expression evaluates an expression based on a condition.

if (x > 0)
y = 1;
else
y = -1;

Alternatively, as in the following example, you can use a conditional expression to achieve
the same result

y = (x > 0) ? 1 : -1;
System.out.println((num % 2 == 0) ? "num is even" : "num is odd");

3.15 Operator Precedence and Associativity

Operator precedence and associativity determine the order in which operators are
evaluated.

3.16 Debugging

Debugging is the process of finding and fixing errors in a program.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值