Untitled
unknown
plain_text
10 months ago
6.9 kB
8
Indexable
I'll break everything down for you step by step.
---
## **1. Formatted Output in Java (`printf`)**
Java provides `printf` (print formatted) to format output.
### **Basic Formatting Codes**
| **Code** | **Type** |
|-----------|---------|
| `%d` | Integer |
| `%f` | Floating point number (float/double) |
| `%s` | String |
| `%b` | Boolean |
| `%c` | Character (Unicode) |
| `%n` | New line |
### **Examples**
```java
String word = "Hello";
int number = 42;
// Output: I am printing Hello and 42
System.out.printf("I am printing %s and %d%n", word, number);
```
The `%s` replaces `word`, and `%d` replaces `number`.
---
## **2. Field Width and Alignment**
- A number after `%` specifies the **field width**.
- Default: **Right-aligned** with spaces added.
- Use `-` to **left-align**.
```java
System.out.printf("|%10s|%n", "Java");
// Output: | Java|
System.out.printf("|%-10s|%n", "Java");
// Output: |Java |
```
---
## **3. Formatting Numbers**
### **Flags**
| **Flag** | **Effect** |
|---------|------------|
| `+` | Forces sign (`+` for positive, `-` for negative) |
| `0` | Pads with zeros instead of spaces |
| `-` | Left-aligns the output |
| `,` | Adds commas in large numbers |
```java
int num = 12345;
System.out.printf("|%,d|%n", num); // Output: |12,345|
System.out.printf("|%010d|%n", num); // Output: |0000012345|
System.out.printf("|%+d|%n", num); // Output: |+12345|
```
---
## **4. Formatting Floating-Point Numbers**
By default, `printf` prints **6 decimal places**.
```java
double pi = 3.1415926535;
System.out.printf("%.2f%n", pi); // Output: 3.14
System.out.printf("%10.3f%n", pi); // Output: 3.142
System.out.printf("%-10.3f%n", pi); // Output: 3.142
```
- `.2f` → Rounds to **2 decimal places**.
- `10.3f` → **Width = 10**, **3 decimal places**.
- `-10.3f` → **Left-aligned**.
---
## **5. Printing Booleans**
```java
boolean isJavaFun = true;
System.out.printf("%b%n", isJavaFun); // Output: true
```
---
## **6. New Lines**
- **`\n`** → New line (Unix-style)
- **`%n`** → Platform-independent new line (recommended)
```java
System.out.printf("Hello%nWorld%n");
```
---
# **7. Rounding Numbers**
Java has built-in methods to round numbers.
### **Rounding to Nearest Integer**
```java
double num = 4.6;
System.out.println(Math.round(num)); // Output: 5
```
### **Rounding Down (`floor`)**
```java
System.out.println(Math.floor(4.9)); // Output: 4.0
```
### **Rounding Up (`ceil`)**
```java
System.out.println(Math.ceil(4.1)); // Output: 5.0
```
---
# **8. Generating Random Numbers**
Java provides `Math.random()` and the `Random` class.
### **Random Integer (0 to 9)**
```java
int randomNumber = (int)(Math.random() * 10);
System.out.println(randomNumber);
```
### **Using `Random` Class**
```java
import java.util.Random;
Random rand = new Random();
int num = rand.nextInt(100); // Random number from 0 to 99
System.out.println(num);
```
---
# **9. Constants and Type Conversions**
### **Declaring Constants**
Constants use the `final` keyword.
```java
final double PI = 3.14159;
```
### **Implicit Type Conversion (Widening)**
- **Smaller to bigger** → Automatic
```java
int num = 10;
double d = num; // int → double
System.out.println(d); // Output: 10.0
```
### **Explicit Type Conversion (Narrowing)**
- **Bigger to smaller** → Must **cast** manually
```java
double pi = 3.14159;
int roundedPi = (int) pi; // double → int
System.out.println(roundedPi); // Output: 3
```
### **Converting Strings to Numbers**
```java
String str = "50";
int x = Integer.parseInt(str);
System.out.println(x + 10); // Output: 60
```
### **Converting Numbers to Strings**
```java
int num = 42;
String strNum = Integer.toString(num);
System.out.println(strNum); // Output: "42"
```
---
This should cover **formatted output, rounding, random numbers, constants, and type conversions** in Java! Let me know if you need more explanations. 🚀
This looks like a whiteboard with key topics for a Java test. Here's a breakdown of what each topic likely covers and how you can prepare:
---
### **1. Outputs of `print` / `printf`**
- **`print`**: Prints text without moving to a new line.
- **`println`**: Prints text and moves to a new line.
- **`printf`**: Formats output (e.g., decimals, alignment).
🔹 **Example:**
```java
System.out.print("Hello");
System.out.print("World");
// Output: HelloWorld
System.out.println("Hello");
System.out.println("World");
// Output:
// Hello
// World
System.out.printf("Pi is %.2f%n", 3.14159);
// Output: Pi is 3.14
```
---
### **2. Given a program, find the error**
- Look for **syntax errors** (missing semicolons, incorrect variable names).
- Look for **logical errors** (wrong calculations, incorrect loops).
- Look for **runtime errors** (dividing by zero, null references).
🔹 **Example Error:**
```java
int x = "10"; // ❌ Type mismatch (String → int)
```
✅ **Fix:**
```java
int x = Integer.parseInt("10");
```
---
### **3. Rounding, Random Numbers, and Type Conversion**
#### **Rounding (`Math.round`, `Math.floor`, `Math.ceil`)**
- `Math.round(x)`: Rounds to the nearest integer.
- `Math.floor(x)`: Rounds **down**.
- `Math.ceil(x)`: Rounds **up**.
🔹 **Example:**
```java
System.out.println(Math.round(4.6)); // Output: 5
System.out.println(Math.floor(4.9)); // Output: 4.0
System.out.println(Math.ceil(4.1)); // Output: 5.0
```
#### **Random Numbers**
```java
import java.util.Random;
Random rand = new Random();
int num = rand.nextInt(10); // Random number from 0 to 9
System.out.println(num);
```
#### **Type Conversion**
```java
int num = 5;
double d = num; // Implicit conversion (int → double)
System.out.println(d); // Output: 5.0
double pi = 3.14;
int x = (int) pi; // Explicit conversion (double → int)
System.out.println(x); // Output: 3
```
---
### **4. Writing a Java Program**
You may need to write a simple program that:
- Uses `printf`
- Rounds numbers
- Generates a random number
- Converts between types
🔹 **Example:**
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
int randomNum = rand.nextInt(100); // 0-99
double pi = 3.14159;
System.out.printf("Random Number: %d%n", randomNum);
System.out.printf("Pi rounded to 2 decimal places: %.2f%n", pi);
}
}
```
---
### **5. `Math.ceil(x)`**
- Returns the **smallest** integer **greater than or equal** to `x`.
- Always rounds **up**.
🔹 **Example:**
```java
System.out.println(Math.ceil(4.1)); // Output: 5.0
System.out.println(Math.ceil(-3.7)); // Output: -3.0
```
---
### **How to Prepare**
✅ Review `printf` format codes
✅ Practice reading and debugging code
✅ Write small programs to test rounding and random numbers
✅ Understand `Math.ceil`, `Math.floor`, and `Math.round`
Let me know if you need extra help! 🚀Editor is loading...
Leave a Comment