[Go to site: main page, start]

0% found this document useful (0 votes)
27 views10 pages

Java Programs for User Input Operations

Java

Uploaded by

mahalakshmis
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)
27 views10 pages

Java Programs for User Input Operations

Java

Uploaded by

mahalakshmis
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

1.

Write a Java program that prompts the user for an integer and prints all the prime numbers
upto that integer

import [Link];

public class PrimeNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter an integer: ");
int n = [Link]();
[Link]();

[Link]("Prime numbers up to " + n + ":");


for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
[Link](i + " ");
}
}
}

public static boolean isPrime(int num) {


if (num <= 1) {
return false;
}
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
2. Write a java program to multiply given 2 matrices.
import [Link];

public class MatrixMultiplication {


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

// Input dimensions of the first matrix


[Link]("Enter the number of rows of the first matrix: ");
int rows1 = [Link]();
[Link]("Enter the number of columns of the first matrix: ");
int cols1 = [Link]();

// Input dimensions of the second matrix


[Link]("Enter the number of rows of the second matrix: ");
int rows2 = [Link]();
[Link]("Enter the number of columns of the second matrix: ");
int cols2 = [Link]();

// Check if multiplication is possible


if (cols1 != rows2) {
[Link]("Matrix multiplication is not possible with these dimensions.");
[Link]();
return;
}

// Input the first matrix


int[][] matrix1 = new int[rows1][cols1];
[Link]("Enter the elements of the first matrix:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
matrix1[i][j] = [Link]();
}
}

// Input the second matrix


int[][] matrix2 = new int[rows2][cols2];
[Link]("Enter the elements of the second matrix:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
matrix2[i][j] = [Link]();
}
}

[Link]();

// Multiply the matrices


int[][] result = new int[rows1][cols2];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// Output the result


[Link]("Resultant matrix:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
[Link](result[i][j] + " ");
}
[Link]();
}
}
}
3. Write a java program that displays number of characters, lines and words in a text
import [Link];

public class TextStatistics {


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

[Link]("Enter the text (type 'END' on a new line to finish):");


StringBuilder text = new StringBuilder();
String line;

while (!(line = [Link]()).equals("END")) {


[Link](line).append("\n");
}

[Link]();

String inputText = [Link]();


int numberOfCharacters = [Link]();
int numberOfLines = [Link]("\r\n|\r|\n").length;
int numberOfWords = [Link]("\\s+").length;

[Link]("Number of characters: " + numberOfCharacters);


[Link]("Number of lines: " + numberOfLines);
[Link]("Number of words: " + numberOfWords);
}
}

4. Generate random numbers between two given limits using Random class and print messages
according to the range of value generated
import [Link];
import [Link];

public class RandomNumberGenerator {


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

// Prompt the user to enter the lower and upper limits


[Link]("Enter the lower limit: ");
int lowerLimit = [Link]();

[Link]("Enter the upper limit: ");


int upperLimit = [Link]();

[Link]();
// Generate a random number between lowerLimit (inclusive) and upperLimit (inclusive)
Random random = new Random();
int randomNumber = [Link](upperLimit - lowerLimit + 1) + lowerLimit;

// Print the generated random number


[Link]("Generated Random Number: " + randomNumber);

// Print messages according to the range of the generated value


if (randomNumber < lowerLimit + (upperLimit - lowerLimit) / 3) {
[Link]("The number is in the lower third of the range.");
} else if (randomNumber < lowerLimit + 2 * (upperLimit - lowerLimit) / 3) {
[Link]("The number is in the middle third of the range.");
} else {
[Link]("The number is in the upper third of the range.");
}
}
}

5. Write a program to do String manipulation using character array and perform the following
operations i) string length ii) Finding a character at a particular position iii) concatenating two
strings
import [Link];

public class StringManipulation {


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

// Input first string


[Link]("Enter the first string: ");
String str1 = [Link]();
char[] charArray1 = [Link]();

// Input second string


[Link]("Enter the second string: ");
String str2 = [Link]();
char[] charArray2 = [Link]();

// i) Finding string length


int length1 = stringLength(charArray1);
int length2 = stringLength(charArray2);
[Link]("Length of the first string: " + length1);
[Link]("Length of the second string: " + length2);

// ii) Finding a character at a particular position


[Link]("Enter the position to find the character in the first string: ");
int position = [Link]();
if (position >= 0 && position < length1) {
char character = charAtPosition(charArray1, position);
[Link]("Character at position " + position + " in the first string: " +
character);
} else {
[Link]("Position out of bounds.");
}

// iii) Concatenating two strings


char[] concatenatedArray = concatenateStrings(charArray1, charArray2);
String concatenatedString = new String(concatenatedArray);
[Link]("Concatenated string: " + concatenatedString);

[Link]();
}

// Method to find the length of a character array


public static int stringLength(char[] charArray) {
int length = 0;
for (char c : charArray) {
length++;
}
return length;
}

// Method to find the character at a particular position


public static char charAtPosition(char[] charArray, int position) {
return charArray[position];
}

// Method to concatenate two character arrays


public static char[] concatenateStrings(char[] charArray1, char[] charArray2) {
int length1 = [Link];
int length2 = [Link];
char[] result = new char[length1 + length2];

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


result[i] = charArray1[i];
}
for (int i = 0; i < length2; i++) {
result[length1 + i] = charArray2[i];
}

return result;
}
}
6. Write a program to perform the following operations using string class. i)String
concatenation ii) Search a substring iii)To extract a substring from given string
import [Link];

public class StringOperations {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

// Input first string

[Link]("Enter the first string: ");

String str1 = [Link]();

// Input second string

[Link]("Enter the second string: ");

String str2 = [Link]();

// i) String concatenation

String concatenatedString = str1 + str2;

[Link]("Concatenated string: " + concatenatedString);

// ii) Search a substring

[Link]("Enter the substring to search in the first string: ");

String substring = [Link]();

if ([Link](substring)) {

[Link]("The substring \"" + substring + "\" is found in the first string.");

} else {

[Link]("The substring \"" + substring + "\" is not found in the first string.");

// iii) To extract a substring from a given string

[Link]("Enter the starting index for substring extraction: ");

int startIndex = [Link]();

[Link]("Enter the ending index for substring extraction: ");


int endIndex = [Link]();

if (startIndex >= 0 && endIndex <= [Link]() && startIndex < endIndex) {

String extractedSubstring = [Link](startIndex, endIndex);

[Link]("Extracted substring: " + extractedSubstring);

} else {

[Link]("Invalid indices for substring extraction.");

[Link]();

7. Write a program to perform the following string operations using StringBuffer Class i)Length
of string ii) Reverse a string iii)Delete the substring from the given string
import [Link];

public class StringBufferOperations {


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

// Input string
[Link]("Enter a string: ");
String inputString = [Link]();
StringBuffer stringBuffer = new StringBuffer(inputString);

// i) Length of string
int length = [Link]();
[Link]("Length of the string: " + length);

// ii) Reverse a string


[Link]();
[Link]("Reversed string: " + [Link]());

// Restore the original string by reversing it again


[Link]();

// iii) Delete a substring from the given string


[Link]("Enter the start index for deletion: ");
int startIndex = [Link]();
[Link]("Enter the end index for deletion: ");
int endIndex = [Link]();
if (startIndex >= 0 && endIndex <= [Link]() && startIndex < endIndex) {
[Link](startIndex, endIndex);
[Link]("String after deletion: " + [Link]());
} else {
[Link]("Invalid indices for deletion.");
}

[Link]();
}
}

8. Write a program that implements multi thread application that has three threads. First
thread generates random integer every 1 second and if the value is even second thread
computes the square of the number and prints. If the value is odd third thread computes the
cube of the number and prints.
import [Link];

class NumberGenerator extends Thread {


private int number;
private final Object lock;

public NumberGenerator(Object lock) {


[Link] = lock;
}

public void run() {


Random random = new Random();
while (true) {
number = [Link](100); // Generate random number between 0 and 99
synchronized (lock) {
[Link]();
}
try {
[Link](1000); // Sleep for 1 second
} catch (InterruptedException e) {
[Link]();
}
}
}

public int getNumber() {


return number;
}
}

class EvenNumberProcessor extends Thread {


private final NumberGenerator generator;
private final Object lock;

public EvenNumberProcessor(NumberGenerator generator, Object lock) {


[Link] = generator;
[Link] = lock;
}

public void run() {


while (true) {
synchronized (lock) {
try {
[Link]();
int number = [Link]();
if (number % 2 == 0) {
[Link]("Square of " + number + " is " + (number * number));
}
} catch (InterruptedException e) {
[Link]();
}
}
}
}
}

class OddNumberProcessor extends Thread {


private final NumberGenerator generator;
private final Object lock;

public OddNumberProcessor(NumberGenerator generator, Object lock) {


[Link] = generator;
[Link] = lock;
}

public void run() {


while (true) {
synchronized (lock) {
try {
[Link]();
int number = [Link]();
if (number % 2 != 0) {
[Link]("Cube of " + number + " is " + (number * number *
number));
}
} catch (InterruptedException e) {
[Link]();
}
}
}
}
}

public class MultiThreadApplication {


public static void main(String[] args) {
Object lock = new Object();
NumberGenerator generator = new NumberGenerator(lock);
EvenNumberProcessor evenProcessor = new EvenNumberProcessor(generator, lock);
OddNumberProcessor oddProcessor = new OddNumberProcessor(generator, lock);

[Link]();
[Link]();
[Link]();
}
}

9.

Common questions

Powered by AI

StringBuilder is used to efficiently accumulate input text line by line. As lines are appended, StringBuilder handles dynamic memory allocation. Once input is complete, the entire text is converted into a single string. This final string enables the program to perform global operations to calculate the character count, determine the number of lines using newline delimiters, and split the text into words based on whitespace, thus deriving the necessary statistics .

Matrix multiplication requires specific dimensional compatibility, meaning the number of columns in the first matrix must equal the number of rows in the second. The program validates this condition prior to proceeding with multiplication. It reads dimensions, checks compatibility, and allocates a result array of appropriate size (rows of the first matrix by columns of the second matrix). If the condition is not met, it gracefully exits, ensuring logical consistency and avoiding computational errors .

Matrix multiplication requires the number of columns in the first matrix to equal the number of rows in the second matrix. If 'cols1 != rows2', the multiplication is undefined because each element of the resultant matrix is a sum of products of corresponding elements from rows of the first and columns of the second matrix. Thus, a check ensures the mathematical validity of the operation before performing it .

The Java program uses a shared lock object for synchronization to coordinate the three threads, ensuring that only one thread accesses the critical section at a time. Upon generating a number, the generator thread notifies all waiting threads, allowing them to act on even or odd numbers appropriately without conflicts. This design leverages simultaneous access control mechanisms to prevent race conditions and ensure thread-safe operations where data consistency is crucial .

Using 'Math.sqrt(num)' in determining if a number is prime is crucial because it reduces the number of iterations needed. By checking divisibility only up to the square root of a number instead of all numbers less than it, the algorithm efficiently eliminates unnecessary checks. If a number n is divisible by a number greater than its square root, it must also be divisible by a number smaller than its square root. This optimization significantly speeds up the prime-checking process .

The program calculates the thresholds for the thirds of the range by dividing the difference between the upper and lower limits into three equal parts. It then checks the position of the random number relative to these thresholds: numbers less than the first third threshold are in the lower third, numbers less than the second threshold are in the middle third, and the rest are in the upper third of the range .

Checking 'startIndex < endIndex' when extracting a substring ensures that the starting point is before the endpoint in the string. This condition guarantees a valid sequence of characters and prevents errors such as negative lengths or reversed parts, which would throw runtime exceptions or yield incorrect results. Such checks contribute to robust error handling in string manipulations .

The program uses 'StringBuffer's 'delete' method, which removes characters from the start index up to, but not including, the end index. The method checks that both indices are within bounds, meaning the start index is non-negative and the end index does not exceed the string length. These validations prevent index out-of-bounds exceptions and ensure correct application of the deletion operation .

The application employs three threads: one to generate numbers, another to process even numbers, and a third to process odd numbers. The generator thread produces random integers, and each time a number is generated, it notifies the other threads via a shared lock. The even number processor calculates and prints the square if the number is even, while the odd processor calculates and prints the cube if the number is odd. This design exemplifies cooperative multi-threading, where threads synchronize on a shared object to distribute work based on number parity .

Using a 'char' array allows low-level manipulation of individual characters, which can be efficient for operations like finding a specific character or calculating length manually. In contrast, the 'String' class provides more abstraction and a wider variety of built-in methods for operations like finding substrings and concatenation, enhancing code readability and reducing errors. While 'char' arrays offer fine control and potentially better performance in certain scenarios, 'String' provides more functionality and ease of use .

You might also like