[Go to site: main page, start]

0% found this document useful (0 votes)
43 views19 pages

Java Programs by Vaishnavi Rajesh

The document contains the solutions to 5 Java assignment questions. It includes code samples for calculating the maximum number from command line arguments, calculating sums and averages of even and odd numbers, designing a bank account class with deposit, withdraw, and balance methods, performing string operations like conversion between cases, length, substring matching, and concatenation, and performing array addition and matrix multiplication.

Uploaded by

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

Java Programs by Vaishnavi Rajesh

The document contains the solutions to 5 Java assignment questions. It includes code samples for calculating the maximum number from command line arguments, calculating sums and averages of even and odd numbers, designing a bank account class with deposit, withdraw, and balance methods, performing string operations like conversion between cases, length, substring matching, and concatenation, and performing array addition and matrix multiplication.

Uploaded by

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

Java Assignment

Name :Vaishnavi Rajesh Nagarkar

PRN :10303320181124510060

[Link] a program to input n numbers on command line argument and


calculate maximum of them

Ans:

public class Max{

public static void main(String[] args) {

if ([Link] == 0){

[Link]("You must enter at least 1 integer. Please try again.");

[Link](0);

int totalInput = [Link];

int commandLineNumber[] = new int[totalInput];

//convert string into integer.

for(int i = 0; i < totalInput; i++){

commandLineNumber[i] = [Link](args[i]);

//find maximum number


int maxNumber = commandLineNumber[0];

for(int i = 1; i < totalInput; i++){

if(commandLineNumber[i] > maxNumber){

maxNumber = commandLineNumber[i];

[Link]("Maximum number is "+maxNumber);

Output :
$javac [Link]

$java Max 5 6 7 8 20

Maximum number is 20

[Link] a program to print the sum and average of the even and odd numbers
of first ten natural numbers.

Ans:

//program to print the sum and average of the even and odd numbers of first ten
natural numbers.
import [Link].*;

import [Link].*;

public class SumAverage {

static void sum_avg_of_even_num(int n)

// sum of first n even numbers

int sum = 0;

for (int i = 1; i <= n; i++)

sum += 2*i;

// calculating Average

[Link]("Sum of first " +n+ " even natural numbers is " +sum);

[Link]("Average of first " +n+ " even natural numbars is " +(sum
/ n));

static void sum_avg_of_odd_num(int n)

// sum of first n odd numbers

int sum = 0;

for (int i = 0; i < n; i++)

sum += ( 1 + (2*i));
// calculating Average

[Link]("Sum of first " +n+" odd natural numbers is " +sum);

[Link]("Average of first " +n+ " odd natural numbars is " + (sum
/ n));

public static void main (String[] args) {

int n = 10;

sum_avg_of_even_num(n);

sum_avg_of_odd_num(n);

Output :
Sum of first 10 even natural numbers is 110

Average of first 10 even natural numbars is 11

Sum of first 10 odd natural numbers is 100

Average of first 10 odd natural numbars is 10

[Link] a class for a bank database the database should support the following operations.
1. Deposit a certain amount into an account,
2. Withdrawing a certain amount from an account,
3. Return a value specifying the amount (i.e. balance) in an amount.

Ans :

import [Link].*;

import [Link];

public class BankAccount {

public static void main(String[] args) {

double startBalance = 0;

double deposite;

double withdraw;

double totalwithdraw = 0;

double totaldeposite = 0;

int count =0;

Scanner key = new Scanner([Link]);

[Link]("Please enter the starting balance");

startBalance=[Link]();

[Link]("Please enter number of transaction you wnat to do");


int b=[Link]();

while(count < b){

[Link]("Enter the method number to execute. \n [Link] Balance\n


[Link] \n [Link] \n");

int a=[Link]();

switch(a)

case 1:

[Link]("Account Balance Rs."+startBalance);

break;

case 2:

[Link]("Please enter the amount to be withdraw");

withdraw=[Link]();

if(withdraw > startBalance){

[Link]("\nThere is less amount in balance than withdraw amount\n You


are not able to withdraw");

else{

totalwithdraw += withdraw;

[Link]("Total withdraws Rs."+totalwithdraw);

startBalance -= withdraw;
[Link]("Account Balance Rs."+startBalance);

break;

case 3:

[Link]("Please enter the amount deposited");

deposite = [Link]();

totaldeposite += deposite;

startBalance += deposite;

[Link]("Total deposits Rs."+totaldeposite);

[Link]("Account Balance Rs."+startBalance);

break;

default:

[Link]("Method not found");

break;

count += 1;

}
Output :

Please enter the starting balance

400

Please enter number of transaction you want to do

Enter the method number to execute.

[Link] Balance

[Link]

[Link]

Please enter the amount to be withdraw

50

Total withdraws Rs.50.0

Account Balance Rs.350.0

Enter the method number to execute.

[Link] Balance

[Link]

[Link]

Please enter the amount deposited

600
Total deposits Rs.600.0

Account Balance Rs.950.0

[Link] a program to perform operations on given string


[Link] any string into upper case to lower case and vice versa.
[Link] length of a string
[Link] the substring
[Link] out location of certain letter.
[Link] two strings
[Link] any two strings.

Ans :

import [Link];

import [Link].*;

public class TwoString

public static void main(String[] args)

Scanner sc = new Scanner([Link]);

String[] input = new String[2];

String a, b ,c;

int temp;

[Link]("Please enter two Strings: ");


input = [Link]().split(" ");

a= input[0];

b= input[1];

[Link]("You input: " + a + " and " + b);

//convert any string into upper case to lower case and vice versa

[Link]("Lowercase of " + a + " is " +[Link]() + " and Lowercase of " +


b + " is " + [Link]());

[Link]("Uppercase of " + a + " is " +[Link]() + " and Uppercase of " +


b + " is " + [Link]() + "\n\n");

//calculate length of a string

[Link]("String length is "+[Link]());

[Link]("String length is "+[Link]()+"\n\n");

//find out location of certain letter.

[Link]("Enter Substring: ");

c=[Link]();

[Link]("Position of substring " + c + " in string " + a + " is " +[Link](c) +


"\n\n");

//match the substring

int n = [Link]();

int m = [Link]();

int index=[Link](c), i=index+1, count=(index>=0)?1:0;


while(index!=-1 && i<=(n-m))

index=[Link](i, n).indexOf(c);

count=(index>=0)?count+1:count;

i=i+index+1;

[Link]("Total Number Of Substring "+ c +" Appears: "+count+ "\n\n");

//compare two strings

temp=[Link](b);

if(temp==0)

[Link]("The Strings are Equal\n ");

else if(temp>0)

[Link]("The String "+b+" is greater than the string "+a + "\n\n");

else

[Link]("The String "+a+" is greater than the string "+b + "\n\n");

//concate any two strings.

[Link]("Entered strings after concatenation is " +[Link](b));

}
Output :
Please enter two Strings:vaishnavi nagarkar

You input: vaishnavi and nagarkar

Lowercase of vaishnavi is vaishnavi and Lowercase of nagarkar is nagarkar

Uppercase of vaishnavi is VAISHNAVI and Uppercase of nagarkar is NAGARKAR

String length is 9

String length is 8

Enter Substring: ai

Position of substring ai in string vaishnavi is 2

Total Number Of Substring ai Appears: 1

The String vaishnavi is greater than the string nagarkar

Entered strings after concatenation is vaishnavinagarkar


[Link] a program to perform array addition and matrix multiplication.

Ans:

import [Link];

public class Matrix

public static void main(String args[])

Scanner in = new Scanner([Link]);

int m, n, c, d, a, p, q, k;

[Link]("Choose the Operation You want to do on Matrix:\n [Link] \n


[Link]");

a = [Link]();

switch(a){

case 1:

[Link]("Enter the number of rows and columns of matrix");

m = [Link]();

n = [Link]();
int first[][] = new int[m][n];

int second[][] = new int[m][n];

int add[][] = new int[m][n];

[Link]("Enter the elements of first matrix");

for (c = 0; c < m; c++)

for (d = 0; d < n; d++)

first[c][d] = [Link]();

[Link]("Enter the elements of second matrix");

for (c = 0 ; c < m; c++)

for (d = 0 ; d < n; d++)

second[c][d] = [Link]();

for (c = 0; c < m; c++)

for (d = 0; d < n; d++)

add[c][d] = first[c][d] + second[c][d]; //replace '+' with '-' to subtract matrices

[Link]("Sum of the matrices:");

for (c = 0; c < m; c++)

{
for (d = 0; d < n; d++)

[Link](add[c][d] + "\t");

[Link]();

break;

case 2:

int sum = 0;

[Link]("Enter the number of rows and columns of first matrix");

m = [Link]();

n = [Link]();

int first_m[][] = new int[m][n];

[Link]("Enter elements of first matrix");

for (c = 0; c < m; c++)

for (d = 0; d < n; d++)

first_m[c][d] = [Link]();

[Link]("Enter the number of rows and columns of second matrix");

p = [Link]();
q = [Link]();

if (n != p)

[Link]("The matrices can't be multiplied with each other.");

else

int second_m[][] = new int[p][q];

int multiply[][] = new int[m][q];

[Link]("Enter elements of second matrix");

for (c = 0; c < p; c++)

for (d = 0; d < q; d++)

second_m[c][d] = [Link]();

for (c = 0; c < m; c++) {

for (d = 0; d < q; d++) {

for (k = 0; k < p; k++)

sum = sum + first_m[c][k]*second_m[k][d];

multiply[c][d] = sum;

sum = 0;

}
[Link]("Product of the matrices:");

for (c = 0; c < m; c++) {

for (d = 0; d < q; d++)

[Link](multiply[c][d]+"\t");

[Link]("\n");

break;

default :

[Link]("Invalid Operation:");

Output :
(base) ┌─[untold@parrot]─[~/Desktop/Assignment]

└──╼ $javac [Link]

(base) ┌─[untold@parrot]─[~/Desktop/Assignment]
└──╼ $java Matrix

Choose the Operation You want to do on Matrix:

[Link]

[Link]

Enter the number of rows and columns of matrix

2 2

Enter the elements of first matrix

1 0

0 1

Enter the elements of second matrix

1 2

2 1

Sum of the matrices:

2 2

2 2

Choose the Operation You want to do on Matrix:

[Link]

[Link]

Enter the number of rows and columns of first matrix

22

Enter elements of first matrix


12

45

Enter the number of rows and columns of second matrix

22

Enter elements of second matrix

13

46

Product of the matrices:

9 15

24 42

Common questions

Powered by AI

The program uses methods like `toLowerCase` and `toUpperCase` to perform case conversions on strings. It compares two strings with `compareTo`, which returns an integer: zero if equal, positive if the first string is lexicographically greater, and negative otherwise. The concatenation of strings is done using the `concat` method .

The program first checks if any integers were provided as command line arguments. If not, it exits with a message. It then converts the arguments from strings to integers and stores them in an array. The first element of this array is assumed to be the maximum number. The program then iterates through the array, comparing each element with the current maximum. If an element is larger, it becomes the new maximum. Finally, the program outputs the largest number found .

The program uses functions to calculate sums and averages. For even numbers, the sum is accumulated by iterating through half the range, multiplying each index by two. The average is calculated by dividing the total by the number of terms (n). For odd numbers, the sum is accumulated using a similar loop starting from a different base. The average is again the sum divided by n .

Input validation ensures that matrices are compatible for the chosen operation. For addition, it checks that both matrices share the same dimensions. For multiplication, it validates that the column count of the first matrix equals the row count of the second. If dimensions are unsuitable, it reports the inability to multiply matrices instead of proceeding with faulty logic .

The program begins with user input for matrix dimensions and contents. For addition, it checks that matrix sizes match, then adds corresponding elements from both matrices into a third matrix. For multiplication, it checks compatibility—columns of the first must match rows of the second—before computing each element of the product matrix by summing the products of elements fetched by iterating over row and column indices .

Integer inputs are handled by converting from strings using `Integer.parseInt`, maintaining numerical operability. The parsing of strings to integers allows operations like comparison and arithmetic. String inputs are processed and manipulated with methods like `toLowerCase`, length determination, and substring searching, demonstrating text-centric capabilities such as case conversion and index-based manipulation .

The program retrieves user input for two strings, then potentially a substring to search for within one of them. It uses an index-based iterative search to count all occurrences of the substring and finds the position of its first appearance using `indexOf`. For string comparison, it leverages the `compareTo` method, determining order based on string value .

The program initializes with a balance and listens for transaction commands. Deposits increase the balance by a specified amount, while withdrawals decrease it, provided sufficient funds exist. The balance updates dynamically after each transaction, with both successful and rejected withdrawal attempts being handled to ensure no negative balance results .

The bank database class supports three operations: viewing balance, depositing money, and withdrawing money. These are implemented using a `switch` statement. Viewing balance is straightforward and prints the current balance. Deposing money adds the entered amount to the balance, while withdrawing subtracts from it after checking if the balance suffices. The program keeps track of total deposits and withdrawals separately and updates the balance accordingly .

Before parsing, the program checks if any arguments are provided. It exits with a user prompt if none are. During parsing, runtime exceptions like `NumberFormatException` could occur, but basic validation through argument length checking and integer parsing within a controlled environment allows avoiding processing errors, assuming the input has been supplied correctly. However, additional error handling could be beneficial in more robust implementations .

You might also like