0% found this document useful (0 votes)
1 views

JAVA ASSIGNMENT

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

JAVA ASSIGNMENT

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Name-Aryan

Roll no-2200290530024

Sec- A

JAVA ASSIGNMENT-02

1). WAP to create a method that reads a file and throws an exception if
the file
import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class FileReadingExample {

public static void readFile(String filePath) throws Exception {

BufferedReader reader = null;

try {

reader = new BufferedReader(new FileReader(filePath));

String line;

System.out.println("File content:");

while ((line = reader.readLine()) != null) {

System.out.println(line);

} catch (IOException e) {

throw new Exception("An error occurred while reading the file: " + e.getMessage());

} finally {

if (reader != null) {

try {

reader.close();

} catch (IOException e) {

throw new Exception("An error occurred while closing the file: " + e.getMessage());
Name-Aryan

Roll no-2200290530024

Sec- A

public static void main(String[] args) {

String filePath = "example.txt";

try {

readFile(filePath);

} catch (Exception e) {

System.err.println(e.getMessage());

2).WAP to Check Array Bounds while Inputting Elements into an Array.

import java.util.Scanner;

public class ArrayBoundsCheck {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the size of the array: ");

int size = scanner.nextInt();

int[] array = new int[size];

System.out.println("Enter " + size + " elements:");


Name-Aryan

Roll no-2200290530024

Sec- A

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

System.out.print("Element " + (i + 1) + ": ");

if (scanner.hasNextInt()) {

array[i] = scanner.nextInt();

} else {

System.out.println("Invalid input. Please enter an integer.");

scanner.next(); // Clear the invalid input

i--; // Decrement i to retry the current index

System.out.println("Array elements:");

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

System.out.println("Element " + (i + 1) + ": " + array[i]);

scanner.close();

You might also like