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

Prime Numbers

The document contains multiple Java programs demonstrating various string operations, including finding prime numbers, analyzing text, and performing string manipulations using both character arrays and the String class. Each program provides a user interface for input and displays the results of operations such as string concatenation, substring extraction, and character counting. The document also includes examples of using the StringBuffer class for similar string operations.

Uploaded by

gaydhsb
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)
25 views19 pages

Prime Numbers

The document contains multiple Java programs demonstrating various string operations, including finding prime numbers, analyzing text, and performing string manipulations using both character arrays and the String class. Each program provides a user interface for input and displays the results of operations such as string concatenation, substring extraction, and character counting. The document also includes examples of using the StringBuffer class for similar string operations.

Uploaded by

gaydhsb
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
You are on page 1/ 19

Prime numbers

import java.util.Scanner;

public class Prime


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

// Prompt the user to enter the upper limit


System.out.print("Enter the upper limit to find prime numbers: ");
int limit = scanner.nextInt();

System.out.println("Prime numbers up to " + limit + ":");

// Start from 2, as 1 is not a prime number


for (int number = 2; number <= limit; number++)
{
if (isPrime(number))
{
System.out.print(number + " ");
}
}
scanner.close(); // Close the scanner to avoid resource leak
}

// Method to check if a number is prime


public static boolean isPrime(int num)
{
for (int divisor = 2; divisor <= Math.sqrt(num); divisor++)
{
if (num % divisor == 0)
{
return false; // Not a prime number
}
}
return true; // Prime number
}
}
Output:

Enter the upper limit to find prime numbers: 100


Prime numbers up to 100:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Text Analyzer
import java.util.Scanner;

public class TextAnalyzer


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

System.out.println("Enter your text (press Enter twice to finish):");


StringBuilder text = new StringBuilder();
String line;

// Read input until an empty line is entered


while (true)
{
line = scanner.nextLine();
if (line.isEmpty())
{
break;
}
text.append(line).append("\n");
}

// Remove spaces and newlines to count characters


String textWithoutSpaces = text.toString().replaceAll("\\s", "");

// Count characters, words, and lines


int charCount = textWithoutSpaces.length();
int wordCount = text.toString().split("\\s+").length;
int lineCount = text.toString().split("\n").length;

// Display results
System.out.println("Number of characters (excluding spaces): " + charCount);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of lines: " + lineCount);

scanner.close();
}
}
Output:
Enter your text (press Enter twice to finish):
hi iam hari
how are you?
iam fine!!

Number of characters (excluding spaces): 28


Number of words: 8
Number of lines: 3
Write a program to do String Manipulation using Character Array and perform
the following string operations:
a) String length
b) Finding a character at a particular position
c) Concatenating two strings

import java.util.Scanner;

public class StringManipulation


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice;
do
{
System.out.println("\n--- String Manipulation Using Character Array ---");
System.out.println("1) Find String Length");
System.out.println("2) Find Character at Position");
System.out.println("3) Concatenate Two Strings");
System.out.println("4) Exit");
System.out.print("Enter your choice: ");
choice = sc.nextLine();

switch (choice)
{
case "1": // Find String Length
System.out.print("Enter the string: ");
char[] str1 = sc.nextLine().toCharArray();
System.out.println("Length: " + str1.length);
break;

case "2": // Find Character at Position


System.out.print("Enter the string: ");
char[] str2 = sc.nextLine().toCharArray();
System.out.print("Enter position (0-based): ");
int position = Integer.parseInt(sc.nextLine());
if (position >= 0 && position < str2.length)
{
System.out.println("Character: " + str2[position]);
}
else
{
System.out.println("Invalid position.");
}
break;

case "3": // Concatenate Two Strings


System.out.print("Enter first string: ");
char[] str3 = sc.nextLine().toCharArray();
System.out.print("Enter second string: ");
char[] str4 = sc.nextLine().toCharArray();
char[] result = new char[str3.length + str4.length];
System.arraycopy(str3, 0, result, 0, str3.length);
System.arraycopy(str4, 0, result, str3.length, str4.length);
System.out.println("Concatenated: " + new String(result));
break;

case "4": // Exit


System.out.println("Exiting...");
break;

default:
System.out.println("Invalid choice. Try again.");
}
} while (!choice.equals("4"));
sc.close();
}
}
Output:

--- String Manipulation Using Character Array ---


1) Find String Length
2) Find Character at Position
3) Concatenate Two Strings
4) Exit
Enter your choice: 1
Enter the string: Artificial intelligence
Length: 23

--- String Manipulation Using Character Array ---


1) Find String Length
2) Find Character at Position
3) Concatenate Two Strings
4) Exit
Enter your choice: 2
Enter the string: Data Science
Enter position (0-based): 8
Character: e

--- String Manipulation Using Character Array ---


1) Find String Length
2) Find Character at Position
3) Concatenate Two Strings
4) Exit
Enter your choice: 3
Enter first string: Computer
Enter second string: Science
Concatenated: ComputerScience

--- String Manipulation Using Character Array ---


1) Find String Length
2) Find Character at Position
3) Concatenate Two Strings
4) Exit
Enter your choice: 4
Exiting...
Write a program to perform the following string operations using String class:
a) String Concatenation
b) Search a substring
c) To extract substring from given string
d) Length of a string
e) Reverse a string
f) Delete a substring from the given string

import java.util.Scanner;

public class StringClass {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String choice;
do {
System.out.println("\n--- Unified String Operations ---");
System.out.println("1) String Concatenation");
System.out.println("2) Search a Substring");
System.out.println("3) Extract Substring");
System.out.println("4) Length of a String");
System.out.println("5) Reverse a String");
System.out.println("6) Delete a Substring");
System.out.println("7) Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextLine();

switch (choice) {
case "1": // String Concatenation
System.out.print("Enter first string: ");
String str1 = scanner.nextLine();
System.out.print("Enter second string: ");
String str2 = scanner.nextLine();
String concatenated = str1.concat(str2);
System.out.println("Concatenated String: " + concatenated);
break;

case "2": // Search a Substring


System.out.print("Enter the main string: ");
String mainStr = scanner.nextLine();
System.out.print("Enter the substring to search: ");
String subStr = scanner.nextLine();
if (mainStr.contains(subStr)) {
System.out.println("Substring found at index: " + mainStr.indexOf(subStr));
} else {
System.out.println("Substring not found.");
}
break;

case "3": // Extract Substring


System.out.print("Enter the main string: ");
String extractStr = scanner.nextLine();
System.out.print("Enter start index: ");
int startIndex = scanner.nextInt();
System.out.print("Enter end index: ");
int endIndex = scanner.nextInt();
scanner.nextLine(); // Consume newline
if (startIndex >= 0 && endIndex <= extractStr.length() && startIndex <
endIndex) {
String extracted = extractStr.substring(startIndex, endIndex);
System.out.println("Extracted Substring: " + extracted);
} else {
System.out.println("Invalid indices.");
}
break;

case "4": // Length of a String


System.out.print("Enter the string: ");
String strLength = scanner.nextLine();
System.out.println("Length of the string: " + strLength.length());
break;

case "5": // Reverse a String (Using Only String Class)


System.out.print("Enter the string: ");
String strReverse = scanner.nextLine();
String reversed = reverseStringUsingStringClass(strReverse);
System.out.println("Reversed String: " + reversed);
break;

case "6": // Delete a Substring (Using Only String Class)


System.out.print("Enter the string: ");
String strDelete = scanner.nextLine();
System.out.print("Enter start index: ");
int deleteStart = scanner.nextInt();
System.out.print("Enter end index: ");
int deleteEnd = scanner.nextInt();
scanner.nextLine(); // Consume newline
if (deleteStart >= 0 && deleteEnd <= strDelete.length() && deleteStart <
deleteEnd) {
String deleted = deleteSubstringUsingStringClass(strDelete, deleteStart,
deleteEnd);
System.out.println("String after deletion: " + deleted);
} else {
System.out.println("Invalid indices.");
}
break;

case "7": // Exit


System.out.println("Exiting...");
break;

default:
System.out.println("Invalid choice. Please try again.");
}
} while (!choice.equals("7"));
scanner.close();
}

// Helper method to reverse a string using only the String class


private static String reverseStringUsingStringClass(String str) {
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i); // Append characters in reverse order
}
return reversed;
}

// Helper method to delete a substring using only the String class


private static String deleteSubstringUsingStringClass(String str, int start, int end) {
String before = str.substring(0, start); // Part before the deletion range
String after = str.substring(end); // Part after the deletion range
return before + after; // Concatenate the two parts
}
}
Output:

--- Unified String Operations ---


1) String Concatenation
2) Search a Substring
3) Extract Substring
4) Length of a String
5) Reverse a String
6) Delete a Substring
7) Exit
Enter your choice: 1
Enter first string: hello
Enter second string: World
Concatenated String: helloWorld

--- Unified String Operations ---


1) String Concatenation
2) Search a Substring
3) Extract Substring
4) Length of a String
5) Reverse a String
6) Delete a Substring
7) Exit
Enter your choice: 2
Enter the main string: hello
Enter the substring to search: l
Substring found at index: 2

--- Unified String Operations ---


1) String Concatenation
2) Search a Substring
3) Extract Substring
4) Length of a String
5) Reverse a String
6) Delete a Substring
7) Exit
Enter your choice: 3
Enter the main string: hello
Enter start index: 0
Enter end index: 4
Extracted Substring: hell

--- Unified String Operations ---


1) String Concatenation
2) Search a Substring
3) Extract Substring
4) Length of a String
5) Reverse a String
6) Delete a Substring
7) Exit
Enter your choice: 4
Enter the string: computerscience
Length of the string: 15

--- Unified String Operations ---


1) String Concatenation
2) Search a Substring
3) Extract Substring
4) Length of a String
5) Reverse a String
6) Delete a Substring
7) Exit
Enter your choice: 5
Enter the string: intelligence
Reversed String: ecnegilletni

--- Unified String Operations ---


1) String Concatenation
2) Search a Substring
3) Extract Substring
4) Length of a String
5) Reverse a String
6) Delete a Substring
7) Exit
Enter your choice: 6
Enter the string: Artificialintelligence
Enter start index: 0
Enter end index: 10
String after deletion: intelligence

--- Unified String Operations ---


1) String Concatenation
2) Search a Substring
3) Extract Substring
4) Length of a String
5) Reverse a String
6) Delete a Substring
7) Exit
Enter your choice: 7
Exiting...
Using StringBuffer Class
import java.util.Scanner;

public class StringBufferClass


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice;
do
{
System.out.println("\n--- Unified StringBuffer Operations ---");
System.out.println("1) String Concatenation");
System.out.println("2) Search a Substring");
System.out.println("3) Extract Substring");
System.out.println("4) Length of a String");
System.out.println("5) Reverse a String");
System.out.println("6) Delete a Substring");
System.out.println("7) Exit");
System.out.print("Enter your choice: ");
choice = sc.nextLine();

switch (choice)
{
case "1": // String Concatenation
System.out.print("Enter first string: ");
String str1 = sc.nextLine();
System.out.print("Enter second string: ");
String str2 = sc.nextLine();
StringBuffer sbConcat = new StringBuffer(str1);
sbConcat.append(str2); // Append second string
System.out.println("Concatenated String: " + sbConcat.toString());
break;

case "2": // Search a Substring


System.out.print("Enter the main string: ");
String mainStr = sc.nextLine();
System.out.print("Enter the substring to search: ");
String subStr = sc.nextLine();
StringBuffer sbSearch = new StringBuffer(mainStr);
int index = sbSearch.indexOf(subStr); // Find index of substring
if (index != -1)
{
System.out.println("Substring found at index: " + index);
}
else
{
System.out.println("Substring not found.");
}
break;

case "3": // Extract Substring


System.out.print("Enter the main string: ");
String extractStr = sc.nextLine();
System.out.print("Enter start index: ");
int startIndex = sc.nextInt();
System.out.print("Enter end index: ");
int endIndex = sc.nextInt();
sc.nextLine(); // Consume newline
StringBuffer sbExtract = new StringBuffer(extractStr);
if (startIndex >= 0 && endIndex <= sbExtract.length() && startIndex <
endIndex)
{
String extracted = sbExtract.substring(startIndex, endIndex); // Extract
substring
System.out.println("Extracted Substring: " + extracted);
}
else {
System.out.println("Invalid indices.");
}
break;

case "4": // Length of a String


System.out.print("Enter the string: ");
String strLength = sc.nextLine();
StringBuffer sbLength = new StringBuffer(strLength);
System.out.println("Length of the string: " + sbLength.length()); // Get length
break;

case "5": // Reverse a String


System.out.print("Enter the string: ");
String strReverse = sc.nextLine();
StringBuffer sbReverse = new StringBuffer(strReverse);
sbReverse.reverse(); // Reverse the string
System.out.println("Reversed String: " + sbReverse.toString());
break;

case "6": // Delete a Substring


System.out.print("Enter the string: ");
String strDelete = sc.nextLine();
System.out.print("Enter start index: ");
int deleteStart = sc.nextInt();
System.out.print("Enter end index: ");
int deleteEnd = sc.nextInt();
sc.nextLine(); // Consume newline
StringBuffer sbDelete = new StringBuffer(strDelete);
if (deleteStart >= 0 && deleteEnd <= sbDelete.length() && deleteStart <
deleteEnd)
{
sbDelete.delete(deleteStart, deleteEnd); // Delete substring
System.out.println("String after deletion: " + sbDelete.toString());
}
else
{
System.out.println("Invalid indices.");
}
break;

case "7": // Exit


System.out.println("Exiting...");
break;

default:
System.out.println("Invalid choice. Please try again.");
}
} while (!choice.equals("7"));
sc.close();
}
}

Matrix Multiplication
import java.util.Scanner;

public class MatrixMultiplication


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

// Input dimensions of the first matrix


System.out.println("Enter the number of rows for the first matrix:");
int rows1 = scanner.nextInt();
System.out.println("Enter the number of columns for the first matrix:");
int cols1 = scanner.nextInt();

// Input dimensions of the second matrix


System.out.println("Enter the number of rows for the second matrix:");
int rows2 = scanner.nextInt();
System.out.println("Enter the number of columns for the second matrix:");
int cols2 = scanner.nextInt();

// Check if multiplication is possible


if (cols1 != rows2)
{
System.out.println("Matrix multiplication is not possible. The number of columns in
the first matrix must equal the number of rows in the second matrix.");
return;
}

// Initialize matrices
int[][] matrix1 = new int[rows1][cols1];
int[][] matrix2 = new int[rows2][cols2];

// Input elements of the first matrix


System.out.println("Enter the elements of the first matrix row by row:");
for (int i = 0; i < rows1; i++)
{
System.out.println("Enter " + cols1 + " elements for row " + (i + 1) + ":");
for (int j = 0; j < cols1; j++)
{
matrix1[i][j] = scanner.nextInt();
}
}

// Input elements of the second matrix


System.out.println("Enter the elements of the second matrix row by row:");
for (int i = 0; i < rows2; i++)
{
System.out.println("Enter " + cols2 + " elements for row " + (i + 1) + ":");
for (int j = 0; j < cols2; j++)
{
matrix2[i][j] = scanner.nextInt();
}
}

// Perform matrix multiplication


int[][] result = new int[rows1][cols2]; // Resultant matrix will have dimensions rows1 x
cols2

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


{
for (int j = 0; j < cols2; j++)
{
result[i][j] = 0; // Initialize the result cell to 0
for (int k = 0; k < cols1; k++)
{ // cols1 == rows2
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// Display the resultant matrix


System.out.println("Resultant Matrix after Multiplication:");
for (int i = 0; i < rows1; i++)
{
for (int j = 0; j < cols2; j++)
{
System.out.print(result[i][j] + " ");
}
System.out.println();
}

scanner.close();
}
}

Output:

Enter the number of rows for the first matrix:


3
Enter the number of columns for the first matrix:
2
Enter the number of rows for the second matrix:
2
Enter the number of columns for the second matrix:
3

Enter the elements of the first matrix row by row:


Enter 2 elements for row 1:
22
Enter 2 elements for row 2:
22
Enter 2 elements for row 3:
22
Enter the elements of the second matrix row by row:
Enter 3 elements for row 1:
222
Enter 3 elements for row 2:
222

Resultant Matrix after Multiplication:


888
888
888

You might also like