HW1-1: Java Exercises - Solutions
1. JOptionPane Example
import [Link];
public class TestDialog {
public static void main(String[] args) {
float num = 3.14f;
[Link](null, "Hello! The number is: " + num);
}
}
This program displays a message and a floating point number in a dialog box.
2. [Link] Example
public class TestPrint {
public static void main(String[] args) {
float num = 3.14f;
[Link]("Hello! The number is: " + num);
}
}
This program prints a message and a floating point number on the console.
3. Format Output in Java vs C++
public class TestFormat {
public static void main(String[] args) {
double x = 3.65782;
[Link]("Java formatted: %.2f%n", x);
}
}
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double x = 3.65782;
cout << fixed << setprecision(2);
cout << "C++ formatted: " << x << endl;
return 0;
}
Both Java and C++ allow formatting floating point numbers with 2 decimal places.
4. Modulus Operator Analysis
- In Java:
- (-5 % -2) = -1
- (-5 % 2) = -1
- (5 % -2) = 1
Reason: The result of modulus has the same sign as the dividend (left operand).
5. Javadoc Description Example
/**
* The Calculator class provides methods to perform basic arithmetic operations.
* @author Student
* @version 1.0
*/
public class Calculator {
/**
* Adds two integers.
* @param a first number
* @param b second number
* @return sum of a and b
*/
public int add(int a, int b) {
return a + b;
}
}
Run 'javadoc [Link]' to generate the documentation.
Original Task Screenshot: