├── .idea
├── .gitignore
├── Java book.iml
├── misc.xml
├── modules.xml
└── vcs.xml
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── I
├── fundamentals
│ ├── README.md
│ └── listings
│ │ ├── ApproximaterPi.java
│ │ ├── AreaPerimeterOfCircle.java
│ │ ├── AreaPerimeterOfRectangle.java
│ │ ├── ComputeExpression.java
│ │ ├── DisplayFiveMessages.java
│ │ ├── DisplayPattern.java
│ │ ├── DisplayThreeMessages.java
│ │ ├── PopulationProject.java
│ │ ├── PrintTable.java
│ │ ├── SimultaneousUsingCramerRule.java
│ │ ├── SummationOfSeries.java
│ │ ├── Welcome.java
│ │ ├── WelcomeWithThreeMessages.java
│ │ └── problems
│ │ ├── AverageSpeedInKilometers.java
│ │ ├── AverageSpeedInMiles.java
│ │ ├── ComputeExpression.java
│ │ ├── README.md
│ │ └── Resources
│ │ ├── 1.1.png
│ │ ├── 1.10.png
│ │ ├── 1.11.png
│ │ ├── 1.12.png
│ │ ├── 1.13.png
│ │ ├── 1.2.png
│ │ ├── 1.3.png
│ │ ├── 1.4.png
│ │ ├── 1.5.png
│ │ ├── 1.6.png
│ │ ├── 1.7.png
│ │ ├── 1.8.png
│ │ ├── 1.9.png
│ │ ├── 1112.png
│ │ ├── 14.png
│ │ ├── 56.png
│ │ └── 710.png
├── loops
│ ├── FutureTuition.java
│ ├── GreatestCommonDivisor.java
│ ├── GuessNumber.java
│ ├── GuessNumberOneTime.java
│ ├── MultiplicationTable.java
│ ├── Palindrome.java
│ ├── PrimeNumber.java
│ ├── README.md
│ ├── RepeatAdditionQuiz.java
│ ├── SentinelValue.java
│ ├── SubtractionQuizLoop.java
│ ├── TestBreak.java
│ ├── TestContinue.java
│ ├── TestDoWhile.java
│ ├── TestSum.java
│ └── problems
│ │ ├── AdditionQuizLoop.java
│ │ ├── ConversionTablesKgPound.java
│ │ ├── ConversionTablesMilesToKm.java
│ │ ├── CountUpperCaseLetter.java
│ │ ├── CountVowelsAndConsonants.java
│ │ ├── DivisibleByFiveAndSix.java
│ │ ├── DivisibleByFiveOrSixButNotBoth.java
│ │ ├── FutureTuition.java
│ │ ├── HighestScore.java
│ │ ├── KilogramToPounds.java
│ │ ├── LargestNForCube.java
│ │ ├── NumberAnalyzer.java
│ │ ├── SmallestNForSquare.java
│ │ └── TwoHighestScores.java
├── mchas
│ └── problems
│ │ ├── AreaOfHexagon.java
│ │ └── AreaOfPentagon.java
└── selections
│ ├── listings
│ ├── AdditionQuiz.java
│ ├── ChineseZodiac.java
│ ├── ComputeAndInterpretBMI.java
│ ├── ComputeTax.java
│ ├── LeapYear.java
│ ├── Lottery.java
│ ├── README.md
│ ├── SimpleIfDemo.java
│ ├── SubtractionQuiz.java
│ └── TestBooleanOperators.java
│ └── problems
│ ├── AdditionQuiz.java
│ ├── BodyMassIndex.java
│ ├── CompareCosts.java
│ ├── ComputeChange.java
│ ├── ComputeTax.java
│ ├── DaysInMonth.java
│ ├── FutureDates.java
│ ├── HeadsOrTails.java
│ ├── ISBNChecker.java
│ ├── LineSegment.java
│ ├── LinearEquationUserInput.java
│ ├── Lottery.java
│ ├── PalindromeNumber.java
│ ├── PointPositions.java
│ ├── QuadraticEquation.java
│ ├── Questions
│ ├── 1.png
│ ├── 10.png
│ ├── 11.png
│ ├── 12.png
│ ├── 13.png
│ ├── 14.png
│ ├── 15.png
│ ├── 16.png
│ ├── 17.png
│ ├── 18.png
│ ├── 2.png
│ ├── 3.png
│ ├── 4.png
│ ├── 5.png
│ ├── 6.png
│ ├── 7.png
│ ├── 8.png
│ ├── 9.png
│ └── README.md
│ ├── README.md
│ ├── RandomMonth.java
│ ├── RandomPoint.java
│ ├── ScissorRockPaper.java
│ ├── ShippingCost.java
│ ├── ShowCurrentTime.java
│ ├── SortThreeNumbers.java
│ ├── SubtractionQuiz.java
│ ├── TrianglePerimeter.java
│ └── TwoRectangles.java
├── II
└── ElementryProgramming
│ └── Listing
│ ├── .idea
│ ├── .gitignore
│ ├── Listing.iml
│ ├── misc.xml
│ ├── modules.xml
│ ├── uiDesigner.xml
│ └── vcs.xml
│ ├── ComputeArea.java
│ ├── ComputeAreaWithConsoleInput.java
│ ├── ComputeAreaWithConstant.java
│ ├── ComputeAverage.java
│ ├── ComputeChange.java
│ ├── ComputeLoan.java
│ ├── DisplayTime.java
│ ├── FahrenheitToCelsius.java
│ ├── SalesTax.java
│ ├── ShowCurrentTime.java
│ └── out
│ └── production
│ └── Listing
│ ├── .idea
│ ├── .gitignore
│ ├── Listing.iml
│ ├── misc.xml
│ ├── modules.xml
│ ├── uiDesigner.xml
│ └── vcs.xml
│ ├── ComputeArea.class
│ ├── ComputeAreaWithConsoleInput.class
│ ├── ComputeAreaWithConstant.class
│ ├── ComputeAverage.class
│ ├── DisplayTime.class
│ └── FahrenheitToCelsius.class
├── LICENSE
├── README.md
└── out
└── production
└── Java book
├── .idea
├── .gitignore
├── Java book.iml
├── misc.xml
└── modules.xml
├── ComputeArea.class
├── ComputeAverage.class
├── DisplayTime.class
├── IncreDecre.class
├── ScannersObject.class
└── ShowCurrentTime.class
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.idea/Java book.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Code of Conduct
2 |
3 | As contributors and maintainers of this project, we pledge to foster an open and welcoming environment. We expect everyone participating in this project to adhere to the following code of conduct:
4 |
5 | ## Our Standards
6 |
7 | 1. **Be Respectful**: Respect each other's ideas, contributions, and differences. Be considerate and kind in your interactions with others.
8 |
9 | 2. **Maintain Professionalism**: Keep discussions and interactions professional and constructive. Refrain from personal attacks, harassment, or discrimination of any kind.
10 |
11 | 3. **Communicate Effectively**: Use clear and concise language in all communications. Be open to feedback and willing to engage in discussions with a focus on resolving issues collaboratively.
12 |
13 | 4. **Respect Privacy**: Avoid sharing personal or confidential information without permission. Respect the privacy and boundaries of others.
14 |
15 | ## Unacceptable Behavior
16 |
17 | The following behaviors are considered unacceptable and may result in removal or banning from the project:
18 |
19 | - Harassment, discrimination, or offensive language or behavior.
20 | - Intimidation, threats, or any form of bullying.
21 | - Disrespectful or disruptive comments or actions.
22 | - Any conduct that violates the rights or safety of others.
23 |
24 | ## Reporting Violations
25 |
26 | If you witness or experience any behavior that violates this code of conduct, please report it to the project maintainers at [contact@example.com]. All reports will be kept confidential.
27 |
28 | ## Enforcement
29 |
30 | Project maintainers are responsible for enforcing the code of conduct. They have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned with this code of conduct. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the project maintainers and may result in removal from the project.
31 |
32 | ## Attribution
33 |
34 | This code of conduct is adapted from the Contributor Covenant, version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html](https://www.contributor-covenant.org/version/2/0/code_of_conduct.html).
35 |
36 | By participating in this project, you agree to abide by this code of conduct.
37 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to Java-Questions
2 |
3 | Thank you for your interest in contributing to Java-Questions! By contributing, you help improve the quality of this repository and support its goal of enhancing Java proficiency.
4 |
5 | We welcome contributions in various forms, including bug fixes, feature enhancements, documentation improvements, and more. Before you start contributing, please take a moment to review the guidelines below.
6 |
7 | ## Coding Style
8 |
9 | Please adhere to the following coding style guidelines:
10 |
11 | - Use meaningful variable and function names that accurately describe their purpose.
12 | - Follow the Java naming conventions for classes, methods, variables, and packages.
13 | - Use indentation consistently for better readability. We recommend using four spaces for indentation.
14 | - Limit line length to 80 characters to ensure readability on various screen sizes.
15 | - Add comments to explain complex logic or functionality, especially where it may not be immediately obvious.
16 |
17 | ## How to Contribute
18 |
19 | 1. **Fork the Repository**: Fork the Java-Questions repository to your GitHub account.
20 |
21 | 2. **Clone the Repository**: Clone the forked repository to your local machine using Git.
22 |
23 | ```bash
24 | git clone https://github.com/annuk123/Java-Questions.git
25 | ```
26 |
27 | 3. **Create a Branch**: Create a new branch for your contribution.
28 |
29 | ```bash
30 | git checkout -b your-branch-name
31 | ```
32 |
33 | 4. **Make Changes**: Make your desired changes to the codebase.
34 |
35 | 5. **Test Your Changes**: Test your changes thoroughly to ensure they work as expected.
36 |
37 | 6. **Commit Your Changes**: Commit your changes with a descriptive commit message.
38 |
39 | ```bash
40 | git add .
41 | git commit -m "Your descriptive commit message"
42 | ```
43 |
44 | 7. **Push Changes**: Push your changes to your forked repository.
45 |
46 | ```bash
47 | git push origin your-branch-name
48 | ```
49 |
50 | 8. **Submit a Pull Request**: Once you have pushed your changes, submit a pull request to the main Java-Questions repository.
51 |
52 | 9. **Review Process**: Your pull request will be reviewed by the repository maintainers. Be prepared to address any feedback or suggestions for improvement.
53 |
54 | ## Code of Conduct
55 |
56 | Please review and adhere to our [Code of Conduct](CODE_OF_CONDUCT.md) to ensure a respectful and inclusive environment for all contributors.
57 |
58 | ## Reporting Issues
59 |
60 | If you encounter any bugs, issues, or have suggestions for improvements, please open an issue on the GitHub repository. Provide detailed information and, if possible, steps to reproduce the issue.
61 |
62 | ## License
63 |
64 | By contributing to Java-Questions, you agree that your contributions will be licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
65 |
66 | Thank you for your contributions and support!
67 |
--------------------------------------------------------------------------------
/I/fundamentals/README.md:
--------------------------------------------------------------------------------
1 | # Java Fundamentals
2 |
3 | ## Chapter I: INTRODUCTION TO COMPUTERS, PROGRAMS, AND JAVA
4 |
5 | This repository contains Java programs related to fundamental concepts.
6 |
7 | ### Aim is to;
8 | ###### ■To write a simple Java program ■■To display output on the console ■■■To explain the basic syntax of a Java program. ■■■■To create, compile, and run Java programs. ■■■■■To use sound Java programming style and document programs properly. ■■■■■■To explain the differences between syntax errors, runtime errors, and logic errors
9 |
10 | ## Listings
11 |
12 | The `listings` directory contains example Java programs:
13 |
14 | - `ComputeExpression.java`: Program to compute a mathematical expression.
15 | - `Welcome.java`: Program to display a welcome message.
16 | - `WelcomeWithThreeMessages.java`: Program to display three welcome messages.
17 |
18 | ## Problems
19 |
20 | The `problems` directory contains Java programs for solving various problems:
21 |
22 | - [1.1 DisplayThreeMessages.java](problems/DisplayThreeMessages.java): Program to display three messages.
23 | - [1.2 DisplayFiveMessages.java](problems/DisplayFiveMessages.java): Program to display five messages.
24 | - [1.3 DisplayPattern.java](problems/DisplayPattern.java): Program to display a pattern.
25 | - [1.4 PrintTable.java](problems/PrintTable.java): Program to print a table.
26 | - [1.5 ComputeExpression.java](problems/ComputeExpression.java): Program to compute a mathematical expression.
27 | - [1.6 SummationOfSeries.java](problems/SummationOfSeries.java): Program to calculate the summation of a series.
28 | - [1.7 ApproximaterPi.java](problems/ApproximaterPi.java): Program to approximate the value of Pi.
29 | - [1.8 AreaPerimeterOfCircle.java](problems/AreaPerimeterOfCircle.java): Program to calculate the area and perimeter of a circle.
30 | - [1.9 AreaPerimeterOfRectangle.java](problems/AreaPerimeterOfRectangle.java): Program to calculate the area and perimeter of a rectangle.
31 | - [1.10 AverageSpeedInMiles.java](problems/AverageSpeedInMiles.java): Program to calculate average speed in miles.
32 | - [1.11 PopulationProject.java](problems/PopulationProject.java): Program to project population growth.
33 | - [1.12 AverageSpeedInKilometers.java](problems/AverageSpeedInKilometers.java): Program to calculate average speed in kilometers.
34 | - [1.13 SimultaneousUsingCramerRule.java](problems/SimultaneousUsingCramerRule.java): Program to solve simultaneous equations using Cramer's
35 |
36 | ## Peogramming problems
37 | All the above problems are in this file: [README.md](problems/README.md)
--------------------------------------------------------------------------------
/I/fundamentals/listings/ApproximaterPi.java:
--------------------------------------------------------------------------------
1 | public class ApproximaterPi {
2 |
3 | public static void main(String[] args) {
4 | // calculate the first pi
5 | double pi_i = 4 * (1 -((1.0/5) + (1.0/5) + (1.0/7) + (1.0/9) + (1.0/11)));
6 | // calcuate the second pi
7 | double pi_ii = 4 * (1 -((1.0/5) + (1.0/5) + (1.0/7) + (1.0/9) + (1.0/11) + (1.0/13)));
8 |
9 | // output
10 | System.out.println("PI with six terms: " + pi_i);
11 | System.out.println("PI with seven terms: " + pi_ii);
12 | }
13 | }
--------------------------------------------------------------------------------
/I/fundamentals/listings/AreaPerimeterOfCircle.java:
--------------------------------------------------------------------------------
1 | public class AreaPerimeterOfCircle {
2 |
3 | public static void main(String[] args) {
4 | // PI and radius
5 | final double PI = 3.14;
6 | double radius = 5.5;
7 |
8 | // formulas for area and perimeter
9 | double area = PI * radius * radius;
10 | double perimeter = 2 * PI * radius;
11 |
12 | // perimeter and area
13 | System.out.println("\nRadius of the circle is: " + radius + "m");
14 | System.out.println("\nPerimeter of the circle is: " + perimeter);
15 | System.out.println("Area of the circle of is: " + area);
16 | }
17 | }
--------------------------------------------------------------------------------
/I/fundamentals/listings/AreaPerimeterOfRectangle.java:
--------------------------------------------------------------------------------
1 | public class AreaPerimeterOfRectangle {
2 |
3 | public static void main(String[] args) {
4 | // length and width
5 | double lenght = 9.7;
6 | double width = 4.5;
7 |
8 | // formulas for area and perimeter
9 | double area = width * lenght;
10 | double perimeter = 2 * ( lenght * width);
11 |
12 | // area and perimeter
13 | System.out.println("\nArea of the Rectangle.\n");
14 | System.out.println("Length is: " + lenght + "m and width is: " + width + "m");
15 | System.out.println("Area of the rectangle is: " + area);
16 | System.out.println("Perimeter of the rectangle is: " + perimeter);
17 |
18 | }
19 | }
--------------------------------------------------------------------------------
/I/fundamentals/listings/ComputeExpression.java:
--------------------------------------------------------------------------------
1 | package I.fundamentals.listings;
2 | public class ComputeExpression {
3 |
4 | public static void main(String[] args) {
5 | System.out.println((10.5 + 2 * 3)/ (45 - 3.5));
6 | }
7 | }
--------------------------------------------------------------------------------
/I/fundamentals/listings/DisplayFiveMessages.java:
--------------------------------------------------------------------------------
1 | public class DisplayFiveMessages {
2 |
3 | public static void main(String[] args) {
4 | // display five messages
5 | System.out.println("Welcome to Java");
6 | System.out.println("Welcome to Java");
7 | System.out.println("Welcome to Java");
8 | System.out.println("Welcome to Java");
9 | System.out.println("Welcome to Java");
10 |
11 | }
12 | }
--------------------------------------------------------------------------------
/I/fundamentals/listings/DisplayPattern.java:
--------------------------------------------------------------------------------
1 | public class DisplayPattern {
2 | public static void main(String[] args) {
3 | // JAVA pattern
4 | // Empty line
5 | System.out.println();
6 | System.out.println(" J A V V A");
7 | System.out.println(" J A A V V A A");
8 | System.out.println(" J AAAAA V V AAAAA");
9 | System.out.println("J J J A A V A A");
10 |
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/I/fundamentals/listings/DisplayThreeMessages.java:
--------------------------------------------------------------------------------
1 | public class DisplayThreeMessages {
2 |
3 | public static void main(String[] args) {
4 | // display three messages
5 | System.out.println("Welcome to Java");
6 | System.out.println("Welcome to Computer Science");
7 | System.out.println("Programming is fun");
8 | }
9 | }
--------------------------------------------------------------------------------
/I/fundamentals/listings/PopulationProject.java:
--------------------------------------------------------------------------------
1 | public class PopulationProject {
2 |
3 | public static void main(String[] args) {
4 |
5 | // constants
6 | int expected_time = 5;
7 | double seconds_per_year = 365 * 24 * 60 * 60;
8 | double births_per_second = 1.0 / 7;
9 | double deaths_per_second = 1.0 / 13;
10 | double immigrants_per_second = 1.0 / 45;
11 |
12 | // events in a year
13 | double births_per_year = births_per_second * seconds_per_year;
14 | double deaths_per_year = deaths_per_second * seconds_per_year;
15 | double immigrants_per_year = immigrants_per_second * seconds_per_year;
16 |
17 | // events in five years
18 | double births_in_five_year = births_per_year * expected_time;
19 | double deaths_in_five_year = deaths_per_year * expected_time;
20 | double immigrants_in_five_year = immigrants_per_year * expected_time;
21 | double net_population_change_per_year = births_per_year - deaths_per_year + immigrants_per_year;
22 |
23 | double net_population_change_in_next_five_years = net_population_change_per_year * expected_time;
24 |
25 | // population changes in five years
26 | System.out.println("Birth Population is the next 5 years will be: " + births_in_five_year);
27 | System.out.println("Deaths Population in the next 5 years will be: " + deaths_in_five_year);
28 | System.out.println("Immigrants population in the next 5 years will be: " + immigrants_in_five_year);
29 |
30 | // total population in a year and next 5 years
31 | System.out.println("\nIn one Year Population is Projected to be: " + net_population_change_per_year);
32 | System.err.println("Total Population in the next 5 Years will be: " + net_population_change_in_next_five_years);
33 | }
34 | }
--------------------------------------------------------------------------------
/I/fundamentals/listings/PrintTable.java:
--------------------------------------------------------------------------------
1 | public class PrintTable {
2 |
3 | public static void main(String[] args) {
4 | // printing a table
5 | // upper part
6 | System.out.println("\ta\ta^2\ta^3");
7 |
8 | // first row
9 | System.out.println("\t1\t1\t1");
10 |
11 | // second row
12 | System.out.println("\t2\t4\t8");
13 |
14 | // third row
15 | System.out.println("\t3\t9\t27");
16 |
17 | // fourth row
18 | System.out.println("\t4\t14\t64");
19 | }
20 | }
--------------------------------------------------------------------------------
/I/fundamentals/listings/SimultaneousUsingCramerRule.java:
--------------------------------------------------------------------------------
1 | public class SimultaneousUsingCramerRule{
2 |
3 | public static void main(String[] args) {
4 | // linear equation
5 | System.out.println("\nSimultaneous Equation Using Cramer's rule.");
6 | System.out.println("3.4x + 50.2y = 44.5");
7 | System.out.println("2.1x + .55y = 5.9");
8 |
9 | // variables
10 | double a = 3.4, b = 50.2, c = 2.1, d = 0.55, e = 44.5, f = 5.9;
11 |
12 | // formula for x and y.
13 | double x = (e * d - b * f) / (a * d - b * c);
14 | double y = (a * f - e * c) / (a * d - b * c);
15 |
16 | // outputs
17 | System.out.println("");
18 | System.out.println("Value of X: " + x); // value of x
19 | System.out.println("Value of Y: " + y); // value of y
20 | }
21 | }
--------------------------------------------------------------------------------
/I/fundamentals/listings/SummationOfSeries.java:
--------------------------------------------------------------------------------
1 | public class SummationOfSeries {
2 |
3 | public static void main(String[] args) {
4 | System.out.println("Summation of a Series");
5 |
6 | // summation variable
7 | double summation = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9;
8 |
9 | // ouput
10 | System.out.println("Summation of number from 1 to 9 is: " + summation);
11 | }
12 | }
--------------------------------------------------------------------------------
/I/fundamentals/listings/Welcome.java:
--------------------------------------------------------------------------------
1 | package I.fundamentals.listings;
2 | public class Welcome {
3 |
4 | public static void main(String[] args) {
5 | System.out.println("Welcome to Java");
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/I/fundamentals/listings/WelcomeWithThreeMessages.java:
--------------------------------------------------------------------------------
1 | package I.fundamentals.listings;
2 | public class WelcomeWithThreeMessages {
3 |
4 | public static void main(String[] args) {
5 | // welcome messages
6 | System.out.println("programming is fun.");
7 | System.out.println("Fundamentals first");
8 | System.out.println("Problem driven");
9 | }
10 | }
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/AverageSpeedInKilometers.java:
--------------------------------------------------------------------------------
1 | package I.fundamentals.listings.problems;
2 | public class AverageSpeedInKilometers {
3 |
4 | public static void main(String[] args) {
5 | // constant
6 | double distance = 14;
7 | double time = 45 + 30/60.0;
8 |
9 | // convert distance to mph
10 | // find the average speed.
11 | double distance_in_miles = distance / 1.6;
12 | double average_speed = distance_in_miles / (time / 60);
13 |
14 | // output: speed in MpH
15 | System.out.println("\n\tAverage Speed Calculator.\n");
16 | System.out.println("distance is 14km and Total time is: 45 minutes and 30 seconds");
17 | System.out.println("The Answer Should be im miles per hour. (Hint: 1 Miles == 1.6km)");
18 | System.out.println("\naverage speed is:" + average_speed + " MpH");
19 | }
20 | }
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/AverageSpeedInMiles.java:
--------------------------------------------------------------------------------
1 | package I.fundamentals.listings.problems;
2 | public class AverageSpeedInMiles {
3 |
4 | public static void main(String[] args) {
5 | // constants
6 | double distance = 24;
7 | double time = 40 + 30 / 60.0;
8 |
9 | // convert distance to miles
10 | double distance_in_km = distance * 1.6;
11 | double average_speed = distance_in_km / (time * 60);
12 |
13 | // output: average speed in kmh
14 | System.out.println("Average Speed in KmH is: " + average_speed);
15 | }
16 | }
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/ComputeExpression.java:
--------------------------------------------------------------------------------
1 | package I.fundamentals.listings.problems;
2 | public class ComputeExpression {
3 |
4 | public static void main(String[] args) {
5 | // expression
6 | System.out.println("Compute expression: \n");
7 |
8 | double expression = (9.5 * 4.5 - ( 2.5 * 3)) / (45.5 - 3.5);
9 | System.out.println("9.5 * 4.5 - 2.5 * 3\n" + // denominators
10 | "------------------\n" + // division symbol
11 | " 45.5 - 3.5"); // nominators
12 |
13 | System.out.println("\nvalue of the expression is: " + expression);
14 | }
15 | }
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/README.md:
--------------------------------------------------------------------------------
1 | The `problems` directory contains Java programs for solving various problems:
2 |
3 | - [1.1 DisplayThreeMessages.java](problems/DisplayThreeMessages.java): Program to display three messages.
4 | 
5 |
6 | - [1.2 DisplayFiveMessages.java](problems/DisplayFiveMessages.java): Program to display five messages.
7 | 
8 |
9 | - [1.3 DisplayPattern.java](problems/DisplayPattern.java): Program to display a pattern.
10 | 
11 |
12 | - [1.4 PrintTable.java](problems/PrintTable.java): Program to print a table.
13 | 
14 |
15 | - [1.5 ComputeExpression.java](problems/ComputeExpression.java): Program to compute a mathematical expression.
16 | 
17 |
18 | - [1.6 SummationOfSeries.java](problems/SummationOfSeries.java): Program to calculate the summation of a series.
19 | 
20 |
21 | - [1.7 ApproximaterPi.java](problems/ApproximaterPi.java): Program to approximate the value of Pi.
22 | 
23 |
24 | - [1.8 AreaPerimeterOfCircle.java](problems/AreaPerimeterOfCircle.java): Program to calculate the area and perimeter of a circle.
25 | 
26 |
27 | - [1.9 AreaPerimeterOfRectangle.java](problems/AreaPerimeterOfRectangle.java): Program to calculate the area and perimeter of a rectangle.
28 | 
29 |
30 | - [1.10 AverageSpeedInMiles.java](problems/AverageSpeedInMiles.java): Program to calculate average speed in miles.
31 | 
32 |
33 | - [1.11 PopulationProject.java](problems/PopulationProject.java): Program to project population growth.
34 | 
35 |
36 | - [1.12 AverageSpeedInKilometers.java](problems/AverageSpeedInKilometers.java): Program to calculate average speed in kilometers.
37 | 
38 |
39 | - [1.13 SimultaneousUsingCramerRule.java](problems/SimultaneousUsingCramerRule.java): Program to solve simultaneous equations using Cramer's
40 | 
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/1.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/1.1.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/1.10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/1.10.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/1.11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/1.11.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/1.12.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/1.12.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/1.13.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/1.13.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/1.2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/1.2.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/1.3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/1.3.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/1.4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/1.4.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/1.5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/1.5.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/1.6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/1.6.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/1.7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/1.7.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/1.8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/1.8.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/1.9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/1.9.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/1112.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/1112.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/14.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/14.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/56.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/56.png
--------------------------------------------------------------------------------
/I/fundamentals/listings/problems/Resources/710.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/fundamentals/listings/problems/Resources/710.png
--------------------------------------------------------------------------------
/I/loops/FutureTuition.java:
--------------------------------------------------------------------------------
1 | public class FutureTuition {
2 | public static void main(String[] args) {
3 | double tuition = 10000; // Initial tuition
4 | int year = 0; // Year counter
5 |
6 | // Calculate when tuition will double
7 | while (tuition < 20000) {
8 | tuition = tuition * 1.07; // Increase tuition by 7% each year
9 | year++; // Increment year counter
10 | }
11 |
12 | // Display the result
13 | System.out.println("Tuition will be doubled in " + year + " years");
14 | System.out.printf("Tuition will be $%.2f in %d years", tuition, year);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/I/loops/GreatestCommonDivisor.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class GreatestCommonDivisor {
4 | /** Main method */
5 | public static void main(String[] args) {
6 | // Create a Scanner
7 | Scanner input = new Scanner(System.in);
8 |
9 | // Prompt the user to enter two integers
10 | System.out.print("Enter first integer: ");
11 | int n1 = input.nextInt();
12 | System.out.print("Enter second integer: ");
13 | int n2 = input.nextInt();
14 |
15 | int gcd = 1; // Initial gcd is 1
16 | int k = 2; // Possible gcd
17 |
18 | // Find the greatest common divisor
19 | while (k <= n1 && k <= n2) {
20 | if (n1 % k == 0 && n2 % k == 0)
21 | gcd = k; // Update gcd if k divides both n1 and n2
22 | k++;
23 | }
24 |
25 | // Display the result
26 | System.out.println("The greatest common divisor for " + n1 +
27 | " and " + n2 + " is " + gcd);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/I/loops/GuessNumber.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class GuessNumber {
4 | public static void main(String[] args) {
5 | // Generate a random number to be guessed
6 | int number = (int)(Math.random() * 101);
7 |
8 | // Create a Scanner
9 | Scanner input = new Scanner(System.in);
10 |
11 | System.out.println("Guess a magic number between 0 and 100");
12 | int guess = -1;
13 | while (guess != number) {
14 | // Prompt the user to guess the number
15 | System.out.print("\nEnter your guess: ");
16 | guess = input.nextInt();
17 |
18 | // Check if the guess is correct
19 | if (guess == number)
20 | System.out.println("Yes, the number is " + number);
21 | else if (guess > number)
22 | System.out.println("Your guess is too high");
23 | else
24 | System.out.println("Your guess is too low");
25 | } // End of loop
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/I/loops/GuessNumberOneTime.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class GuessNumberOneTime {
4 | public static void main(String[] args) {
5 | // Generate a random number to be guessed
6 | int number = (int) (Math.random() * 101);
7 |
8 | // Create a Scanner
9 | Scanner input = new Scanner(System.in);
10 |
11 | System.out.println("Guess a magic number between 0 and 100");
12 | // Prompt the user to guess the number
13 | System.out.print("\nEnter your guess: ");
14 | int guess = input.nextInt();
15 |
16 | // Check if the guess is correct
17 | if (guess == number)
18 | System.out.println("Yes, the number is " + number);
19 | else if (guess > number)
20 | System.out.println("Your guess is too high");
21 | else
22 | System.out.println("Your guess is too low");
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/I/loops/MultiplicationTable.java:
--------------------------------------------------------------------------------
1 | public class MultiplicationTable {
2 | /** Main method */
3 | public static void main(String[] args) {
4 | // Display the table heading
5 | System.out.println("\nMultiplication Table");
6 |
7 | // Display the number title
8 | System.out.print("\n");
9 | for (int j = 1; j <= 9; j++)
10 | System.out.print("\t" + j); // Display numbers with proper spacing
11 | System.out.println("\n———————————————————————————————————————");
12 |
13 | // Display table body
14 | for (int i = 1; i <= 9; i++) { // Outer loop for rows
15 | System.out.print(i + " | "); // Display row number
16 |
17 | for (int j = 1; j <= 9; j++) { // Inner loop for columns
18 | // Display the product and align properly
19 | System.out.printf("%4d", i * j); // Display product with proper spacing
20 | }
21 |
22 | System.out.println(); // Move to the next line for the next row
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/I/loops/Palindrome.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class Palindrome {
4 | /** Main method */
5 | public static void main(String[] args) {
6 | // Create a Scanner
7 | Scanner input = new Scanner(System.in);
8 |
9 | // Prompt the user to enter a string
10 | System.out.print("Enter a string: ");
11 | String s = input.nextLine(); // Input string
12 |
13 | // The index of the first character in the string
14 | int low = 0; // Low index
15 | // The index of the last character in the string
16 | int high = s.length() - 1; // High index
17 |
18 | boolean isPalindrome = true;
19 |
20 | // Check if the string is a palindrome
21 | while (low < high) {
22 | if (s.charAt(low) != s.charAt(high)) {
23 | isPalindrome = false;
24 | break;
25 | }
26 |
27 | // Update indices
28 | low++;
29 | high--;
30 | }
31 |
32 | // Display the result
33 | if (isPalindrome)
34 | System.out.println(s + " is a palindrome");
35 | else
36 | System.out.println(s + " is not a palindrome");
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/I/loops/PrimeNumber.java:
--------------------------------------------------------------------------------
1 | public class PrimeNumber {
2 | public static void main(String[] args) {
3 | final int NUMBER_OF_PRIMES = 50; // Number of primes to display
4 | final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line
5 | int count = 0; // Count the number of prime numbers
6 | int number = 2; // A number to be tested for primeness
7 |
8 | System.out.println("The first 50 prime numbers are \n");
9 |
10 | // Repeatedly find prime numbers
11 | while (count < NUMBER_OF_PRIMES) {
12 | // Assume the number is prime
13 | boolean isPrime = true; // Is the current number prime?
14 |
15 | // Test whether number is prime
16 | for (int divisor = 2; divisor <= number / 2; divisor++) {
17 | if (number % divisor == 0) { // If true, number is not prime
18 | isPrime = false; // Set isPrime to false
19 | break; // Exit the for loop
20 | }
21 | }
22 |
23 | // Display the prime number and increase the count
24 | if (isPrime) {
25 | count++; // Increase the count
26 | if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
27 | // Display the number and advance to the new line
28 | System.out.println(number);
29 | } else {
30 | System.out.print(number + " ");
31 | }
32 | }
33 |
34 | // Check if the next number is prime
35 | number++;
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/I/loops/README.md:
--------------------------------------------------------------------------------
1 | # chapter 5: loops
2 |
3 | This repository contains a collection of Java programs related to loops, arithmetic operations, and quizzes.
4 |
5 | ## Examples
6 |
7 | [5.1 RepeatAdditionQuiz.java](RepeatAdditionQuiz.java): A repeat addition quiz program.
8 |
9 | [5.2 GuessNumberOneTime.java](GuessNumberOneTime.java): A number guessing game where the user gets only one chance to guess the number.
10 |
11 | [5.3 GuessNumber.java](GuessNumber.java): A number guessing game where the user guesses a randomly generated number.
12 |
13 | [5.4 SubtractionQuizLoop.java](SubtractionQuizLoop.java): A subtraction quiz program with a loop.
14 |
15 | [5.5 SentinelValue.java](SentinelValue.java): Reads integers until the user enters 0 and then calculates their sum.
16 |
17 | [5.6 TestDoWhile.java](TestDoWhile.java): test Do while loops
18 |
19 | [5.7 MultiplicationTable.java](MultiplicationTable.java): Prints the multiplication table up to 9x9.
20 |
21 | [5.8 TestSum.java](TestSum.java): Sums a series of floating-point numbers.
22 |
23 | [5.9 GreatestCommonDivisor.java](GreatestCommonDivisor.java): Finds the greatest common divisor of two integers.
24 |
25 | [5.10 FutureTuition.java](FutureTuition.java): Predicts the number of years until tuition doubles.
26 |
27 | [5.11 Dec2Hexa.java](Dec2Hexa.java): Converts a decimal number to hexadecimal.
28 |
29 | [5.12TestBreak.java](TestBreak.java): Demonstrates the usage of the `break` statement.
30 |
31 | [5.13 TestContinue.java](TestContinue.java): Demonstrates the usage of the `continue` statement.
32 |
33 | [5.14 Palindrome.java](Palindrome.java): Checks if a given string is a palindrome.
34 |
35 | [5.15 PrimeNumber.java](PrimeNumber.java): Prints the first 50 prime numbers.
36 |
--------------------------------------------------------------------------------
/I/loops/RepeatAdditionQuiz.java:
--------------------------------------------------------------------------------
1 | import java.util.InputMismatchException;
2 | import java.util.Scanner;
3 |
4 | public class RepeatAdditionQuiz {
5 | public static void main(String[] args) {
6 | int number1 = (int) (Math.random() * 10);
7 | int number2 = (int) (Math.random() * 10);
8 | // Create a Scanner
9 | Scanner input = new Scanner(System.in);
10 | System.out.print(
11 | "What is " + number1 + " + " + number2 + "? ");
12 | int answer = 0;
13 | boolean validInput = false;
14 | while (!validInput) {
15 | try {
16 | answer = input.nextInt();
17 | validInput = true;
18 | } catch (InputMismatchException e) {
19 | System.out.println("Invalid input. Please enter an integer.");
20 | input.next(); // Clear the invalid input from the scanner
21 | }
22 | }
23 | while (number1 + number2 != answer) {
24 | System.out.print("Wrong answer. Try again. What is "
25 | + number1 + " + " + number2 + "? ");
26 | validInput = false;
27 | while (!validInput) {
28 | try {
29 | answer = input.nextInt();
30 | validInput = true;
31 | } catch (InputMismatchException e) {
32 | System.out.println("Invalid input. Please enter an integer.");
33 | input.next(); // Clear the invalid input from the scanner
34 | }
35 | }
36 | }
37 | System.out.println("You got it!");
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/I/loops/SentinelValue.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class SentinelValue {
4 | /** Main method */
5 | public static void main(String[] args) {
6 | // Create a Scanner
7 | Scanner input = new Scanner(System.in);
8 |
9 | // Read an initial data
10 | System.out.print("Enter an integer (the input ends if it is 0): ");
11 | int data = input.nextInt();
12 |
13 | // Keep reading data until the input is 0
14 | int sum = 0;
15 | while (data != 0) { // Loop
16 | sum += data;
17 | // Read the next data
18 | System.out.print("Enter an integer (the input ends if it is 0): ");
19 | data = input.nextInt();
20 | } // End of loop
21 |
22 | // Display the result
23 | System.out.println("The sum is " + sum);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/I/loops/SubtractionQuizLoop.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class SubtractionQuizLoop {
4 | public static void main(String[] args) {
5 | final int NUMBER_OF_QUESTIONS = 5; // Number of questions
6 | int correctCount = 0; // Count the number of correct answers
7 | int count = 0; // Count the number of questions
8 | long startTime = System.currentTimeMillis(); // Get start time
9 | String output = ""; // Output string is initially empty
10 | Scanner input = new Scanner(System.in);
11 |
12 | while (count < NUMBER_OF_QUESTIONS) { // Loop
13 | // 1. Generate two random single-digit integers
14 | int number1 = (int)(Math.random() * 10);
15 | int number2 = (int)(Math.random() * 10);
16 |
17 | // 2. If number1 < number2, swap number1 with number2
18 | if (number1 < number2) {
19 | int temp = number1;
20 | number1 = number2;
21 | number2 = temp;
22 | }
23 |
24 | // 3. Prompt the student to answer "What is number1 – number2?"
25 | System.out.print("What is " + number1 + " - " + number2 + "? ");
26 | int answer = input.nextInt();
27 |
28 | // 4. Grade the answer and display the result
29 | if (number1 - number2 == answer) {
30 | System.out.println("You are correct!");
31 | correctCount++; // Increase the correct answer count
32 | } else {
33 | System.out.println("Your answer is wrong.\n" + number1
34 | + " - " + number2 + " should be " + (number1 - number2));
35 | }
36 |
37 | // Increase the question count
38 | count++;
39 |
40 | // Append the question and answer to the output string
41 | output += "\n" + number1 + "-" + number2 + "=" + answer +
42 | ((number1 - number2 == answer) ? " correct" : " wrong");
43 | } // End of loop
44 |
45 | long endTime = System.currentTimeMillis(); // Get end time
46 | long testTime = endTime - startTime; // Calculate test time
47 |
48 | // Display result
49 | System.out.println("Correct count is " + correctCount +
50 | "\nTest time is " + testTime / 1000 + " seconds\n" + output);
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/I/loops/TestBreak.java:
--------------------------------------------------------------------------------
1 | public class TestBreak {
2 | public static void main(String[] args) {
3 | int sum = 0;
4 | int number = 0;
5 |
6 | // Loop until the sum is greater than or equal to 100
7 | while (number < 20) {
8 | number++;
9 | sum += number;
10 | if (sum >= 100)
11 | break; // Exit the loop if the sum is greater than or equal to 100
12 | }
13 |
14 | // Display the result
15 | System.out.println("The number is " + number);
16 | System.out.println("The sum is " + sum);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/I/loops/TestContinue.java:
--------------------------------------------------------------------------------
1 | public class TestContinue {
2 | public static void main(String[] args) {
3 | int sum = 0;
4 | int number = 0;
5 |
6 | // Loop until number reaches 20
7 | while (number < 20) {
8 | number++;
9 |
10 | // Skip adding number to sum if it's equal to 10 or 11
11 | if (number == 10 || number == 11)
12 | continue;
13 |
14 | sum += number; // Add number to sum
15 | }
16 |
17 | // Display the result
18 | System.out.println("The sum is " + sum);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/I/loops/TestDoWhile.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class TestDoWhile {
4 | /** Main method */
5 | public static void main(String[] args) {
6 | int data;
7 | int sum = 0;
8 |
9 | // Create a Scanner
10 | Scanner input = new Scanner(System.in);
11 |
12 | // Keep reading data until the input is 0
13 | do {
14 | // Read the next data
15 | System.out.print("Enter an integer (the input ends if it is 0): ");
16 | data = input.nextInt();
17 | sum += data;
18 | } while (data != 0);
19 |
20 | // Display the sum
21 | System.out.println("The sum is " + sum);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/I/loops/TestSum.java:
--------------------------------------------------------------------------------
1 | public class TestSum {
2 | public static void main(String[] args) {
3 | // Initialize sum
4 | float sum = 0;
5 |
6 | // Add 0.01, 0.02, ..., 0.99, 1 to sum
7 | for (float i = 0.01f; i <= 1.0f; i = i + 0.01f) {
8 | sum += i;
9 | }
10 |
11 | // Display result
12 | System.out.println("The sum is " + sum);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/I/loops/problems/AdditionQuizLoop.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class AdditionQuizLoop {
4 | public static void main(String[] args) {
5 | final int NUMBER_OF_QUESTIONS = 10;
6 | int correctCount = 0;
7 | int count = 0;
8 | long startTime = System.currentTimeMillis();
9 | String output = "";
10 | Scanner input = new Scanner(System.in);
11 |
12 | // Loop for ten questions
13 | while (count < NUMBER_OF_QUESTIONS) {
14 | // 1. Generate two random single-digit
15 | // integers for addition between 1 and 15
16 | int number1 = (int)(Math.random() * 15) + 1;
17 | int number2 = (int)(Math.random() * 15) + 1;
18 |
19 | // 2. Prompt the student to answer "What is number1 + number2?"
20 | System.out.print("What is " + number1 + " + " + number2 + "? ");
21 | int answer = input.nextInt();
22 |
23 | // 3. Grade the answer and display the result
24 | if (number1 + number2 == answer) {
25 | System.out.println("You are correct!");
26 | correctCount++; // Increase the correct answer count
27 | } else {
28 | System.out.println("Your answer is wrong.\n" + number1
29 | + " + " + number2 + " should be " + (number1 + number2));
30 | }
31 |
32 | // increase the question count
33 | count++;
34 |
35 | // Append the question and answer to the output string
36 | output += "\n" + number1 + " + " + number2 + " = " + answer +
37 | ((number1 + number2 == answer) ? " correct" : " wrong");
38 | }
39 |
40 | long endTime = System.currentTimeMillis(); // Get end time
41 | long testTime = endTime - startTime; // Calculate test time
42 |
43 | // Display result
44 | System.out.println("Correct count is " + correctCount +
45 | "\nTest time is " + testTime / 1000 + " seconds\n" + output);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/I/loops/problems/ConversionTablesKgPound.java:
--------------------------------------------------------------------------------
1 | public class ConversionTablesKgPound {
2 |
3 | public static void main(String[] args) {
4 | System.out.println("Kilograms\t\tPounds\t\t|\t\tPounds\t\tKilograms");
5 | System.out.println("----------------------------------------------------------|----------------------------------------------------------");
6 | for (int kilogram = 1, pound = 2; kilogram <= 199 && pound <= 515; kilogram += 2, pound += 5) {
7 | double poundToKg = pound / 2.2;
8 | double kgToPound = kilogram * 2.2;
9 | System.out.printf("%-9d\t\t%-9.1f\t|\t\t%-9d\t\t%-9.2f\n", kilogram, kgToPound, pound, poundToKg);
10 | }
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/I/loops/problems/ConversionTablesMilesToKm.java:
--------------------------------------------------------------------------------
1 | public class ConversionTablesMilesToKm {
2 |
3 | public static void main(String[] args) {
4 | System.out.println("Miles\t\tKilometers\t|\t\tKilometers\t\tMiles");
5 | System.out.println("---------------------------------------------------------------|--------------------------");
6 | for (int miles = 1, km = 2; miles <= 10 && km <= 65; miles++, km += 5) {
7 | double kmToMiles = km / 1.609;
8 | double milesToKm = miles * 1.609;
9 | System.out.printf("%-9d\t%-12.3f\t|\t%-12d\t\t%-9.3f\n", miles, milesToKm, km, kmToMiles);
10 | }
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/I/loops/problems/CountUpperCaseLetter.java:
--------------------------------------------------------------------------------
1 | // package danielliang.fundamentals.loops;
2 |
3 | import java.util.Scanner;
4 |
5 | public class CountUpperCaseLetter {
6 |
7 | public static void main(String[] args) {
8 | try (Scanner input = new Scanner(System.in)) {
9 | System.out.println("\nEnter a String (or enter 'exit' to quit): ");
10 |
11 | while (true) {
12 | System.out.print("\nEnter a sentence: ");
13 | String string = input.nextLine();
14 |
15 | if (string.equalsIgnoreCase("exit")) {
16 | System.out.print("Exiting the program...");
17 | Thread.sleep(2000);
18 | break;
19 | }
20 |
21 | int count = 0;
22 | StringBuilder uppercaseLetters = new StringBuilder();
23 |
24 | for (int value = 0; value < string.length(); value++) {
25 | char character = string.charAt(value);
26 |
27 | if (Character.isUpperCase(character)) {
28 | count++;
29 | // Append uppercase letter to StringBuilder
30 | uppercaseLetters.append(character).append(" ");
31 | }
32 | }
33 |
34 | // Display the number of uppercase letters
35 | System.out.println("The number of uppercase letters is " + count + ".");
36 |
37 | // If there are any uppercase letters, display them
38 | if (count > 0) {
39 | System.out.println("The uppercase letters are: " + uppercaseLetters);
40 | }
41 | }
42 | } catch (Exception e) {
43 | System.out.println("an error occurred: " + e);
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/I/loops/problems/CountVowelsAndConsonants.java:
--------------------------------------------------------------------------------
1 | // package DanielLiang.fundamentals.V;
2 |
3 | import java.util.Scanner;
4 |
5 | public class CountVowelsAndConsonants {
6 |
7 | public static void main(String[] args) {
8 | try (Scanner input = new Scanner(System.in)) {
9 | while (true) {
10 | System.out.print("\nEnter a String: ");
11 | String string = input.nextLine();
12 |
13 | if(string.equalsIgnoreCase("exit")){
14 | System.out.print("Exiting..");
15 | Thread.sleep(2000);
16 | break;
17 | }
18 | int vowelcount = 0;
19 | int consonantcount = 0;
20 |
21 | for (int value = 0; value < string.length(); value++){
22 | char character = Character.toLowerCase(string.charAt(value));
23 |
24 | if (character >= 'a' && character <= 'z' ) {
25 | if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u') {
26 | vowelcount++;
27 | }else{
28 | consonantcount++;
29 | }
30 | }
31 | }
32 | System.out.println("The number of vowels is " + vowelcount);
33 | System.out.println("The number of consonants is " + consonantcount);
34 |
35 | }
36 | }catch (Exception e) {
37 | System.err.println("an error occurred: " + e);
38 | }
39 | }
40 | }
--------------------------------------------------------------------------------
/I/loops/problems/DivisibleByFiveAndSix.java:
--------------------------------------------------------------------------------
1 | public class DivisibleByFiveAndSix {
2 |
3 | public static void main(String[] args) {
4 | final int NUMS_PER_LINE = 10;
5 | int count = 0;
6 |
7 | for (int num = 100; num <= 1000; num++) {
8 | if (num % 5 == 0 && num % 6 == 0) {
9 | System.out.print(num + " ");
10 | count++;
11 |
12 | if (count % NUMS_PER_LINE == 0)
13 | System.out.println();
14 | }
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/I/loops/problems/DivisibleByFiveOrSixButNotBoth.java:
--------------------------------------------------------------------------------
1 | public class DivisibleByFiveOrSixButNotBoth {
2 |
3 | public static void main(String[] args) {
4 | final int NUMS_PER_LINE = 10;
5 | int count = 0;
6 |
7 | System.out.println("Numbers divisible by 5 or 6, but not both, from 100 to 200:");
8 |
9 | for (int num = 100; num <= 200; num++) {
10 | if ((num % 5 == 0 || num % 6 == 0) && !(num % 5 == 0 && num % 6 == 0)) {
11 | System.out.print(num + " ");
12 | count++;
13 |
14 | if (count % NUMS_PER_LINE == 0)
15 | System.out.println();
16 | }
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------
/I/loops/problems/FutureTuition.java:
--------------------------------------------------------------------------------
1 | public class FutureTuition {
2 |
3 | public static void main(String[] args) {
4 | double tuition = 10000;
5 | double increaseRate = 0.05; // 5% increase rate
6 |
7 | // Calculate tuition for ten years
8 | for (int year = 1; year <= 10; year++) {
9 | tuition *= (1 + increaseRate);
10 | System.out.printf("Year %d: $%.2f\n", year, tuition);
11 | }
12 |
13 | // Calculate total cost of four years' worth of tuition after the tenth year
14 | double totalCost = 0;
15 | for (int i = 0; i < 4; i++) {
16 | tuition *= (1 + increaseRate);
17 | totalCost += tuition;
18 | }
19 | System.out.printf("Total cost of four years' worth of tuition after the tenth year: $%.2f\n", totalCost);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/I/loops/problems/HighestScore.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class HighestScore {
4 |
5 | public static void main(String[] args) {
6 | Scanner scanner = new Scanner(System.in);
7 | System.out.print("Enter the number of students: ");
8 | int numStudents = scanner.nextInt();
9 | scanner.nextLine(); // Consume newline character
10 |
11 | String highestScorer = "";
12 | double highestScore = Double.MIN_VALUE;
13 |
14 | for (int i = 0; i < numStudents; i++) {
15 | System.out.print("Enter student's name: ");
16 | String name = scanner.nextLine();
17 | System.out.print("Enter student's score: ");
18 | double score = scanner.nextDouble();
19 | scanner.nextLine(); // Consume newline character
20 |
21 | if (score > highestScore) {
22 | highestScore = score;
23 | highestScorer = name;
24 | }
25 | }
26 |
27 | System.out.println("\nStudent with the highest score: " + highestScorer);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/I/loops/problems/KilogramToPounds.java:
--------------------------------------------------------------------------------
1 | public class KilogramToPounds {
2 |
3 | public static void main(String[] args) {
4 | System.out.println("\tkilograms\t\tpounds");
5 | System.out.println("-----------------------------------------");
6 | for(int kilogram = 1; kilogram <= 199; kilogram +=2){
7 | double pound = kilogram * 2.2;
8 |
9 | String formattedPound = String.format("%.1f", pound);
10 | System.out.println("\t" + kilogram + "\t\t" + formattedPound + " \t");
11 | }
12 | }
13 | }
--------------------------------------------------------------------------------
/I/loops/problems/LargestNForCube.java:
--------------------------------------------------------------------------------
1 | public class LargestNForCube {
2 |
3 | public static void main(String[] args) {
4 | int n = 1;
5 | while (n * n * n <= 12000) {
6 | n++;
7 | }
8 | // decrement n by 1 to get the largest integer
9 | n--;
10 | System.out.println("The largest integer n such that n^3 is less than 12,000 is: " + n);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/I/loops/problems/NumberAnalyzer.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class NumberAnalyzer {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 |
7 | int positiveCount = 0;
8 | int negativeCount = 0;
9 | int total = 0;
10 | int count = 0;
11 |
12 | System.out.print("Enter an integer, the input ends if it is 0: ");
13 |
14 | while (true) {
15 | int num = scanner.nextInt();
16 |
17 | if (num == 0) {
18 | break;
19 | } else if (num > 0) {
20 | positiveCount++;
21 | } else {
22 | negativeCount++;
23 | }
24 |
25 | total += num;
26 | count++;
27 | }
28 |
29 | if (count == 0) {
30 | System.out.println("No numbers are entered except 0");
31 | } else {
32 | System.out.println("The number of positives is " + positiveCount);
33 | System.out.println("The number of negatives is " + negativeCount);
34 | System.out.println("The total is " + total);
35 | System.out.println("The average is " + ((double) total / count));
36 | }
37 |
38 | scanner.close();
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/I/loops/problems/SmallestNForSquare.java:
--------------------------------------------------------------------------------
1 | public class SmallestNForSquare {
2 |
3 | public static void main(String[] args) {
4 | int n = 1;
5 | while (n * n <= 12000) {
6 | n++;
7 | }
8 | System.out.println("The smallest integer n such that n^2 is greater than 12,000 is: " + n);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/I/loops/problems/TwoHighestScores.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class TwoHighestScores {
4 |
5 | public static void main(String[] args) {
6 | Scanner scanner = new Scanner(System.in);
7 | System.out.print("Enter the number of students: ");
8 | int numStudents = scanner.nextInt();
9 | scanner.nextLine(); // Consume newline character
10 |
11 | String highestScorer = "";
12 | double highestScore = Double.MIN_VALUE;
13 | String secondHighestScorer = "";
14 | double secondHighestScore = Double.MIN_VALUE;
15 |
16 | for (int i = 0; i < numStudents; i++) {
17 | System.out.print("Enter student's name: ");
18 | String name = scanner.nextLine();
19 | System.out.print("Enter student's score: ");
20 | double score = scanner.nextDouble();
21 | scanner.nextLine(); // Consume newline character
22 |
23 | if (score > highestScore) {
24 | secondHighestScore = highestScore;
25 | secondHighestScorer = highestScorer;
26 | highestScore = score;
27 | highestScorer = name;
28 | } else if (score > secondHighestScore) {
29 | secondHighestScore = score;
30 | secondHighestScorer = name;
31 | }
32 | }
33 |
34 | System.out.println("Student with the highest score: " + highestScorer);
35 | System.out.println("Student with the second highest score: " + secondHighestScorer);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/I/mchas/problems/AreaOfHexagon.java:
--------------------------------------------------------------------------------
1 | package DanielLiang.FundamentalOfProgramming.MathematicalFunctionsCharacterAndStrings;
2 |
3 | import java.util.Scanner;
4 |
5 | public class AreaOfHexagon {
6 |
7 | public static void main(String[] args) {
8 | try (Scanner input = new Scanner(System.in)) {
9 | System.out.print("Enter the side: ");
10 |
11 | double side = input.nextDouble();
12 | double area = 6 * side * side /(4 *(Math.tan(Math.PI/6)));
13 |
14 | System.out.printf("Area of Hexagon is: %.2f", area);
15 |
16 | } catch (Exception e) {
17 | System.out.println("Bad expressions");
18 | }
19 |
20 |
21 | }
22 | }
--------------------------------------------------------------------------------
/I/mchas/problems/AreaOfPentagon.java:
--------------------------------------------------------------------------------
1 |
2 | import java.util.*;
3 |
4 | public class AreaOfPentagon {
5 |
6 | public static void main(String[] args){
7 | try (Scanner input = new Scanner(System.in)) {
8 | System.out.print("Enter the Length Form the center to the vertex: ");
9 |
10 | double radius = input.nextDouble();
11 |
12 | double distance = 2 * radius * (Math.sin(Math.PI/5));
13 | double area = 5 * distance * distance /(4 * (Math.tan(Math.PI/5)));
14 |
15 | System.out.printf("Area of the Pentagon is: %.2f", area);
16 |
17 | } catch (Exception e) {
18 | System.err.println("Bad Expression");
19 | }
20 |
21 | }
22 |
23 | }
--------------------------------------------------------------------------------
/I/selections/listings/AdditionQuiz.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class AdditionQuiz {
4 | public static void main(String[] args) {
5 | // generate number1
6 | int number1 = (int)(System.currentTimeMillis() % 10);
7 |
8 | // generate number2
9 | int number2 = (int)(System.currentTimeMillis() / 7 % 10);
10 |
11 | // create a Scanner
12 | Scanner input = new Scanner(System.in);
13 |
14 | // show question
15 | System.out.print("What is " + number1 + " + " + number2 + "? ");
16 |
17 | // get user input
18 | int answer = input.nextInt();
19 |
20 | // display result
21 | System.out.println(number1 + " + " + number2 + " = " + answer + " is " +
22 | (number1 + number2 == answer));
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/I/selections/listings/ChineseZodiac.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class ChineseZodiac {
4 | public static void main(String[] args) {
5 | Scanner input = new Scanner(System.in);
6 |
7 | // Prompt the user to enter a year
8 | System.out.print("Enter a year: ");
9 | int year = input.nextInt();
10 |
11 | // Determine the Chinese Zodiac sign for the entered year
12 | switch (year % 12) {
13 | case 0:
14 | System.out.println("Monkey");
15 | break;
16 | case 1:
17 | System.out.println("Rooster");
18 | break;
19 | case 2:
20 | System.out.println("Dog");
21 | break;
22 | case 3:
23 | System.out.println("Pig");
24 | break;
25 | case 4:
26 | System.out.println("Rat");
27 | break;
28 | case 5:
29 | System.out.println("Ox");
30 | break;
31 | case 6:
32 | System.out.println("Tiger");
33 | break;
34 | case 7:
35 | System.out.println("Rabbit");
36 | break;
37 | case 8:
38 | System.out.println("Dragon");
39 | break;
40 | case 9:
41 | System.out.println("Snake");
42 | break;
43 | case 10:
44 | System.out.println("Horse");
45 | break;
46 | case 11:
47 | System.out.println("Sheep");
48 | break;
49 | default:
50 | System.out.println("Invalid year entered.");
51 | break;
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/I/selections/listings/ComputeAndInterpretBMI.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class ComputeAndInterpretBMI {
4 | public static void main(String[] args) {
5 | Scanner input = new Scanner(System.in);
6 |
7 | // Prompt the user to enter weight in pounds
8 | System.out.print("Enter weight in pounds: ");
9 | double weight = input.nextDouble();
10 |
11 | // Prompt the user to enter height in inches
12 | System.out.print("Enter height in inches: ");
13 | double height = input.nextDouble();
14 |
15 | final double KILOGRAMS_PER_POUND = 0.45359237; // Constant
16 | final double METERS_PER_INCH = 0.0254; // Constant
17 |
18 | // Compute BMI
19 | double weightInKilograms = weight * KILOGRAMS_PER_POUND;
20 | double heightInMeters = height * METERS_PER_INCH;
21 | double bmi = weightInKilograms / (heightInMeters * heightInMeters);
22 |
23 | // Display result
24 | System.out.println("BMI is " + bmi);
25 |
26 | if (bmi < 18.5)
27 | System.out.println("Underweight");
28 | else if (bmi < 25)
29 | System.out.println("Normal");
30 | else if (bmi < 30)
31 | System.out.println("Overweight");
32 | else
33 | System.out.println("Obese");
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/I/selections/listings/ComputeTax.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class ComputeTax {
4 | public static void main(String[] args) {
5 | // Create a Scanner
6 | Scanner input = new Scanner(System.in);
7 |
8 | // Prompt the user to enter filing status
9 | System.out.print("(0-single filer, 1-married jointly or " +
10 | "qualifying widow(er), 2-married separately, 3-head of " +
11 | "household) Enter the filing status: ");
12 | int status = input.nextInt(); // Input status
13 |
14 | // Prompt the user to enter taxable income
15 | System.out.print("Enter the taxable income: ");
16 | double income = input.nextDouble(); // Input income
17 |
18 | // Compute tax
19 | double tax = 0; // Compute tax
20 | if (status == 0) { // Compute tax for single filers
21 | if (income <= 8350)
22 | tax = income * 0.10;
23 | else if (income <= 33950)
24 | tax = 8350 * 0.10 + (income - 8350) * 0.15;
25 | else if (income <= 82250)
26 | tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950) * 0.25;
27 | else if (income <= 171550)
28 | tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (income - 82250) * 0.28;
29 | else if (income <= 372950)
30 | tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 +
31 | (171550 - 82250) * 0.28 + (income - 171550) * 0.33;
32 | else
33 | tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 +
34 | (171550 - 82250) * 0.28 + (372950 - 171550) * 0.33 + (income - 372950) * 0.35;
35 | } else if (status == 1) {
36 | // Compute tax for married file jointly or qualifying widow(er)
37 | // Left as an exercise
38 | } else if (status == 2) {
39 | // Compute tax for married separately
40 | // Left as an exercise
41 | } else if (status == 3) {
42 | // Compute tax for head of household
43 | // Left as an exercise
44 | } else {
45 | System.out.println("Error: invalid status");
46 | System.exit(1);
47 | }
48 |
49 | // Display the result
50 | System.out.println("Tax is " + (int)(tax * 100) / 100.0);
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/I/selections/listings/LeapYear.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 | public class LeapYear {
3 | public static void main(String[] args) {
4 | // Create a Scanner
5 | Scanner input = new Scanner(System.in);
6 | System.out.print("Enter a year: ");
7 | int year = input.nextInt();
8 | // Check if the year is a leap year
9 | boolean isLeapYear =
10 | (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
11 | // Display the result
12 | System.out.println(year + " is a leap year? " + isLeapYear);
13 | }
14 | }
--------------------------------------------------------------------------------
/I/selections/listings/Lottery.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class Lottery {
4 | public static void main(String[] args) {
5 | // Generate a lottery number
6 | int lottery = (int) (Math.random() * 100);
7 |
8 | // Prompt the user to enter a guess
9 | Scanner input = new Scanner(System.in);
10 | System.out.print("Enter your lottery pick (two digits): ");
11 | int guess = input.nextInt();
12 |
13 | // Get digits from lottery
14 | int lotteryDigit1 = lottery / 10;
15 | int lotteryDigit2 = lottery % 10;
16 |
17 | // Get digits from guess
18 | int guessDigit1 = guess / 10;
19 | int guessDigit2 = guess % 10;
20 |
21 | System.out.println("The lottery number is " + lottery);
22 |
23 | // Check the guess
24 | if (guess == lottery)
25 | System.out.println("Exact match: you win $10,000");
26 | else if ((guessDigit2 == lotteryDigit1 && guessDigit1 == lotteryDigit2) ||
27 | (guessDigit1 == lotteryDigit1 && guessDigit1 == lotteryDigit2) ||
28 | (guessDigit2 == lotteryDigit1 && guessDigit2 == lotteryDigit2))
29 | System.out.println("Match all digits: you win $3,000");
30 | else if (guessDigit1 == lotteryDigit1 || guessDigit1 == lotteryDigit2 ||
31 | guessDigit2 == lotteryDigit1 || guessDigit2 == lotteryDigit2)
32 | System.out.println("Match one digit: you win $1,000");
33 | else
34 | System.out.println("Sorry, no match");
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/I/selections/listings/README.md:
--------------------------------------------------------------------------------
1 | # All java examples in chapter three are here
2 |
3 | ## list of examples(listings)
4 |
5 | [3.1 AdditionQuiz](AdditionQuiz.java): Simple addition programm
6 |
7 | [3.2 SimpleIfDemo.java](SimpleIfDemo.java): Simple demostration of if statements
8 |
9 | [3.3 SubtractionQuiz.java](SubtractionQuiz.java): Simpe Subtraction program
10 |
11 | [3.4 ComputeAndInterpretBMI.java](ComputeAndInterpretBMI.java): Compute And Interpret BMI
12 |
13 | [3.5 ComputeTax.java](ComputeTax.java): program to Compute Tax
14 |
15 | [3.6 TestBooleanOperators.java](TestBooleanOperators.java): program to test boolean operators
16 |
17 | [3.7 LeapYear.java](LeapYear.java): program to find a leap year
18 |
19 | [3.8 Lottery.java](Lottery.java): simulation of lottery game
20 |
21 | [3.9 ChineseZodiac.java](ChineseZodiac.java): Simple program to find Chinese Zodiac
22 |
23 | ### These projects are numbered you may skip or follow the order.
--------------------------------------------------------------------------------
/I/selections/listings/SimpleIfDemo.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class SimpleIfDemo {
4 | public static void main(String[] args) {
5 | Scanner input = new Scanner(System.in);
6 | System.out.println("Enter an integer: ");
7 | int number = input.nextInt();
8 |
9 | if (number % 5 == 0 && number % 2 == 0) {
10 | System.out.println("HiFive");
11 | System.out.println("HiEven");
12 | } else if (number % 5 == 0) {
13 | System.out.println("HiFive");
14 | } else if (number % 2 == 0) {
15 | System.out.println("HiEven");
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/I/selections/listings/SubtractionQuiz.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class SubtractionQuiz {
4 | public static void main(String[] args) {
5 | // Generate two random single-digit integers
6 | int number1 = (int)(Math.random() * 10);
7 | int number2 = (int)(Math.random() * 10);
8 |
9 | // If number1 < number2, swap number1 with number2
10 | if (number1 < number2) {
11 | int temp = number1;
12 | number1 = number2;
13 | number2 = temp;
14 | }
15 |
16 | // Prompt the student to answer ”What is number1 – number2?”
17 | System.out.print("What is " + number1 + " - " + number2 + "? ");
18 | Scanner input = new Scanner(System.in);
19 | int answer = input.nextInt();
20 |
21 | // Grade the answer and display the result
22 | if (number1 - number2 == answer)
23 | System.out.println("You are correct!");
24 | else {
25 | System.out.println("Your answer is wrong.");
26 | System.out.println(number1 + " - " + number2 +
27 | " should be " + (number1 - number2));
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/I/selections/listings/TestBooleanOperators.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class TestBooleanOperators {
4 | public static void main(String[] args) {
5 | // Create a Scanner
6 | Scanner input = new Scanner(System.in);
7 |
8 | // Receive an input
9 | System.out.print("Enter an integer: ");
10 | int number = input.nextInt();
11 |
12 | if (number % 2 == 0 && number % 3 == 0)
13 | System.out.println(number + " is divisible by 2 and 3.");
14 |
15 | if (number % 2 == 0 || number % 3 == 0)
16 | System.out.println(number + " is divisible by 2 or 3.");
17 |
18 | if (number % 2 == 0 ^ number % 3 == 0)
19 | System.out.println(number + " is divisible by 2 or 3, but not both.");
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/I/selections/problems/AdditionQuiz.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class AdditionQuiz {
4 | public static void main(String[] args) {
5 | // generate three random numbers
6 | int number1 = (int)(System.currentTimeMillis() % 10);
7 | int number2 = (int)(System.currentTimeMillis() / 7 % 10);
8 | int number3 = (int)(System.currentTimeMillis() / 11 % 10);
9 |
10 | // Scanner
11 | Scanner input = new Scanner(System.in);
12 |
13 | // show question
14 | System.out.print("What is " + number1 + " + " + number2 + " + " + number3 + "? ");
15 |
16 | // get user input
17 | int answer = input.nextInt();
18 |
19 | // Calculate the correct answer
20 | int correctAnswer = number1 + number2 + number3;
21 |
22 | // Display result
23 | System.out.println(number1 + " + " + number2 + " + " + number3 + " = " + answer + " is " +
24 | (correctAnswer == answer));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/I/selections/problems/BodyMassIndex.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class BodyMassIndex {
4 |
5 | public static void main(String[] args) {
6 | Scanner input = new Scanner(System.in);
7 |
8 | // weight in pounds
9 | System.out.print("Enter weight in pounds: ");
10 | int weight_pounds = input.nextInt();
11 |
12 | // pound convertion to kilograms
13 | double weight_kg = weight_pounds * 0.453592;
14 |
15 | // height in feet and inches
16 | System.out.print("Enter feet: ");
17 | int feet = input.nextInt();
18 |
19 | System.out.print("Enter inches: ");
20 | int inches = input.nextInt();
21 |
22 | // Convert inches to meters
23 | double height_meters = ((feet * 12) + inches) * 0.0254;
24 |
25 | // Calculate BMI
26 | // Formula for BMI calculation
27 | double bmi = weight_kg / (height_meters * height_meters);
28 |
29 | System.out.println("BMI is " + bmi);
30 |
31 | // Interpret BMI
32 | if (bmi < 18.5) {
33 | System.out.println("Underweight");
34 | } else if (bmi < 25) {
35 | System.out.println("Normal");
36 | } else if (bmi < 30) {
37 | System.out.println("Overweight");
38 | } else {
39 | System.out.println("Obese");
40 | }
41 | }
42 |
43 | }
--------------------------------------------------------------------------------
/I/selections/problems/CompareCosts.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class CompareCosts {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 |
7 | // user prompt to enter weight and price for package 1
8 | System.out.print("Enter weight and price for package 1: ");
9 | double weight1 = scanner.nextDouble();
10 | double price1 = scanner.nextDouble();
11 |
12 | // user prompt to enter weight and price for package 2
13 | System.out.print("Enter weight and price for package 2: ");
14 | double weight2 = scanner.nextDouble();
15 | double price2 = scanner.nextDouble();
16 |
17 | // calculate the unit price for each package
18 | double unitPrice1 = price1 / weight1;
19 | double unitPrice2 = price2 / weight2;
20 |
21 | // compare the unit prices
22 | if (unitPrice1 < unitPrice2) {
23 | System.out.println("Package 1 has a better price.");
24 | } else if (unitPrice1 > unitPrice2) {
25 | System.out.println("Package 2 has a better price.");
26 | } else {
27 | System.out.println("Two packages have the same price.");
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/I/selections/problems/ComputeChange.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class ComputeChange {
4 | public static void main(String[] args) {
5 | Scanner input = new Scanner(System.in);
6 |
7 | // receive the amount
8 | System.out.print("Enter an amount in double, for example 11.56: ");
9 | double amount = input.nextDouble();
10 |
11 | int remainingAmount = (int)(amount * 100);
12 |
13 | // find the number of one dollars
14 | int numberOfOneDollars = remainingAmount / 100;
15 | remainingAmount = remainingAmount % 100;
16 |
17 | // find the number of quarters in the remaining amount
18 | int numberOfQuarters = remainingAmount / 25;
19 | remainingAmount = remainingAmount % 25;
20 |
21 | // find the number of dimes in the remaining amount
22 | int numberOfDimes = remainingAmount / 10;
23 | remainingAmount = remainingAmount % 10;
24 |
25 | // find the number of nickels in the remaining amount
26 | int numberOfNickels = remainingAmount / 5;
27 | remainingAmount = remainingAmount % 5;
28 |
29 | // find the number of pennies in the remaining amount
30 | int numberOfPennies = remainingAmount;
31 |
32 | // display results for nonzero denominations
33 | System.out.println("Your amount " + amount + " consists of:");
34 |
35 | if (numberOfOneDollars != 0)
36 | System.out.println(numberOfOneDollars + (numberOfOneDollars == 1 ? " dollar" : " dollars"));
37 |
38 | if (numberOfQuarters != 0)
39 | System.out.println(numberOfQuarters + (numberOfQuarters == 1 ? " quarter" : " quarters"));
40 |
41 | if (numberOfDimes != 0)
42 | System.out.println(numberOfDimes + (numberOfDimes == 1 ? " dime" : " dimes"));
43 |
44 | if (numberOfNickels != 0)
45 | System.out.println(numberOfNickels + (numberOfNickels == 1 ? " nickel" : " nickels"));
46 |
47 | if (numberOfPennies != 0)
48 | System.out.println(numberOfPennies + (numberOfPennies == 1 ? " penny" : " pennies"));
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/I/selections/problems/ComputeTax.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class ComputeTax {
4 | public static void main(String[] args) {
5 | Scanner input = new Scanner(System.in);
6 |
7 | // user prompt to enter filing status
8 | System.out.print("(0-single filer, 1-married jointly or " +
9 | "qualifying widow(er), 2-married separately, 3-head of " +
10 | "household) Enter the filing status: ");
11 | int status = input.nextInt(); // Input status
12 |
13 | // user prompt to enter taxable income
14 | System.out.print("Enter the taxable income: ");
15 | double income = input.nextDouble(); // Input income
16 |
17 | // Compute tax
18 | double tax = 0; // Compute tax
19 | if (status == 0) { // compute tax for single filers
20 | if (income <= 8350)
21 | tax = income * 0.10;
22 | else if (income <= 33950)
23 | tax = 8350 * 0.10 + (income - 8350) * 0.15;
24 | else if (income <= 82250)
25 | tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950) * 0.25;
26 | else if (income <= 171550)
27 | tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (income - 82250) * 0.28;
28 | else if (income <= 372950)
29 | tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 +
30 | (171550 - 82250) * 0.28 + (income - 171550) * 0.33;
31 | else
32 | tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 +
33 | (171550 - 82250) * 0.28 + (372950 - 171550) * 0.33 + (income - 372950) * 0.35;
34 | } else if (status == 1) { // Compute tax for married jointly or qualifying widow(er)
35 | if (income <= 16700)
36 | tax = income * 0.10;
37 | else if (income <= 67900)
38 | tax = 16700 * 0.10 + (income - 16700) * 0.15;
39 | else if (income <= 137050)
40 | tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (income - 67900) * 0.25;
41 | else if (income <= 208850)
42 | tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (income - 137050) * 0.28;
43 | else if (income <= 372950)
44 | tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 +
45 | (208850 - 137050) * 0.28 + (income - 208850) * 0.33;
46 | else
47 | tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 +
48 | (208850 - 137050) * 0.28 + (372950 - 208850) * 0.33 + (income - 372950) * 0.35;
49 | } else if (status == 2) { // Compute tax for married separately
50 |
51 | // Left as an exercise
52 | System.out.println("Tax computation for married separately is left as an exercise.");
53 | } else if (status == 3) { // Compute tax for head of household
54 |
55 | // left as an exercise
56 | System.out.println("Tax computation for head of household is left as an exercise.");
57 | } else { // Invalid status
58 | System.out.println("Error: invalid status");
59 | System.exit(1);
60 | }
61 |
62 | // display the result
63 | System.out.println("Tax is " + (int)(tax * 100) / 100.0);
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/I/selections/problems/DaysInMonth.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class DaysInMonth {
4 |
5 | public static void main(String[] args) {
6 | Scanner input = new Scanner(System.in);
7 |
8 | // user prompt to enter the month (1 - 12)
9 | System.out.print("Enter the month (1 - 12): ");
10 | int month = input.nextInt();
11 |
12 | // user prompt to enter the year
13 | System.out.print("Enter the year: ");
14 | int year = input.nextInt();
15 |
16 | // user prompt to enter a day
17 | System.out.print("Enter a day: ");
18 | int day = input.nextInt();
19 |
20 | int days_in_month;
21 |
22 | // determine the number of days in the entered month
23 | switch (month) {
24 | case 1:
25 | System.out.print("January ");
26 | days_in_month = 31;
27 | break;
28 | case 2:
29 | System.out.print("February ");
30 | // check for leap year
31 | if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
32 | days_in_month = 29;
33 | } else {
34 | days_in_month = 28;
35 | }
36 | break;
37 | case 3:
38 | System.out.print("March ");
39 | days_in_month = 31;
40 | break;
41 | case 4:
42 | System.out.print("April ");
43 | days_in_month = 30;
44 | break;
45 | case 5:
46 | System.out.print("May ");
47 | days_in_month = 31;
48 | break;
49 | case 6:
50 | System.out.print("June ");
51 | days_in_month = 30;
52 | break;
53 | case 7:
54 | System.out.print("July ");
55 | days_in_month = 31;
56 | break;
57 | case 8:
58 | System.out.print("August ");
59 | days_in_month = 31;
60 | break;
61 | case 9:
62 | System.out.print("September ");
63 | days_in_month = 30;
64 | break;
65 | case 10:
66 | System.out.print("October ");
67 | days_in_month = 31;
68 | break;
69 | case 11:
70 | System.out.print("November ");
71 | days_in_month = 30;
72 | break;
73 | case 12:
74 | System.out.print("December ");
75 | days_in_month = 31;
76 | break;
77 | default:
78 | System.out.println("Invalid month entered.");
79 | days_in_month = -1; // Invalid month
80 | break;
81 | }
82 |
83 | // display the number of days in
84 | // the entered month, day, and year
85 | if (days_in_month != -1) {
86 | System.out.println(day + ", " + year + " had " + days_in_month + " days.");
87 | }
88 |
89 | input.close();
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/I/selections/problems/FutureDates.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class FutureDates {
4 |
5 | public static void main(String[] args) {
6 | Scanner input = new Scanner(System.in);
7 |
8 | // prompt for today's day
9 | System.out.print("Enter today's day (Sunday is 0, Monday is 1, ..., Saturday is 6): ");
10 | int today = input.nextInt();
11 |
12 | // prompt for the number of days elapsed
13 | System.out.print("Enter the number of days elapsed since today: ");
14 | int elapsedDays = input.nextInt();
15 |
16 | // calculate future day
17 | int futureDay = (today + elapsedDays) % 7;
18 |
19 | // display result for today's day
20 | System.out.print("Today is ");
21 | if (today == 0)
22 | System.out.print("Sunday");
23 | else if (today == 1)
24 | System.out.print("Monday");
25 | else if (today == 2)
26 | System.out.print("Tuesday");
27 | else if (today == 3)
28 | System.out.print("Wednesday");
29 | else if (today == 4)
30 | System.out.print("Thursday");
31 | else if (today == 5)
32 | System.out.print("Friday");
33 | else
34 | System.out.print("Saturday");
35 |
36 | // display result for future day
37 | System.out.print(" and the future day is ");
38 | if (futureDay == 0)
39 | System.out.println("Sunday");
40 | else if (futureDay == 1)
41 | System.out.println("Monday");
42 | else if (futureDay == 2)
43 | System.out.println("Tuesday");
44 | else if (futureDay == 3)
45 | System.out.println("Wednesday");
46 | else if (futureDay == 4)
47 | System.out.println("Thursday");
48 | else if (futureDay == 5)
49 | System.out.println("Friday");
50 | else
51 | System.out.println("Saturday");
52 |
53 | input.close();
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/I/selections/problems/HeadsOrTails.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class HeadsOrTails {
4 |
5 | public static void main(String[] args) {
6 | Scanner input = new Scanner(System.in);
7 |
8 | // random number (0 or 1) representing heads or tails
9 | int random = (int) (Math.random() * 2);
10 |
11 | // user prompt to enter a guess (0 for heads, 1 for tails)
12 | System.out.print("Guess the result (0 for heads, 1 for tails): ");
13 | int guess = input.nextInt();
14 |
15 | // guess calculatios to check is correct
16 | // or incorrect and display the result
17 | if (guess == random) {
18 | if (guess == 0) {
19 | System.out.println("Correct! The result is heads.");
20 | } else {
21 | System.out.println("Correct! The result is tails.");
22 | }
23 | } else {
24 | if (guess == 0) {
25 | System.out.println("Incorrect! The result is tails.");
26 | } else {
27 | System.out.println("Incorrect! The result is heads.");
28 | }
29 | }
30 |
31 | input.close(); // Close the Scanner object
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/I/selections/problems/ISBNChecker.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class ISBNChecker {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 |
7 | // user prompt to enter the first 9 digits of the ISBN as integer
8 | System.out.print("Enter the first 9 digits of an ISBN as integer: ");
9 | int firstNineDigits = scanner.nextInt();
10 |
11 | // calculate the checksum
12 | int checksum = 0;
13 | int remainingDigits = firstNineDigits;
14 | for (int i = 9; i >= 1; i--) {
15 | int digit = remainingDigits % 10;
16 | checksum += digit * i;
17 | remainingDigits /= 10;
18 | }
19 |
20 | checksum %= 11;
21 |
22 | // determine the last digit of the ISBN
23 | char lastDigit;
24 | if (checksum == 10) {
25 | lastDigit = 'X';
26 | } else {
27 | lastDigit = (char)('0' + checksum);
28 | }
29 |
30 | // display the 10-digit ISBN
31 | System.out.println("The ISBN-10 number is " + firstNineDigits + lastDigit);
32 |
33 | // close the scanner
34 | scanner.close();
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/I/selections/problems/LineSegment.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class LineSegment {
4 | public static void main(String[] args){
5 | Scanner input = new Scanner(System.in); // Create Scanner object
6 | //Prompt the user to enter the three points for p0, p1, and p2
7 | System.out.print("Enter three for p0, p1 and p2: ");
8 | double x0 = input.nextDouble();
9 | double y0 = input.nextDouble();
10 | double x1 = input.nextDouble();
11 | double y1 = input.nextDouble();
12 | double x2 = input.nextDouble();
13 | double y2 = input.nextDouble();
14 |
15 | // Calculation point in on line segment
16 | boolean distance = !(((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)) > 0 || ((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)) < 0 || ((x2 < x0) || (y2 < y0) || (x2 > x1) || (y2 > y1))) ;
17 | System.out.print( "(" + x2 + ", " + y2 + ")" + " is" );
18 |
19 | if(!distance) {
20 | System.out.print(" not on the line segment from (" + x0 + ", " + y0 + ") to (" + x1 + ", " + y1 + ")");
21 | }
22 | else {
23 |
24 | System.out.println(" on the line segment from (" + x0 + ", " + y0 + ") to " + "(" + x1 + ", " + y1 + ")");
25 | }
26 |
27 | }
28 | }
--------------------------------------------------------------------------------
/I/selections/problems/LinearEquationUserInput.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class LinearEquationUserInput {
4 |
5 | public static void main(String[] args) {
6 | System.out.println("solve linear equaton of 2 * 2");
7 |
8 | // scanner to store user input.
9 | Scanner input = new Scanner(System.in);
10 |
11 | System.out.print("Enter value of a, b, c, d, e, f: ");
12 | double a = input.nextDouble();
13 | double b = input.nextDouble();
14 | double c = input.nextDouble();
15 | double d = input.nextDouble();
16 | double e = input.nextDouble();
17 | double f = input.nextDouble();
18 |
19 | double x = (e * d - b * f) / (a * d - b * c);
20 | double y = (a * f - e * c) / (a * d - b * c);
21 |
22 | System.out.println("x is: " + x);
23 | System.out.println("y is: " + y);
24 |
25 | if((a * d - b * c) == 0){
26 | System.err.println("The equation has no solution.");
27 | }
28 |
29 | }
30 | }
--------------------------------------------------------------------------------
/I/selections/problems/Lottery.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class Lottery {
4 |
5 | public static void main(String[] args) {
6 | // random lottery number generation
7 | // Generates a number between 100 and 999 (inclusive)
8 | int lottery = (int) (Math.random() * 900) + 100;
9 |
10 | Scanner input = new Scanner(System.in);
11 |
12 | // user prompt to enter a three-digit number within the specified range
13 | System.out.print("Enter your lottery pick (three digits between 100 and 999): ");
14 | int user_guess = input.nextInt();
15 |
16 | // Validate the user's guess to ensure it's within the specified range
17 | if (user_guess < 100 || user_guess > 999) {
18 | System.out.println("Invalid input. Please enter a three-digit number between 100 and 999.");
19 | return; // exit the program if the input is invalid
20 | }
21 |
22 | // extract digits from the lottery number and user's guess
23 | int lottery_digit_1 = lottery / 100;
24 | int lottery_digit_2 = (lottery / 10) % 10;
25 | int lottery_digit_3 = lottery % 10;
26 |
27 | int user_guess_digit_1 = user_guess / 100;
28 | int user_guess_digit_2 = (user_guess / 10) % 10;
29 | int user_guess_digit_3 = user_guess % 10;
30 |
31 | System.out.println("The lottery number is " + lottery);
32 |
33 | // check each digit of the user's guess
34 | // against each digit of the lottery number
35 | if (user_guess == lottery) {
36 | System.out.println("Exact match: you win $10,000!");
37 | } else if (user_guess_digit_1 == lottery_digit_1 || user_guess_digit_1 == lottery_digit_2 || user_guess_digit_1 == lottery_digit_3
38 | || user_guess_digit_2 == lottery_digit_1 || user_guess_digit_2 == lottery_digit_2 || user_guess_digit_2 == lottery_digit_3
39 | || user_guess_digit_3 == lottery_digit_1 || user_guess_digit_3 == lottery_digit_2 || user_guess_digit_3 == lottery_digit_3) {
40 | System.out.println("Match one digit: you win $1,000!");
41 | } else {
42 | System.out.println("Sorry, no match.");
43 | }
44 |
45 | input.close(); // Close the Scanner object
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/I/selections/problems/PalindromeNumber.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class PalindromeNumber {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 |
7 | // user prompt to enter a three-digit integer
8 | System.out.print("Enter a three-digit integer: ");
9 | int number = scanner.nextInt();
10 |
11 | // extract digits
12 | int firstDigit = number / 100;
13 | int lastDigit = number % 10;
14 |
15 | // check if it's a palindrome
16 | if (firstDigit == lastDigit) {
17 | System.out.println(number + " is a palindrome");
18 | } else {
19 | System.out.println(number + " is not a palindrome");
20 | }
21 |
22 | // close the scanner
23 | scanner.close();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/I/selections/problems/PointPositions.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class PointPositions {
4 | public static void main(String[] args){
5 | Scanner input = new Scanner(System.in); // Create Scanner object
6 | //Prompt the user to enter the three points for p0, p1, and p2
7 | System.out.print("Enter three for p0, p1 and p2: ");
8 | double x0 = input.nextDouble();
9 | double y0 = input.nextDouble();
10 | double x1 = input.nextDouble();
11 | double y1 = input.nextDouble();
12 | double x2 = input.nextDouble();
13 | double y2 = input.nextDouble();
14 |
15 | // Calculation point position
16 | double distance = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0);
17 | System.out.print( "(" + x2 + ", " + y2 + ")" + " is on the " );
18 |
19 | if (distance > 0){
20 | System.out.println("left side of the line from (" + x0 + " , " + y0 + ") to " + "(" + x1 + ", " + y1 + ")");
21 | }
22 | if (distance == 0) {
23 | System.out.println("line from (" + x0 + " , " + y0 + ") to " + "(" + x1 + ", " + y1 + ")");
24 |
25 | }
26 | if (distance < 0){
27 | System.out.println("right side of the line from (" + x0 + " , " + y0 + ") to " + "(" + x1 + ", " + y1 + ")");
28 |
29 | }
30 | }
31 | }
--------------------------------------------------------------------------------
/I/selections/problems/QuadraticEquation.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class QuadraticEquation {
4 |
5 | public static void main(String[] args) {
6 | Scanner input = new Scanner(System.in);
7 |
8 | // user prmpt for a, b, and c
9 | System.out.print("Enter a, b, c: ");
10 | double a = input.nextDouble();
11 | double b = input.nextDouble();
12 | double c = input.nextDouble();
13 |
14 | // calculate the discriminant
15 | double discriminant = b * b - 4 * a * c;
16 |
17 | // discriminant and root calculations
18 | if (discriminant > 0) {
19 | double r1 = (-b + Math.pow(discriminant, 0.5)) / (2 * a);
20 | double r2 = (-b - Math.pow(discriminant, 0.5)) / (2 * a);
21 | System.out.println("The equation has two roots " + r1 + " and " + r2);
22 | } else if (discriminant == 0) {
23 | double r = -b / (2 * a);
24 | System.out.println("The equation has one root " + r);
25 | } else {
26 | System.out.println("The equation has no real roots");
27 | }
28 |
29 | input.close();
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/I/selections/problems/Questions/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/1.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/10.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/11.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/12.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/12.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/13.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/13.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/14.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/14.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/15.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/15.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/16.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/17.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/17.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/18.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/18.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/2.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/3.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/4.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/5.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/6.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/7.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/8.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/I/selections/problems/Questions/9.png
--------------------------------------------------------------------------------
/I/selections/problems/Questions/README.md:
--------------------------------------------------------------------------------
1 | # Chapter 3: SELECTIONS
2 |
3 | ## PROGRAMMING EXERCISES
4 |
5 | 
6 | 
7 | 
8 | 
9 | 
10 | 
11 | 
12 | 
13 | 
14 | 
15 | 
16 | 
17 | 
18 | 
19 | 
20 | 
21 | 
22 | 
23 |
--------------------------------------------------------------------------------
/I/selections/problems/README.md:
--------------------------------------------------------------------------------
1 | # Chapter 3: SELECTIONS
2 |
3 | This repository contains a collection of Java programs for various problems and exercises relating to selections statements
4 | which is chapter three of this book.
5 |
6 | ## PROGRAMMING EXERCISES
7 |
8 | - [3.1 QuadraticEquation.java](QuadraticEquation.java) - Solve quadratic equations.
9 | - [3.2 AdditionQuiz.java](AdditionQuiz.java) - A Java program for a game that adds three numbers.
10 | - [3.3 LinearEquationUserInput.java](LinearEquationUserInput.java) - Solve a 2x2 linear equation based on user input.
11 | - [3.4 RandomMonth.java](RandomMonth.java) - Generate a random month.
12 | - [3.5 FutureDates.java](FutureDates.java) - Calculate future dates given a starting date and a number of days.
13 | - [3.6 BodyMassIndex.java](BodyMassIndex.java) - Calculate body mass index based on user input.
14 | - [3.7 ComputeChange.java](ComputeChange.java) - Calculate change given a purchase amount and tendered amount.
15 | - [3.8 SortThreeNumbers.java](SortThreeNumbers.java) - Sort three numbers in ascending order.
16 | - [3.9 ISBNChecker.java](ISBNChecker.java) - Check if an ISBN number is valid.
17 | - [3.10 SubtractionQuiz.java](SubtractionQuiz.java) - A Java program for a game that subtracts two numbers.
18 | - [3.11 DaysInMonth.java](DaysInMonth.java) - Determine the number of days in a given month and year.
19 | - [3.12 PalindromeNumber.java](PalindromeNumber.java) - Check if a number is a palindrome.
20 | - [3.13 ComputeTax.java](ComputeTax.java) - Calculate tax based on income and filing status.
21 | - [3.14 HeadsOrTails.java](HeadsOrTails.java) - A Java program to simulate a coin flip.
22 | - [3.15 Lottery.java](Lottery.java) - Simulate a lottery drawing.
23 | - [3.16 RandomPoint.java](RandomPoint.java) - Generate a random point in a rectangle.
24 | - [3.17 ScissorRockPaper.java](ScissorRockPaper.java) - Simulate a rock-paper-scissors game.
25 | - [3.18 ShippingCost.java](ShippingCost.java) - Calculate shipping cost based on weight and distance.
26 | - [3.19 TrianglePerimeter.java](TrianglePerimeter.java) - Calculate the perimeter of a triangle.
27 | - [3.25 Lines.java](Lines.java) - Represent lines and intersections in a coordinate system.
28 | - [3.28 TwoRectangles.java](TwoRectangles.java) - Two rectangles in java
29 | - [3.30 ShowCurrentTime.java](ShowCurrentTime.java) - Display the current time in different time zones.
30 | - [3.32 PointPositions.java](PointPositions.java) - Point positions in java
31 | - [3.33 CompareCosts.java](CompareCosts.java) - Compare the cost of two products based on weight and price.
32 | - [3.34 LineSegment.java](LineSegment.java) - Represent a line segment in a coordinate system.
33 | - [3.60 Rectangle.java](Rectangle.java) - Represent a rectangle and calculate its properties.
34 |
35 | ## All Questions are here: [README.md](Questions/README.md)
36 |
--------------------------------------------------------------------------------
/I/selections/problems/RandomMonth.java:
--------------------------------------------------------------------------------
1 | public class RandomMonth{
2 | public static void main(String[] args){
3 | int random = (int)(Math.random() * 13);
4 | if (random == 1 ){
5 | System.out.println("January");
6 | } else if(random == 2){
7 | System.out.print("February");
8 | } else if(random == 3){
9 | System.out.print("March");
10 | } else if(random == 4){
11 | System.out.print("April");
12 | } else if(random == 5){
13 | System.out.print("May");
14 | } else if(random == 6){
15 | System.out.print("June");
16 | } else if(random == 7){
17 | System.out.print("July");
18 | }else if(random == 8){
19 | System.out.print("August");
20 | } else if(random == 9){
21 | System.out.print("September");
22 | } else if(random == 10){
23 | System.out.print("October");
24 | }else if(random == 11){
25 | System.out.print("November");
26 | }else if(random == 12){
27 | System.out.print("December");
28 | }
29 | else{
30 | System.out.print("Invalid Month Number");
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/I/selections/problems/RandomPoint.java:
--------------------------------------------------------------------------------
1 | public class RandomPoint {
2 | public static void main(String[] args) {
3 | // generate random coordinates
4 | // random x-coordinate in the range [-50, 50]
5 | double x = Math.random() * 100 - 50;
6 |
7 | // random y-coordinate in the range [-100, 100]
8 | double y = Math.random() * 200 - 100;
9 |
10 | // display the random coordinate
11 | System.out.println("Random coordinate: (" + x + ", " + y + ")");
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/I/selections/problems/ScissorRockPaper.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class ScissorRockPaper {
4 | public static void main(String[] args) {
5 | // generate a random number (0 for scissor, 1 for rock, 2 for paper)
6 | int computerChoice = (int) (Math.random() * 3);
7 |
8 | // user prompt to enter a number
9 | Scanner scanner = new Scanner(System.in);
10 | System.out.print("Enter 0 for scissor, 1 for rock, or 2 for paper: ");
11 | int userChoice = scanner.nextInt();
12 |
13 | // determine the winner
14 | if (computerChoice == userChoice) {
15 | System.out.println("It's a draw!");
16 | } else if ((userChoice == 0 && computerChoice == 2) ||
17 | (userChoice == 1 && computerChoice == 0) ||
18 | (userChoice == 2 && computerChoice == 1)) {
19 | System.out.println("You win!");
20 | } else {
21 | System.out.println("You lose!");
22 | }
23 |
24 | // display the choices
25 | String computerChoiceString, userChoiceString;
26 | switch (computerChoice) {
27 | case 0:
28 | computerChoiceString = "scissor";
29 | break;
30 | case 1:
31 | computerChoiceString = "rock";
32 | break;
33 | case 2:
34 | computerChoiceString = "paper";
35 | break;
36 | default:
37 | computerChoiceString = "invalid";
38 | break;
39 | }
40 | switch (userChoice) {
41 | case 0:
42 | userChoiceString = "scissor";
43 | break;
44 | case 1:
45 | userChoiceString = "rock";
46 | break;
47 | case 2:
48 | userChoiceString = "paper";
49 | break;
50 | default:
51 | userChoiceString = "invalid";
52 | break;
53 | }
54 | System.out.println("Computer chose " + computerChoiceString);
55 | System.out.println("You chose " + userChoiceString);
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/I/selections/problems/ShippingCost.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class ShippingCost {
4 | public static void main(String[] args) {
5 | // user prompt to enter the weight of the package
6 | Scanner scanner = new Scanner(System.in);
7 | System.out.print("Enter the weight of the package in pounds: ");
8 | double weight = scanner.nextDouble();
9 |
10 | // calculate the shipping cost based on the weight
11 | double cost;
12 | if (weight <= 1) {
13 | cost = 3.5;
14 | } else if (weight <= 3) {
15 | cost = 5.5;
16 | } else if (weight <= 10) {
17 | cost = 8.5;
18 | } else if (weight <= 20) {
19 | cost = 10.5;
20 | } else {
21 | System.out.println("The package cannot be shipped.");
22 | return;
23 | }
24 |
25 | // display the shipping cost
26 | System.out.println("Shipping cost: $" + cost);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/I/selections/problems/ShowCurrentTime.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class ShowCurrentTime {
4 | public static void main(String[] args) {
5 | Scanner scanner = new Scanner(System.in);
6 |
7 | // prompt the user to enter the time zone offset to GMT
8 | System.out.print("Enter the time zone offset to GMT: ");
9 | int timeZoneOffset = scanner.nextInt();
10 |
11 | // obtain the total milliseconds since midnight, Jan 1, 1970
12 | long totalMilliseconds = System.currentTimeMillis();
13 |
14 | // obtain the total seconds since midnight, Jan 1, 1970
15 | long totalSeconds = totalMilliseconds / 1000;
16 |
17 | // compute the current second in the minute in the hour
18 | long currentSecond = totalSeconds % 60;
19 |
20 | // obtain the total minutes
21 | long totalMinutes = totalSeconds / 60;
22 |
23 | // compute the current minute in the hour
24 | long currentMinute = totalMinutes % 60;
25 |
26 | // obtain the total hours
27 | long totalHours = totalMinutes / 60;
28 |
29 | // compute the current hour
30 | long currentHour = (totalHours + timeZoneOffset) % 24;
31 |
32 | // determine if it's AM or PM
33 | String am_pm = (currentHour < 12) ? "AM" : "PM";
34 |
35 | // convert to 12-hour format
36 | currentHour = currentHour % 12;
37 | if (currentHour == 0) {
38 | currentHour = 12; // 12 AM or 12 PM
39 | }
40 |
41 | // display the current time in the specified time zone
42 | System.out.println("The current time is " + currentHour + ":" + currentMinute + ":" + currentSecond + " " + am_pm);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/I/selections/problems/SortThreeNumbers.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class SortThreeNumbers {
4 |
5 | public static void main(String[] args) {
6 | Scanner input = new Scanner(System.in);
7 | // user prompt for three numbers
8 | System.out.print("Enter three integers: ");
9 | int first_number = input.nextInt();
10 | int second_number = input.nextInt();
11 | int third_number = input.nextInt();
12 |
13 | // sort the integers
14 | // in non-decreasing order
15 | int temp;
16 | if (first_number > second_number) {
17 | temp = first_number;
18 | first_number = second_number;
19 | second_number = temp;
20 | }
21 | if (second_number > third_number) {
22 | temp = second_number;
23 | second_number = third_number;
24 | third_number = temp;
25 | }
26 | if (first_number > second_number) {
27 | temp = first_number;
28 | first_number = second_number;
29 | second_number = temp;
30 | }
31 |
32 | // display the sorted integers
33 | System.out.println("The integers in non-decreasing order are: " + first_number + " " + second_number + " " + third_number);
34 |
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/I/selections/problems/SubtractionQuiz.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class SubtractionQuiz {
4 | public static void main(String[] args) {
5 | // generate two random integers less than 100
6 | int number1 = (int)(Math.random() * 100);
7 | int number2 = (int)(Math.random() * 100);
8 |
9 | // student prompt to answer "What is number1 + number2?"
10 | System.out.print("What is " + number1 + " + " + number2 + "? ");
11 | Scanner input = new Scanner(System.in);
12 | int answer = input.nextInt();
13 |
14 | // grade the answer and display the result
15 | if (number1 + number2 == answer)
16 | System.out.println("You are correct!");
17 | else {
18 | System.out.println("Your answer is wrong.");
19 | System.out.println(number1 + " + " + number2 + " should be " + (number1 + number2));
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/I/selections/problems/TrianglePerimeter.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class TrianglePerimeter {
4 | public static void main(String[] args) {
5 | // user prompt to enter the edges of the triangle
6 | Scanner scanner = new Scanner(System.in);
7 |
8 | System.out.println("Enter the lengths of the three edges of the triangle:");
9 | double edge1 = scanner.nextDouble();
10 | double edge2 = scanner.nextDouble();
11 | double edge3 = scanner.nextDouble();
12 |
13 | // check if the input forms a valid triangle
14 | boolean isValidTriangle = (edge1 + edge2 > edge3) && (edge1 + edge3 > edge2) && (edge2 + edge3 > edge1);
15 | if (isValidTriangle) {
16 | // compute the perimeter of the triangle
17 | double perimeter = edge1 + edge2 + edge3;
18 | System.out.println("Perimeter of the triangle: " + perimeter);
19 | } else {
20 | System.out.println("Invalid input. The input does not form a valid triangle.");
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/I/selections/problems/TwoRectangles.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 | public class TwoRectangles {
3 | public static void main(String[] args){
4 | Scanner input = new Scanner(System.in);
5 | System.out.print("Enter r1's center x-"+ " , y-coordinates, width, and height: ");
6 | double r1x = input.nextDouble();
7 | double r1y = input.nextDouble();
8 | double r1Width = input.nextDouble();
9 | double r1Height = input.nextDouble();
10 |
11 | System.out.print("Enter r2's center x-"+ " , y-coordinates, width, and height: ");
12 | double r2x = input.nextDouble();
13 | double r2y = input.nextDouble();
14 | double r2Width = input.nextDouble();
15 | double r2Height = input.nextDouble();
16 |
17 | if ((Math.pow(Math.pow(r2y - r1y, 2), .05) + r2Height / 2 <= r1Height / 2) &&
18 | (Math.pow(Math.pow(r2x - r1x, 2), .05) + r2Width / 2 <= r1Width / 2) &&
19 | (r1Height / 2 + r2Height / 2 <= r1Height) &&
20 | (r1Width / 2 + r2Width / 2 <= r1Width))
21 | System.out.println("r2 is inside r1");
22 | else if ((r1x + r1Width / 2 > r2x - r2Width) ||
23 | (r1y + r1Height / 2 > r2y - r2Height))
24 | System.out.println("r2 overlaps r1");
25 | else
26 | System.out.println("r2 does not overlap r1");
27 |
28 | }
29 | }
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/.idea/Listing.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/.idea/uiDesigner.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | -
6 |
7 |
8 | -
9 |
10 |
11 | -
12 |
13 |
14 | -
15 |
16 |
17 | -
18 |
19 |
20 |
21 |
22 |
23 | -
24 |
25 |
26 |
27 |
28 |
29 | -
30 |
31 |
32 |
33 |
34 |
35 | -
36 |
37 |
38 |
39 |
40 |
41 | -
42 |
43 |
44 |
45 |
46 | -
47 |
48 |
49 |
50 |
51 | -
52 |
53 |
54 |
55 |
56 | -
57 |
58 |
59 |
60 |
61 | -
62 |
63 |
64 |
65 |
66 | -
67 |
68 |
69 |
70 |
71 | -
72 |
73 |
74 | -
75 |
76 |
77 |
78 |
79 | -
80 |
81 |
82 |
83 |
84 | -
85 |
86 |
87 |
88 |
89 | -
90 |
91 |
92 |
93 |
94 | -
95 |
96 |
97 |
98 |
99 | -
100 |
101 |
102 | -
103 |
104 |
105 | -
106 |
107 |
108 | -
109 |
110 |
111 | -
112 |
113 |
114 |
115 |
116 | -
117 |
118 |
119 | -
120 |
121 |
122 |
123 |
124 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/ComputeArea.java:
--------------------------------------------------------------------------------
1 | public class ComputeArea {
2 | public static void main(String[] args){
3 | double radius;
4 | double area;
5 | radius = 20; //radius is now 20
6 |
7 | //Compute area
8 | area = radius * radius * 3.14159;
9 |
10 | //Display results
11 | System.out.println("The area for the circle of radius " + radius + " is " + area);
12 |
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/ComputeAreaWithConsoleInput.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner; //Scanner is in the java.util package
2 | public class ComputeAreaWithConsoleInput {
3 | public static void main(String[] args){
4 | //Create a Scanner object
5 | Scanner input = new Scanner(System.in);
6 |
7 | //Prompt the user to enter a radius
8 | System.out.print("Enter a number for radius: ");
9 | double radius = input.nextDouble();
10 |
11 | //Compute area
12 | double area = radius * radius * 3.141519;
13 |
14 | //Display results
15 | System.out.println("The area for the circle of radius " + radius + " is " + area);
16 |
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/ComputeAreaWithConstant.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner; //Scanner is in the java.util package
2 | public class ComputeAreaWithConstant {
3 | public static void main(String[] args){
4 | final double PI = 3.141519; //Declare a constant
5 | //Create a Scanner object
6 | Scanner input = new Scanner(System.in);
7 |
8 | //Prompt the user to enter a radius
9 | System.out.print("Enter a number for radius: ");
10 | double radius = input.nextDouble();
11 |
12 | //Compute area
13 | double area = radius * radius * PI;
14 |
15 | //Display result
16 | System.out.println("The area for circle of radius " + radius + " is " + area);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/ComputeAverage.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner; //Scanner is in the java.util package
2 |
3 | public class ComputeAverage {
4 | public static void main(String[] args){
5 | //Create a Scanner object
6 | Scanner input = new Scanner(System.in);
7 |
8 | //Prompt the user to enter three numbers
9 | System.out.print("Enter three numbers: ");
10 | double number1 = input.nextDouble();
11 | double number2 = input.nextDouble();
12 | double number3 = input.nextDouble();
13 |
14 | //Compute average
15 | double average = (number1 + number2 + number3) / 3;
16 |
17 | //Display results
18 | System.out.println("The average of " + number1 + " " + number2 + " " + number3 + " is " + average);
19 |
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/ComputeChange.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 | public class ComputeChange {
3 | public static void main(String[] args){
4 | //Create a Scanner
5 | Scanner input = new Scanner(System.in);
6 |
7 | //Recevie the amount
8 | System.out.print("Enter an amount in Double: ");
9 | double amount = input.nextDouble();
10 |
11 | int remainingAmount = (int)(amount * 100);
12 |
13 | //Find the number of one dollars
14 | int numberOfOneDollars = remainingAmount / 100;
15 | remainingAmount = remainingAmount % 100;
16 |
17 | //Find the number of Quarters in the remaining amount
18 | int numberOfQuarters = remainingAmount / 25;
19 | remainingAmount = remainingAmount % 25;
20 |
21 | //find the number of dimes in the remaining amount
22 | int numberOfDimes = remainingAmount / 10;
23 | remainingAmount = remainingAmount % 10;
24 |
25 | //find the number of nickels in the remaining amount
26 | int numberOfNickels = remainingAmount / 5;
27 | remainingAmount = remainingAmount % 5;
28 |
29 | //find the number of pennies in the remaining amount
30 | int numberOfPennies = remainingAmount;
31 |
32 | //Display results
33 | System.out.println("Your amount " + amount + " consists of");
34 | System.out.println(" " + numberOfOneDollars + " dollars");
35 | System.out.println(" " + numberOfQuarters + " quaters");
36 | System.out.println(" " + numberOfDimes + " dimes");
37 | System.out.println(" " + numberOfNickels + " nickels");
38 | System.out.println(" " + numberOfPennies + " Pennies");
39 |
40 | }
41 | }
42 |
43 |
44 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/ComputeLoan.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 | public class ComputeLoan {
3 | public static void main(String[] args){
4 | //Create a Scanner
5 | Scanner input = new Scanner(System.in);
6 |
7 | //Enter annual interest rate in percentage, e.g., 7.25%
8 | System.out.print("Enter annual interest rate: ");
9 | double annualInterestRate = input.nextDouble();
10 |
11 | //Obtain monthly interest rate
12 | double monthlyInterestRate = annualInterestRate / 1200;
13 |
14 | //Enter Number of years as an integer.
15 | System.out.print("Enter Number of years as an integer: ");
16 | int numberOfYears = input.nextInt();
17 |
18 | //Enter loan amount
19 | System.out.print("Enter loan amount: ");
20 | double loanAmount = input.nextDouble();
21 |
22 | //Calculate payment
23 | double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1/ Math.pow(1 + monthlyInterestRate, numberOfYears *12));
24 |
25 | double totalPayment = monthlyPayment * numberOfYears * 12;
26 |
27 | //Display results
28 | System.out.println("The monthly payment is $" + (int)(monthlyPayment * 100) / 100.0);
29 | System.out.println("The total payment is $" + (int)(totalPayment * 100) / 100.0);
30 | }
31 | }
32 |
33 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/DisplayTime.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner; //Scanner is in the java.util package
2 | public class DisplayTime {
3 | public static void main (String[] args){
4 | Scanner input = new Scanner(System.in);
5 | //Prompt the user for input
6 | System.out.print("Enter an integer for seconds: ");
7 | int seconds = input.nextInt();
8 | //find minutes in seconds
9 | int minutes = seconds / 60;
10 | // Seconds remaining
11 | int remainingSeconds = seconds % 60;
12 | System.out.println(seconds + " seconds is " + minutes + " minutes and " + remainingSeconds + " seconds");
13 |
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/FahrenheitToCelsius.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner; //Scanner is in the java.util package
2 | public class FahrenheitToCelsius {
3 | public static void main(String[] args){
4 | Scanner input = new Scanner(System.in);
5 |
6 | System.out.print("Enter a degree in Fahrenheit: ");
7 | double fahrenheit = input.nextDouble();
8 |
9 | //Convert Fahrenheit to Celsius
10 | double celsius = (5.0 / 9) * (fahrenheit - 32);
11 | System.out.println("Fahrenheit " + fahrenheit + " is " + celsius + " in Celsius");
12 |
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/SalesTax.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 | public class SalesTax {
3 | public static void main(String[] args) {
4 | Scanner input = new Scanner(System.in);
5 |
6 | System.out.print("Enter purchase amount: ");
7 | double purchaseAmount = input.nextDouble();
8 |
9 | double tax = purchaseAmount * 0.06;
10 | System.out.println("Sales tax is $" + (int) (tax * 100) / 100.0);
11 | }
12 | }
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/ShowCurrentTime.java:
--------------------------------------------------------------------------------
1 | public class ShowCurrentTime {
2 | public static void main(String[] args){
3 | //You can invoke System.currentTimeMillis() to return the current time.
4 |
5 | //Obtain the total milliseconds since midnight, jan 1, 1970
6 | long totalMilliseconds = System.currentTimeMillis();
7 |
8 | //Obtain the total seconds since in the minute in the hour
9 | long totalSeconds = totalMilliseconds / 1000;
10 |
11 | //Compute the current second in the minute in the hour
12 | long currentSecond = totalSeconds % 60;
13 |
14 | //Obtain the total minutes
15 | long totalMinutes = totalSeconds / 60;
16 |
17 | //Compute the total minutes
18 | long currentMinute = totalMinutes % 60;
19 |
20 | // Obtain the total hours
21 | long totalHours = totalMinutes / 60;
22 |
23 | //Compute the current minute in the Hour
24 | long currentHour = totalHours % 24;
25 |
26 | //Display results
27 | System.out.println("Current time is " + currentHour + ":" + currentMinute + ":" + currentSecond + " GMT" );
28 | }
29 | }
30 |
31 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/out/production/Listing/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/out/production/Listing/.idea/Listing.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/out/production/Listing/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/out/production/Listing/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/out/production/Listing/.idea/uiDesigner.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | -
6 |
7 |
8 | -
9 |
10 |
11 | -
12 |
13 |
14 | -
15 |
16 |
17 | -
18 |
19 |
20 |
21 |
22 |
23 | -
24 |
25 |
26 |
27 |
28 |
29 | -
30 |
31 |
32 |
33 |
34 |
35 | -
36 |
37 |
38 |
39 |
40 |
41 | -
42 |
43 |
44 |
45 |
46 | -
47 |
48 |
49 |
50 |
51 | -
52 |
53 |
54 |
55 |
56 | -
57 |
58 |
59 |
60 |
61 | -
62 |
63 |
64 |
65 |
66 | -
67 |
68 |
69 |
70 |
71 | -
72 |
73 |
74 | -
75 |
76 |
77 |
78 |
79 | -
80 |
81 |
82 |
83 |
84 | -
85 |
86 |
87 |
88 |
89 | -
90 |
91 |
92 |
93 |
94 | -
95 |
96 |
97 |
98 |
99 | -
100 |
101 |
102 | -
103 |
104 |
105 | -
106 |
107 |
108 | -
109 |
110 |
111 | -
112 |
113 |
114 |
115 |
116 | -
117 |
118 |
119 | -
120 |
121 |
122 |
123 |
124 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/out/production/Listing/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/out/production/Listing/ComputeArea.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/II/ElementryProgramming/Listing/out/production/Listing/ComputeArea.class
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/out/production/Listing/ComputeAreaWithConsoleInput.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/II/ElementryProgramming/Listing/out/production/Listing/ComputeAreaWithConsoleInput.class
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/out/production/Listing/ComputeAreaWithConstant.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/II/ElementryProgramming/Listing/out/production/Listing/ComputeAreaWithConstant.class
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/out/production/Listing/ComputeAverage.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/II/ElementryProgramming/Listing/out/production/Listing/ComputeAverage.class
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/out/production/Listing/DisplayTime.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/II/ElementryProgramming/Listing/out/production/Listing/DisplayTime.class
--------------------------------------------------------------------------------
/II/ElementryProgramming/Listing/out/production/Listing/FahrenheitToCelsius.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/II/ElementryProgramming/Listing/out/production/Listing/FahrenheitToCelsius.class
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Annu Kumari
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ###### Updated whenever there is a change
2 |
3 | # Java-Questions
4 |
5 | This repository is for recognizing and solving Java programming questions sourced from "Introduction to JAVA programming comprehensive edition 10th edition" by Y. Daniel Liang. It aims to enhance Java proficiency through puzzle-solving.
6 |
7 | ## Table of Contents
8 |
9 | 1. [Directory or Repository Structure](#directory-or-repository-structure)
10 | 2. [Usage](#usage)
11 | 3. [License](#license)
12 | 4. [Contribution](#contribution)
13 |
14 | ## Directory or Repository Structure
15 |
16 | The repository includes:
17 |
18 | - Java programming fundamentals
19 | - Object-oriented programming
20 | - GUI programming with JavaFX
21 | - Data structures and algorithms
22 | - Advanced Java programming concepts
23 |
24 | ### Fundamentals of Programming
25 | Introduces Java basics like variables, control flow, methods, and arrays.
26 | (Chapter 1) and fundamental programming techniques
27 | with primitive data types, variables, constants, assignments, expressions, and operators (Chapter 2),
28 | selection statements (Chapter 3), mathematical functions, characters, and strings (Chapter 4), loops
29 | (Chapter 5), methods (Chapter 6), and arrays (Chapters 7–8)
30 |
31 | ### Object-Oriented Programming
32 | Covers classes, inheritance, polymorphism, exceptions, abstract classes, and interfaces.
33 | (Chapters 9–10), class inheritance (Chapter 11), polymorphism
34 | (Chapter 11), exception handling (Chapter 12), abstract classes (Chapter 13), and interfaces
35 | (Chapter 13).
36 |
37 |
38 | ## Usage
39 |
40 | Clone the reposirory and start coding or adding any other files
41 | ## License
42 |
43 | This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
44 |
45 | ## Contribution
46 |
47 | Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct
48 | and the process for submitting pull requests.
49 |
--------------------------------------------------------------------------------
/out/production/Java book/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/out/production/Java book/.idea/Java book.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/out/production/Java book/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/out/production/Java book/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/out/production/Java book/ComputeArea.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/out/production/Java book/ComputeArea.class
--------------------------------------------------------------------------------
/out/production/Java book/ComputeAverage.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/out/production/Java book/ComputeAverage.class
--------------------------------------------------------------------------------
/out/production/Java book/DisplayTime.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/out/production/Java book/DisplayTime.class
--------------------------------------------------------------------------------
/out/production/Java book/IncreDecre.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/out/production/Java book/IncreDecre.class
--------------------------------------------------------------------------------
/out/production/Java book/ScannersObject.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/out/production/Java book/ScannersObject.class
--------------------------------------------------------------------------------
/out/production/Java book/ShowCurrentTime.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/annuk123/Java-Questions/e171a0bbafa663f6e6a4027a66e7906b737f3813/out/production/Java book/ShowCurrentTime.class
--------------------------------------------------------------------------------