0% found this document useful (0 votes)
7 views14 pages

Java Programs for Basic Math and Logic

The document contains multiple Java programs demonstrating various programming concepts such as input/output operations, arithmetic calculations, class creation, and control structures. Key functionalities include calculating sums and averages, checking for multiples, managing bank account transactions, processing employee salary information, and sorting arrays. Each program includes user interaction and outputs results based on the provided inputs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views14 pages

Java Programs for Basic Math and Logic

The document contains multiple Java programs demonstrating various programming concepts such as input/output operations, arithmetic calculations, class creation, and control structures. Key functionalities include calculating sums and averages, checking for multiples, managing bank account transactions, processing employee salary information, and sorting arrays. Each program includes user interaction and outputs results based on the provided inputs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

/*PROGRAM TO INPUT THREE INTEGERS FROM USER AND PERFORM

FOLLOWING OPERATIONS SUM, AVERAGE, PRODUCT, LARGEST, SMALLEST.


SYCSE-B (268) */

import [Link];
class Operations {
public static void main(String[] args) {
Scanner num = new Scanner([Link]);

[Link]("Enter First Number: ");


int number1 = [Link]();
[Link]("Enter Second Number: ");
int number2 = [Link]();
[Link]("Enter Third Number: ");
int number3 = [Link]();

int sum = number1 + number2 + number3;


double average = sum / 3.0;
int product = number1 * number2 * number3;
int largest = [Link](number1, [Link](number2, number3));
int smallest = [Link](number1, [Link](number2, number3));

[Link]("Sum = "+ sum);


[Link]("Average = "+ average);
[Link]("Product = "+ product);
[Link]("Largest = "+ largest);
[Link]("Smallest = "+ smallest);
}
}
/********************************OUTPUT*************************
Enter First Number: 5
Enter Second Number: 2
Enter Third Number: 6
Sum = 13
Average = 4.333333333333333
Product = 60
Largest = 6
Smallest = 2 */

================================================================
//PROGRAM TO CHECK FIRST NUMBER IS THE MULTIPLE OF THE SECOND
NUMBER SYCSE-B (268)

import [Link];
public class Multiplenum {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter First number: ");
int a = [Link]();
[Link]("Enter Second number: ");
int b = [Link]();
if (a%b==0) {
[Link](a +" Multiple of "+ b);
}
else {
[Link](a +" Not Multiple of "+ b);
}
}
}
/******************************OUTPUT***************************
Enter First number: 25
Enter Second number: 5
25 Multiple of 5 */

================================================================

//APPLICATION THAT INPUT FIND NUMBERS AND DETERMINE AND PRINT


THE NUMBERS POSITIVE NUMBERS, NEGETIVE NUMBERS, AND THE
NUMBERS OF ZERO SYCSE-B (268)

import [Link];
public class Findnum {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int positives = 0, negatives = 0, zeros = 0;
[Link]("Enter how many numbers: ");
int n = [Link]();
[Link]("Enter " + n + " numbers:");
for (int i = 0; i < n; i++) {
int num = [Link]();
if (num > 0) {
positives++;
} else if (num < 0) {
negatives++;
} else {
zeros++;
}
}
[Link]("Number of Positive Numbers: " + positives);
[Link]("Number of Negative Numbers: " + negatives);
[Link]("Number of Zeros: " + zeros);
}
}
/*******************************OUTPUT**************************
Enter how many numbers: 6
Enter 6 numbers:
0 1 3 -5 -4 3
Number of Positive Numbers: 3
Number of Negative Numbers: 2
Number of Zeros: 1 */

================================================================

//CREATE CLASS ACCOUNT TO PROVIDE A METHOD CALLED DEBIT THAT


WITHDRAWS MONEY FROM AN ACCOUNT. ENSURE THAT THE DEBIT
AMOUNT DOES NOT EXCEED THE ACCOUNT'S BALANCE. IF IT DOES, THE
BALANCE SHOULD BE LEFT UNCHANGED, AND THE METHOD SHOULD PRINT A
MESSAGE INDICATING "DEBIT AMOUNT EXCEEDED COUNT BALANCE."
MODIFY CLASS ACCOUNT TEST TO TEST METHOD DEBIT (268)

import [Link];
class Account {
private double balance;
public Account(double initialBalance) {
if (initialBalance > 0.0) {
balance = initialBalance;
}
}
public void credit(double amount) {
balance += amount;
}
public void debit(double amount) {
if (amount > balance) {
[Link]("Debit amount exceeded account balance.");
} else {
balance -= amount;
[Link]("Debit successful! Withdrawn: " + amount);
}
}
public double getBalance() {
return balance;
}
}
public class AccountTest {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter initial balance: ");


double initialBalance = [Link]();
Account myAccount = new Account(initialBalance);
[Link]("Current balance: " + [Link]());
[Link]("Enter amount to debit: ");
double debitAmount = [Link]();
[Link](debitAmount);
[Link]("Remaining balance: " + [Link]());
[Link]();
}
}
/******************************OUTPUT***************************
Enter initial balance: 1000
Current balance: 1000.0
Enter amount to debit: 500
Debit successful! Withdrawn: 500.0
Remaining balance: 500.0 */
//CREATE A CLASS CALLED EMPLOYEE THAT INCLUDES THREE INSTANCE
VARIABLES A FIRST NAME (TYPE STRING), A LAST NAME (TYPE STRING) AND A
MONTHLY SALARY (DOUBLE). PROVIDE A CONSTRUCTOR THAT INITIALIZES
THE THREE INSTANCE VARIABLES. PROVIDE A SET AND A GET METHOD FOR
EACH INSTANCE VARIABLE. IF THE MONTHLY SALARY IS NOT POSITIVE, DO
NOT SET ITS VALUE. WRITE A TEST APPLICATION NAMED EMPLOYEE TEST
THAT DEMONSTRATES CLASS EMPLOYEE'S CAPABILITIES. CREATE TWO
EMPLOYEE OBJECTS AND DISPLAY EACH OBJECT'S YEARLY SALARY. THEN GIVE
EACH EMPLOYEE A 10% RAISE AND DISPLAY EACH EMPLOYEE'S YEARLY
SALARY AGAIN (268)
class Employee {
private String firstName;
private String lastName;
private double monthlySalary;

public Employee(String firstName, String lastName, double monthlySalary) {


[Link] = firstName;
[Link] = lastName;

if (monthlySalary > 0.0) {


[Link] = monthlySalary;
} else {
[Link] = 0.0; // default to 0 if invalid
}
}
public void setFirstName(String firstName) {
[Link] = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
[Link] = lastName;
}
public String getLastName() {
return lastName;
}
public void setMonthlySalary(double monthlySalary) {
if (monthlySalary > 0.0) {
[Link] = monthlySalary;
}
}
public double getMonthlySalary() {
return monthlySalary;
}
public double getYearlySalary() {
return monthlySalary * 12;
}
public void giveRaise(double percent) {
if (percent > 0) {
monthlySalary += monthlySalary * percent / 100;
}
}
}
public class EmployeeTest {
public static void main(String[] args) {
Employee emp1 = new Employee("Vaishnavi", "Keshatwar", 50000);
Employee emp2 = new Employee("Vaishu", "Keshatwar", 60000);

[Link]("Yearly Salaries before raise:");


[Link]([Link]() + " " + [Link]() +
": $" + [Link]());
[Link]([Link]() + " " + [Link]() +
": $" + [Link]());

[Link](10);
[Link](10);

[Link]("\nYearly Salaries after 10% raise:");


[Link]([Link]() + " " + [Link]() +
": $" + [Link]());
[Link]([Link]() + " " + [Link]() +
": $" + [Link]());
}
}
/******************************OUTPUT***************************
Yearly Salaries before raise:
Vaishnavi Keshatwar: $600000.0
Vaishu Keshatwar: $720000.0
Yearly Salaries after 10% raise:
Vaishnavi Keshatwar: $660000.0
Vaishu Keshatwar: $792000.0 */

================================================================

//JAVA PROGRAM ON COUNTER CONTROLED LOOP WRITE A PROGRAM FOR


THE FOLLOWING PROBLEM STATEMENT. A CLASS OF 10 STUDENTS TO QUIZ,
THE GRADES RANGE (0-100) FOR THIS QUIZ, AVALABLE TO YOU DETARMINE
THE TOTAL GRADES & AVERAGE ON THE QUIZ (268)

import [Link];
public class Quiz {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int total = 0, grade, stud = 10;
for (int i = 0; i < stud; i++) {
[Link]("Enter Grade: ");
grade = [Link]();
if (grade > 0 && grade <= 100)
{
total += grade;
}
else {
[Link]("Invaild Grade.");
i--;
}
}
double avg = (double) total / stud;
[Link]("Total Grades= " + total);
[Link]("Avarage of Grade= " + avg);
[Link]();
}
}
/********************************OUTPUT*************************
Enter Grade: 10
Enter Grade: 20
Enter Grade: 30
Enter Grade: 40
Enter Grade: 50
Enter Grade: 60
Enter Grade: 70
Enter Grade: 80
Enter Grade: 90
Enter Grade: 100
Total Grades= 550
Avarage of Grade= 55.0 */

================================================================

//WAP FOR A SENTIMENTAL CONTROL LOOP DEVELOP A CLASS AVERAGE IN


PROGRAM THAT PROCESS GRADES FOR AN ARBITARI NUMBER OF STUDENTS
FOR EACH TIME ITS RUN (268)

import [Link];
public class Student {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int total = 0;
int count = 0;
int grade;
[Link]("Enter grades for students (enter -1 to finish): ");
grade = [Link]();

while (grade != -1) {


total += grade;
count++;

[Link]("Enter next grade (-1 to finish): ");


grade = [Link]();
}
if (count != 0) {
double average = (double) total / count;
[Link]("\nNumber of students: " + count);
[Link]("Total of grades: " + total);
[Link]("Class average: %.2f\n", average);
} else {
[Link]("\nNo grades were entered.");
}
[Link]();
}
}
/******************************OUTPUT***************************
Enter grades for students (enter -1 to finish): 95
Enter next grade (-1 to finish): 96
Enter next grade (-1 to finish): 90
Enter next grade (-1 to finish): 80
Enter next grade (-1 to finish): 85
Enter next grade (-1 to finish): -1

Number of students: 5
Total of grades: 446
Class average: 89.20 */

================================================================

/* DEVELOP PROGRAMS TO DEMONSTRATE USE OF SENTINEL-CONTROLLED


REPETITION: DEVELOP A CLASS-AVERAGING PROGRAM THAT PROCESSES
GRADES FOR AN ARBITRARY NUMBER OF STUDENTS EACH TIME ITS RUN
(268) */

import [Link];
public class ClassAverage {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

int total = 0;
int count = 0;
int grade;
[Link]("Enter grades for students (enter -1 to finish):");
grade = [Link]();

while (grade != -1) {


total += grade;
count++;

[Link]("Enter next grade (-1 to finish): ");


grade = [Link]();
}
if (count != 0) {
double average = (double) total / count;
[Link]("\nNumber of students: " + count);
[Link]("Total of grades: " + total);
[Link]("Class average: %.2f\n", average);
} else {
[Link]("\nNo grades were entered.");
}

[Link]();
}
}
/******************************OUTPUT***************************
Enter grades for students (enter -1 to finish):10
Enter next grade (-1 to finish): 20
Enter next grade (-1 to finish): 30
Enter next grade (-1 to finish): 40
Enter next grade (-1 to finish): 50
Enter next grade (-1 to finish): -1

Number of students: 5
Total of grades: 150
Class average: 30.00 */

================================================================

/* DEVELOP PROGRAMS TO DEMONSTRATE USE OF SWITCH CASE:


AN ONLINE RETAILER SELLS FIVE PRODUCTS WHOSE RETAIL PRICES ARE AS
FOLLOWS: PRODUCT 1, $2.98; PRODUCT 2,$4.50;PRODUCT 3, $9.98;PRODUCT
4, $4.49 AND PRODUCT 5, $6.87. WRITE AN APPLICATION THAT READS A
SERIES OF PAIRS OF NUMBERS AS FOLLOWS: PRODUCT NUMBER, QUANTITY
SOLD. YOUR PROGRAM SHOULD USE A SWITCH STATEMENT TO DETERMINE
THE RETAIL PRICE FOR EACH PRODUCT. IT SHOULD CALCULATE AND DISPLAY
THE TOTAL RETAIL VALUE OF ALL PRODUCTS SOLD. (268) */

import [Link];
public class RetailStore {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int productNumber;
int quantity;
double totalRetailValue = 0.0; // total sales value

[Link]("Online Retailer - Product Sales Calculator");


[Link]("Product List:");
[Link]("1: $2.98");
[Link]("2: $4.50");
[Link]("3: $9.98");
[Link]("4: $4.49");
[Link]("5: $6.87");
[Link]("Enter product number and quantity sold (Enter -1 to
stop):");

[Link]("\nEnter product number (-1 to stop): ");


productNumber = [Link]();

while (productNumber != -1) {


[Link]("Enter quantity sold: ");
quantity = [Link]();
double price = 0.0;

switch (productNumber) {
case 1:
price = 2.98;
break;
case 2:
price = 4.50;
break;
case 3:
price = 9.98;
break;
case 4:
price = 4.49;
break;
case 5:
price = 6.87;
break;
default:
[Link]("Invalid product number!");
price = 0.0;
}
totalRetailValue += price * quantity;

[Link]("\nEnter product number (-1 to stop): ");


productNumber = [Link]();
}
[Link]("\nTotal retail value of all products sold: $%.2f\n",
totalRetailValue);
[Link]();
}
}
/******************************OUTPUT***************************
Online Retailer - Product Sales CalculatorProduct List:
1: $2.98
2: $4.50
3: $9.98
4: $4.49
5: $6.87
Enter product number and quantity sold (Enter -1 to stop):
Enter product number (-1 to stop): 2
Enter quantity sold: 1

Enter product number (-1 to stop): 3


Enter quantity sold: 2

Enter product number (-1 to stop): -1

Total retail value of all products sold: $24.46 */


//WRITE A PROGRAM TO ACCEPT AN ARRAY FROM USER AND SORT IT IN
ASCENDING ORDER (268)

import [Link];
import [Link];

public class SortArray {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter the size of the array: ");


int n = [Link]();
int[] arr = new int[n];
[Link]("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
[Link](arr);
[Link]("Sorted array in ascending order:");
for (int num : arr) {
[Link](num + " ");
}
[Link]();
}
}
/*******************************OUTPUT**************************
Enter the size of the array: 5
Enter 5 elements:
23861
Sorted array in ascending order:
1 2 3 6 8 */

================================================================

//WRITE A PROGRAM TO CALCULATE THE FREQUENCY OF FACES OF SIX-SIDED


DICE IF IT IS ROLLED 100 TIMES USING ARRAY (268)

import [Link];
public class DiceFrequency {
public static void main(String[] args) {
int[] frequency = new int[6];
Random rand = new Random();
for (int i = 0; i < 100; i++) {
int face = [Link](6) + 1;
frequency[face - 1]++;
}
[Link]("Face\tFrequency");
for (int i = 0; i < 6; i++) {
[Link]((i + 1) + "\t" + frequency[i]);
}
}
}
/******************************OUTPUT***************************
Face Frequency
1 16
2 19
3 13
4 15
5 16
6 21
--------------------------------------
Face Frequency
1 22
2 19
3 12
4 19
5 14
6 14 */

Common questions

Powered by AI

The 'Multiplenum' class checks if one number is a multiple of another by performing a modulus operation. It takes two integers from the user and checks if the first integer modulo the second integer equals zero. If true, the first is a multiple of the second; otherwise, it is not .

The 'DiceFrequency' program simulates rolling a six-sided die 100 times using the Random class. For each roll, a random number between 1 and 6 is generated, representing a dice face. The program increments the corresponding index in an integer array ‘frequency’ to track outcomes. This process allows accumulating how often each side appears, and the results are printed as frequency distributions for each face .

The choice of using a switch statement in the 'RetailStore' program simplifies determining the retail price for each product type based on the product number. This choice enhances code readability by clearly mapping each product to its respective price, making the code easy to manage and update, particularly when adjusting prices or adding new products. The structured approach aids maintainability and minimizes the risk of errors compared to multiple if statements .

The 'Employee' class is designed to encapsulate employee information, including first name, last name, and monthly salary, as private instance variables. It provides constructors and getter/setter methods to initialize and modify these fields. The design supports encapsulation, preventing direct access to the fields and ensuring data validation, such as enforcing non-negative salaries. The class also includes methods to compute the yearly salary and apply raises appropriately, demonstrating robust object-oriented principles by combining data representation with relevant functionality .

The 'Student' program employs a sentinel value (-1) to signal the end of user input for student grades. This allows flexibility in handling an arbitrary number of entries without predefining the quantity. The use of a sentinel value efficiently concludes the input loop and calculates the results without requiring a fixed count, thereby enhancing the program's adaptability and user control .

The Java class 'Operations' performs several key operations on three user-input integers: sum, average, product, largest, and smallest. 1. **Sum**: It adds the three integers directly. 2. **Average**: It divides the sum by 3.0 for floating-point division. 3. **Product**: It multiplies the three integers directly. 4. **Largest**: It uses the Math.max function to determine the maximum value among the three integers. 5. **Smallest**: It uses the Math.min function to determine the minimum value among the three integers .

The 'Quiz' program handles errors during grade entry by implementing a validation check within its loop. If a grade entered by the user is not between 0 and 100, the program prints 'Invalid Grade.' and allows re-entry for the same student by decrementing the loop counter, effectively discarding the invalid entry .

The 'Account' class implements a method called 'debit' to handle withdrawals. If the withdrawal amount exceeds the current balance, the method prints a message: 'Debit amount exceeded account balance,' and the balance remains unchanged . Otherwise, it subtracts the amount from the balance and prints a success message with the withdrawn amount .

The 'SortArray' class sorts the input array in ascending order by utilizing the Arrays.sort() method. This internally applies a Dual-Pivot Quicksort algorithm to rearrange the elements. As the method is part of the Java standard library, it ensures efficient sorting performance and correctness .

The 'Employee' class uses a method called 'giveRaise' to handle salary increases. This method takes a percentage as input and checks if it is positive. Then it increases the current monthly salary by this percentage. The calculation safely updates the salary by adding the current salary multiplied by the percentage divided by 100, ensuring arithmetic operations are correctly applied .

You might also like