0% found this document useful (0 votes)
3 views2 pages

HW1 Java Solutions

The document contains Java exercises with solutions, including examples of using JOptionPane for dialogs, printing to the console, formatting output in Java and C++, and analyzing the modulus operator. It also includes a Javadoc example for a Calculator class that performs basic arithmetic operations. Each exercise demonstrates different programming concepts and syntax in Java.

Uploaded by

Rachel Tan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

HW1 Java Solutions

The document contains Java exercises with solutions, including examples of using JOptionPane for dialogs, printing to the console, formatting output in Java and C++, and analyzing the modulus operator. It also includes a Javadoc example for a Calculator class that performs basic arithmetic operations. Each exercise demonstrates different programming concepts and syntax in Java.

Uploaded by

Rachel Tan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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:

You might also like