Sheet7
Sheet7
1
import java.util.InputMismatchException;
import java.util.Scanner;
12.2
import java.util.Random;
import java.util.Scanner;
12.5
@Override
public String toString() {
return "Triangle with sides: " + side1 + ", " + side2 + ", " + side3;
}
}
import java.util.Scanner;
} 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);
}
12.9
public class BinaryFormatException extends Exception {
public BinaryFormatException(String message) {
super(message);
}
}
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
charCount += line.length();
12.14
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
int sum = 0;
int count = 0;
writeRandomNumbersToFile(filename);
try {
URL url = new URL(urlString);
Scanner input = new Scanner(url.openStream());
int wordCount = 0;
while (input.hasNext()) {
input.next();
wordCount++;
}
input.close();
} catch (IOException e) {
System.out.println("Error reading from URL: " + e.getMessage());
}
}
}
Mini project
import java.io.*;
import java.util.Scanner;
loadNamesData(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 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];