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

Sheet7

The document contains various Java programs demonstrating exception handling, file operations, and data processing. Key examples include handling input mismatches, calculating sums, managing triangle properties with custom exceptions, and reading/writing data to files. Additionally, it features a mini project for ranking baby names based on user input and data files.

Uploaded by

mohvvmedssr002
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)
6 views14 pages

Sheet7

The document contains various Java programs demonstrating exception handling, file operations, and data processing. Key examples include handling input mismatches, calculating sums, managing triangle properties with custom exceptions, and reading/writing data to files. Additionally, it features a mini project for ranking baby names based on user input and data files.

Uploaded by

mohvvmedssr002
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/ 14

12.

1
import java.util.InputMismatchException;
import java.util.Scanner;

public class InputMismatchExample {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0, num2 = 0;
boolean validInput = false;

// Loop until the user provides two valid integers


while (!validInput) {
try {
System.out.print("Enter the first integer: ");
num1 = input.nextInt();

System.out.print("Enter the second integer: ");


num2 = input.nextInt();

validInput = true; // Exit loop if inputs are valid


} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter integers only.");
input.nextLine(); // Clear the invalid input
}
}

int sum = num1 + num2;


System.out.println("The sum is: " + sum);
}
}

12.2
import java.util.Random;
import java.util.Scanner;

public class ArrayIndexOutOfBoundsExample {


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

int[] numbers = new int[100];


for (int i = 0; i < numbers.length; i++) {
numbers[i] = random.nextInt
}
System.out.println("Array created with 100 random numbers.");

System.out.print("Enter an index (0 to 99): ");


try {
int index = input.nextInt();

System.out.println("The element at index " + index + " is: " + numbers[index]);


} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Out of Bounds");
} catch (Exception e) {
System.out.println("Invalid input. Please enter a valid index.");
}
}
}

12.5

public class IllegalTriangleException extends Exception {


public IllegalTriangleException(String message) {
super(message);
}
}

public class Triangle {


private double side1;
private double side2;
private double side3;

/** Construct a triangle with the specified sides */


public Triangle(double side1, double side2, double side3) throws
IllegalTriangleException {
if (side1 + side2 <= side3 || side1 + side3 <= side2 || side2 + side3 <= side1) {
throw new IllegalTriangleException("The sum of any two sides must be greater
than the third side.");
}
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

// Getters for the sides


public double getSide1() {
return side1;
}

public double getSide2() {


return side2;
}

public double getSide3() {


return side3;
}

@Override
public String toString() {
return "Triangle with sides: " + side1 + ", " + side2 + ", " + side3;
}
}
import java.util.Scanner;

public class TestTriangle {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.print("Enter side1: ");
double side1 = input.nextDouble();

System.out.print("Enter side2: ");


double side2 = input.nextDouble();

System.out.print("Enter side3: ");


double side3 = input.nextDouble();

Triangle triangle = new Triangle(side1, side2, side3);


System.out.println(triangle);

} catch (IllegalTriangleException e) {
System.out.println("Invalid Triangle: " + e.getMessage());
} catch (Exception e) {
System.out.println("Invalid input. Please enter valid numbers.");
}
}
}

12.8
public class HexFormatException extends Exception {
public HexFormatException(String message) {
super(message);
}
}
public class HexToDecimalConverter {
public static int hex2Dec(String hex) throws HexFormatException {
for (int i = 0; i < hex.length(); i++) {
char ch = hex.charAt(i);
if (!((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'))) {
throw new HexFormatException("Invalid hex string: " + hex);
}
}
return Integer.parseInt(hex, 16);
}

public static void main(String[] args) {


try {
String hexString = "1A3F";
int decimalValue = hex2Dec(hexString);
System.out.println("The decimal value of " + hexString + " is " + decimalValue);

String invalidHex = "1G3F";


System.out.println("The decimal value of " + invalidHex + " is " +
hex2Dec(invalidHex));
} catch (HexFormatException e) {
System.out.println(e.getMessage());
}
}
}

12.9
public class BinaryFormatException extends Exception {
public BinaryFormatException(String message) {
super(message);
}
}

public class BinaryToDecimalConverter {


public static int bin2Dec(String binary) throws BinaryFormatException {
for (int i = 0; i < binary.length(); i++) {
char ch = binary.charAt(i);
if (ch != '0' && ch != '1') {
throw new BinaryFormatException("Invalid binary string: " + binary);
}
}
return Integer.parseInt(binary, 2);
}

public static void main(String[] args) {


try {
String binaryString = "1011";
int decimalValue = bin2Dec(binaryString);
System.out.println("The decimal value of " + binaryString + " is " + decimalValue);

String invalidBinary = "1021";


System.out.println("The decimal value of " + invalidBinary + " is " +
bin2Dec(invalidBinary));
} catch (BinaryFormatException e) {
System.out.println(e.getMessage());
}
}
}
12.13
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileCharacterWordLineCounter {


public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java FileCharacterWordLineCounter filename");
System.exit(1);
}

String filename = args[0];


File file = new File(filename);

int charCount = 0;
int wordCount = 0;
int lineCount = 0;

try (Scanner input = new Scanner(file)) {


while (input.hasNextLine()) {
String line = input.nextLine();
lineCount++;

charCount += line.length();

String[] words = line.split("\\s+");


wordCount += words.length;
}

System.out.println("Number of characters: " + charCount);


System.out.println("Number of words: " + wordCount);
System.out.println("Number of lines: " + lineCount);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + filename);
}
}
}

12.14
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ProcessScoresFromFile {


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

System.out.print("Enter the file name: ");


String filename = consoleInput.nextLine();

File file = new File(filename);

int sum = 0;
int count = 0;

try (Scanner fileInput = new Scanner(file)) {


while (fileInput.hasNext()) {
if (fileInput.hasNextInt()) {
sum += fileInput.nextInt();
count++;
} else {
fileInput.next();
}
}

double average = (count == 0) ? 0 : (double) sum / count;

System.out.println("Total: " + sum);


System.out.println("Average: " + average);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + filename);
}
}
}
12.15
import java.io.*;
import java.util.*;

public class WriteReadData {


public static void main(String[] args) {
String filename = "Exercise12_15.txt";

writeRandomNumbersToFile(filename);

List<Integer> numbers = readNumbersFromFile(filename);


Collections.sort(numbers);

System.out.println("Numbers in increasing order:");


for (int number : numbers) {
System.out.print(number + " ");
}
}

public static void writeRandomNumbersToFile(String filename) {


try (PrintWriter output = new PrintWriter(new File(filename))) {
Random rand = new Random();
for (int i = 0; i < 100; i++) {
int randomNum = rand.nextInt
output.print(randomNum + " ");
}
System.out.println("Random numbers have been written to the file: " + filename);
} catch (IOException e) {
System.out.println("Error writing to the file: " + e.getMessage());
}
}

public static List<Integer> readNumbersFromFile(String filename) {


List<Integer> numbers = new ArrayList<>();
try (Scanner input = new Scanner(new File(filename))) {
while (input.hasNextInt()) {
numbers.add(input.nextInt());
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + filename);
}
return numbers;
}
}
12.19
import java.io.*;
import java.net.URL;
import java.util.Scanner;

public class CountWordsInGettysburg {


public static void main(String[] args) {
String urlString = "https://liveexample.pearsoncmg.com/data/Lincoln.txt";

try {
URL url = new URL(urlString);
Scanner input = new Scanner(url.openStream());

int wordCount = 0;

while (input.hasNext()) {
input.next();
wordCount++;
}

input.close();

System.out.println("Number of words in Lincoln's Gettysburg Address: " +


wordCount);

} catch (IOException e) {
System.out.println("Error reading from URL: " + e.getMessage());
}
}
}

Mini project
import java.io.*;
import java.util.Scanner;

public class BabyNameRanking {

public static void main(String[] args) {


String[][] boyNames = new String[10][1000];
String[][] girlNames = new String[10][1000];

loadNamesData(boyNames, girlNames);

Scanner input = new Scanner(System.in);


System.out.print("Enter the year (2001-2010): ");
int year = input.nextInt();
if (year < 2001 || year > 2010) {
System.out.println("Year must be between 2001 and 2010.");
return;
}

System.out.print("Enter the gender (M/F): ");


String gender = input.next().toUpperCase();
if (!gender.equals("M") && !gender.equals("F")) {
System.out.println("Invalid gender. Please enter M or F.");
return;
}
System.out.print("Enter the name: ");
String name = input.next();

int rank = getRanking(year, gender, name, boyNames, girlNames);

if (rank != -1) {
System.out.println(name + " is ranked #" + rank + " in year " + year);
} else {
System.out.println("The name " + name + " is not ranked in year " + year);
}
}

public static void loadNamesData(String[][] boyNames, String[][] girlNames) {


for (int year = 2001; year <= 2010; year++) {
String fileName = "babynameranking" + year + ".txt";
File file = new File(fileName);

try (Scanner input = new Scanner(file)) {


int index = 0;
while (input.hasNext() && index < 1000) {
int rank = input.nextInt();
String boyName = input.next();
input.next();
String girlName = input.next();
input.next();

boyNames[year - 2001][index] = boyName;


girlNames[year - 2001][index] = girlName;
index++;
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + fileName);
}
}
}

public static int getRanking(int year, String gender, String name, String[][] boyNames,
String[][] girlNames) {
int yearIndex = year - 2001;
String[] namesArray = gender.equals("M") ? boyNames[yearIndex] :
girlNames[yearIndex];

for (int i = 0; i < namesArray.length; i++) {


if (namesArray[i] != null && namesArray[i].equalsIgnoreCase(name)) {
return i + 1;
}
}
return -1;
}
}

You might also like