Throw exceptions in Java - java

I'm working on a mortgage calculator in Java. I have to validate the data using try and catch blocks. I have done the rest of the program, but I can't figure out how to implement the try and catch blocks. Here's what the prompt is asking for:
"Write your own exceptions to validate your data by using try and catch blocks. For example loan amount cannot be a negative number and it should be between $5000 and $1,000,000."
Edit: Here's the try-catch block that finally worked. It needed to be placed in the actionPerformed method where the rest of my data is. I had another issue where the code kept throwing an exception for any amount that I entered until I figured out that I needed to place the for loop inside of the try block.
try
{
if((n1 < 5000) || (n1 > 1000000))
throw new Exception();
for (int i = 0; i < term[0] * 12; i++)
{
double interest_paid = n1 * (rate[0] / 12);
double principal_paid = tr1 - interest_paid;
n1 = n1 - principal_paid;
//Prints the results.
edit.append("\n " + (i+1) + " \t\t " + (two.format(interest_paid))
+ " \t\t " + (two.format(principal_paid)) + " \t\t "
+ (two.format(Math.abs(n1))));
}
}
catch (Exception e)
{
edit.setText("Please enter an amount between $5,000 and $1,000,000.");
mortText.setText("");
out.setText("");
}

Here's the try-catch block that finally worked. It needed to be placed in the actionPerformed method where the rest of my data is. I had another issue where the code kept throwing an exception for any amount that I entered until I figured out that I needed to place the for loop inside of the try block.
try
{
if((n1 < 5000) || (n1 > 1000000))
throw new Exception();
for (int i = 0; i < term[0] * 12; i++)
{
double interest_paid = n1 * (rate[0] / 12);
double principal_paid = tr1 - interest_paid;
n1 = n1 - principal_paid;
//Prints the results.
edit.append("\n " + (i+1) + " \t\t " + (two.format(interest_paid))
+ " \t\t " + (two.format(principal_paid)) + " \t\t "
+ (two.format(Math.abs(n1))));
}
}
catch (Exception e)
{
edit.setText("Please enter an amount between $5,000 and $1,000,000.");
mortText.setText("");
out.setText("");
}

Related

Java file is blank when Writing in a file

Appreciate the help. I am using Java and I want to write a text in the file. I am not sure what is wrong with my code. Is below code sufficient since it is a snippets of the program? I am trying to write a text in the file and there is no error. When I tried opening the file, the file is blank.
PharmacyReceipt = is the file where the system will read it and compute the total price
PharmacyInvoice = if the money exceeds the total price, the system will write an invoice and delete the receipt file
Thank you
double change = 0;
grandTotal = 0;
try {
BufferedReader pharmacyFile = new BufferedReader(new FileReader("pharmacyReceipt.txt"));
BufferedWriter write1 = new BufferedWriter(new FileWriter("pharmacyInvoice.txt", true));
String input_1;
System.out.printf("%-16s %-50.30s %-20s %-20s %-20s\n", "Product Code", "Product Name", "Price", "Quantity", "Net Amount");
while ((input_1 = pharmacyFile.readLine()) != null) {
String[] data = input_1.split(",");
adminObject.setProductCode(data[0]);
adminObject.setName(data[1]);
adminObject.setPrice(Double.parseDouble(data[2]));
adminObject.setQuantity(Double.parseDouble(data[3]));
adminObject.setTax(Double.parseDouble(data[4]));
adminObject.setDiscount(Double.parseDouble(data[5]));
int MAX_CHAR = 40;
int maxLength = (adminObject.getName().length() < MAX_CHAR) ? adminObject.getName().length() : MAX_CHAR;
//grossAmount = adminObject.getPrice() * (adminObject.getTax()/100);
//netAmount = adminObject.getQuantity() * (grossAmount - (grossAmount * adminObject.getDiscount()/100));
netAmount = adminObject.getPrice() * adminObject.getQuantity();
System.out.printf("%-16s %-50.30s %-20.2f %-20.2f %.2f\n", adminObject.getProductCode(), adminObject.getName().substring(0, maxLength), adminObject.getPrice(), adminObject.getQuantity(), netAmount);
//System.out.println(adminObject.getProductCode() + "\t \t " + adminObject.getName() + "\t\t " + adminObject.getPrice() + "\t\t " + adminObject.getQuantity() + "\t\t " + adminObject.getTax() + "\t " + adminObject.getDiscount());
grandTotal += netAmount;
}
System.out.printf("\nGrand Total = PHP %.2f\n\n", grandTotal);
pharmacyFile.close();
System.out.print("Do you want to proceed to print the receipt? ");
choice_3 = sc.nextLine();
choice_3 = choice_3.toUpperCase();
if (choice_3.equals("YES") || choice_3.equals("Y")) {
System.out.print("\nHow much is the money? ");
double money = sc.nextDouble();
if (grandTotal <= money) {
BufferedReader groceryFile1 = new BufferedReader(new FileReader("pharmacyReceipt.txt"));
System.out.printf("%-16s %-50.30s %-20s %-15s %-20s\n", "Product Code", "Product Name", "Price", "Quantity", "Net Amount");
while ((input_1 = groceryFile1.readLine()) != null) {
String[] data = input_1.split(",");
adminObject.setProductCode(data[0]);
adminObject.setName(data[1]);
adminObject.setPrice(Double.parseDouble(data[2]));
adminObject.setQuantity(Double.parseDouble(data[3]));
adminObject.setTax(Double.parseDouble(data[4]));
adminObject.setDiscount(Double.parseDouble(data[5]));
int MAX_CHAR = 40;
int maxLength = (adminObject.getName().length() < MAX_CHAR) ? adminObject.getName().length() : MAX_CHAR;
//grossAmount = adminObject.getPrice() * (adminObject.getTax()/100);
//netAmount = adminObject.getQuantity() * (grossAmount - (grossAmount * adminObject.getDiscount()/100));
netAmount = adminObject.getPrice() * adminObject.getQuantity();
write1.write(adminObject.getProductCode() + "," + adminObject.getName() + "," + adminObject.getPrice() + "," + adminObject.getQuantity() + "," + adminObject.getTax() + "," + adminObject.getDiscount() + "," + adminObject.getTax() + "," + adminObject.getDiscount() + "\n");
System.out.printf("%-16s %-50.30s %.2f\t\t %.2f\t\t %.2f\n", adminObject.getProductCode(), adminObject.getName().substring(0, maxLength), adminObject.getPrice(), adminObject.getQuantity(), netAmount);
//System.out.println(adminObject.getProductCode() + "\t \t " + adminObject.getName() + "\t\t " + adminObject.getPrice() + "\t\t " + adminObject.getQuantity() + "\t\t " + adminObject.getTax() + "\t " + adminObject.getDiscount());
}
write1.write("___________________________________________________");
write1.write("\nGrand Total = PHP %.2f\n\n" + grandTotal);
write1.write("Money: " + money + "\n");
write1.write("Change: " + (change = money - grandTotal) + "\n");
write1.write("___________________________________________________\n");
System.out.println("___________________________________________________\n");
System.out.printf("\nGrand Total = PHP %.2f\n\n", grandTotal);
System.out.println("Money: " + money + "\n");
System.out.println("Change: " + (change = money - grandTotal) + "\n");
System.out.println("___________________________________________________\n");
}
} else {
System.out.println("___________________________________________________\n");
System.out.println("***Money exceeds the amount.***");
System.out.println("___________________________________________________\n");
}
pharmacyFile.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found" + e);
} catch (IOException e) {
System.out.println("File Not Found");
} catch (NumberFormatException e) {
System.out.println(e);
} catch (Exception e) {
System.out.println(e);
}
break;
You have to close the writer at the end via writer1.close(). Because you have a BufferedWriter, it is not writing to the file always immediately. If then your program for example exits before it can write, your content to the file, it will remain blank.
Also you should just in general always close this kind of resources at the end as they might cause memory leaks and other problems. You can do it via:
try (FileWriter writer1 = new FileWriter(new File("blablub")) {
// ... do your stuff with the writer
}
This is called a try-with-resources clause and will close the Resource in the end automatically. The more explicit version is:
FileWriter writer1 = new FileWriter(newFile("blablub"));
try {
// ... do your stuff with the writer
} catch (Exception ex) {
...
} finally {
writer1.close();
}
Edit: It might be, that you are thinking that you are closing the writer1 as I've now seen, but actually you have two calls to pharmacyFile.close(). Maybe this is your issue.

Why is this working for one semaphore but not for the other?

I've been trying to make this work, but it keeps getting stuck. The part with withdraw works perfectly but for create it freezes.
tellerReady, queueNotempty, createcomplete, withdrawcomplete and others like that are semaphores. There are several classes which work fine, but the parts you see below are causing problem:
//withdrawal being made
if (task == 2) {
mutex.acquire();
bankTellQueue.add(num);
queueNotEmpty.release();
mutex.release();
tellerReady[num].acquire();
withdraw[num] = 100 * (1 + (int) (Math.random() * 5));
System.out.println("Customer " + num + " requests from the teller " + servingTeller[num] + " to make a withdrawal of $" + withdraw[num]);
Thread.sleep(100);
banktellerRequest[servingTeller[num]].release();
withdrawalReceipt[servingTeller[num]].acquire();
Thread.sleep(100);
System.out.println("Customer " + num + " gets their cash and receipt from the teller " + servingTeller[num]);
withdrawalComplete[servingTeller[num]].release();
}
if (task == 3) {
mutex1.acquire();
bankTellQueue.add(num);
queue1NotEmpty.release();
mutex1.release();
tellerReady[num].acquire();
Create[num] = num;
System.out.println("Customer " +num + " Creates account");
Thread.sleep(100);
banktellerRequest[servingTeller[num]].release();
createComplete[servingTeller[num]].acquire();
Thread.sleep(100);
System.out.println("Account created by teller " +servingTeller[num]);
createComplete[servingTeller[num]].release();
}
Also there is this part in the class of Teller:
if (nextcustomertask == 2) {
Customer.banktellerRequest[num].acquire();
System.out.println("Teller " + num + " processes withdrawal for Customer " + nextcustomer);
Thread.sleep(300);
Customer.customerBalance[nextcustomer] = Customer.customerBalance[nextcustomer] - Customer.withdraw[nextcustomer];
Customer.withdrawalReceipt[num].release();
Customer.withdrawalComplete[num].acquire();
}
//handling create account
if(nextcustomertask ==3 ) {
Customer.banktellerRequest[num].acquire();
System.out.println("Teller " + num + " processes Create account for customer " + nextcustomer);
Thread.sleep(300);
Customer.customerBalance[nextcustomer] = 1000;
Customer.createReceipt[num].release();
Customer.createComplete[num].acquire();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
UPDATE: I found where the problem was. I was using the wrong semaphore.

Program crashes even with try and catch statements

one problem I noticed is that the program crashes if you enter non digits even though there is a catch statement. can someone help me out? I can't seem to find the problem.
Can you also explain what I'm doing wrong and why it's wrong? Thank you in advance.
//previous code had an issue while I was creating a new scanner. it's correct now.
import java.util.*;
public class HighLow {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numberOfAttempts = 0;
System.out.println("WIN THE THREE ROUNDS TO WIN THE GAME!.");
int theNumber = (int) (Math.random() * 10 + 1);
System.out.println("Round 1: I am thinking of a number between" + "\n" + "1 and 10, can you guess the number in " + "\n" + "less than 3 attempts?");
System.out.println("Type a number below and press enter.");
int guess = 0;
do {
try {
guess = scan.nextInt();
if (guess != theNumber) {
if (guess < theNumber) {
System.out.println("Sorry " + guess + " is too low, please try again");
}else if (guess > theNumber) {
System.out.println("Sorry " + guess + " is too high, please try again." );
}
numberOfAttempts = numberOfAttempts + 1;
}else {
System.out.println(guess + " is the correct answer. You got it on" + "\n" + "attempt number " + (numberOfAttempts + 1) + ". Proceeding to round 2.");
theNumber = (int) (Math.random() * 100 + 1);
System.out.println("\n" + "Round 2: I am thinking of a number between " + "\n" + "1 and 100, can you guess the number in " + "\n" + "less than 6 attempts?");
numberOfAttempts = 0;
int secondRoundGuess = 0;
do {
try {
secondRoundGuess = scan.nextInt();
if (secondRoundGuess != theNumber) {
if (secondRoundGuess < theNumber) {
System.out.println("Sorry " + secondRoundGuess + " is too low, please try again");
}else{
System.out.println("Sorry " + secondRoundGuess + " is too high, please try again");
}
numberOfAttempts = numberOfAttempts + 1;
}
else {
System.out.println(secondRoundGuess + " is the correct answer. You got it on " + "\n" + "attempt number " + (numberOfAttempts + 1) + "." + "\n" + "Proceeding to round 3.");
System.out.println("\n" + "Round 3: I am thinking of a number between " + "\n" + "1 and 1000, can you guess the number in " + "\n" + "less than 10 attempts?");
theNumber = (int)(Math.random() * 1000 + 1);
numberOfAttempts = 0;
int thirdRoundGuess = 0;
do {
try {
thirdRoundGuess = scan.nextInt();
if (thirdRoundGuess != theNumber) {
if (thirdRoundGuess < theNumber) {
System.out.println("Sorry " + thirdRoundGuess + " is too low, please try again");
}else {
System.out.println("Sorry " + thirdRoundGuess + " is too high, please try again");
}
numberOfAttempts = numberOfAttempts + 1;
}else{
System.out.println(thirdRoundGuess + " is the correct answer.");
System.out.println("You won the game, you are a badass." + "\n" + "I made this game and I cant even beat " + "\n" + "level 3.");
System.out.println("I am a newbie at programming and it's my " + "\n" + "fourth month on this java journey ." + "\n" + "I am looking for fellow newbies who are willing " + "\n" + "to learn and grow together (or advanced programmers " + "\n" + "who will not get annoyed by teaching newbies)." + "\n" + "If you get to this point in the game " + "\n" + "and see this message, hit me up via direct " + "\n" + "messaging, lets create a group where we can learn " + "\n" + "and grow together.");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
thirdRoundGuess = scan.nextInt();
}
}while(numberOfAttempts != 10);
System.out.println("Game over, you were so close. Try again");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
secondRoundGuess = scan.nextInt();
}
}while(numberOfAttempts != 6);
System.out.println("Game Over. Try again?");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
guess = scan.nextInt();
}
}while (numberOfAttempts != 3);
System.out.println("Game Over. Try again?");
scan.close();
}
}
The root cause of the problem is using scan.nextInt() inside the catch block. What is happening is guess = scan.nextInt(); just below the try is throwing an exception for non-integer input and the control enters the catch block where it encounters guess = scan.nextInt(); again which tries to consume the Enter from the last input causing the program to crash as Enter is not an int.
How to get rid of it?
You need to make two changes to get rid of the problem:
A. Use guess = Integer.parseInt(scan.nextLine()); in which scan.nextLine() will also consume Enter.
B. Comment out the line, guess = scan.nextInt(); as shown below:
} catch (Exception e) {
System.out.println("Please enter a number.");
//guess = scan.nextInt();
}
This is the exception stack trace you get when you run the code:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at HighLow.main(HighLow.java:137)
When you handle the exception first time the user types in a non-numeric value, the exception gets handled below:
catch(Exception e) {
System.out.println("Please enter a number.");
guess = scan.nextInt();
}
When it reaches guess = scan.nextInt();, the previous non-numeric value is still present in the scanner. And when it tries to get an integer out of the scanner when it has a non-numeric value, it throws another InputMismatchException inside catch that is not handled.

recognize string as input and throw exception if not an integer

I'm new to java and was trying to do this program. Basically entering 3 numbers, it will calculate the volume of a cube. If a negative number is typed then it will throw an exception, and also when there are more then 3 input. I wanted it to throw an exception also, if the input is not a number, but I have no idea how to store the input inside a variable and then check if it's a string and eventually throw an exception. Any suggestions? Here's my code
public class CubeVolume
{
public static void main(String [] args)
{
try
{
// try if there is more than 3 arguments
int width = Integer.parseInt(args[0]);
int depth = Integer.parseInt(args[1]);
int hight = Integer.parseInt(args[2]);
if (args.length > 3)
throw new ArrayIndexOutOfBoundsException
("You have supplied " + args.length + " arguments!");
// try if there is less than 3 arguments
if (args.length < 3)
throw new ArrayIndexOutOfBoundsException
("You have supplied " + args.length + " arguments!");
// checks if the width entered is equal or less than 0
if (width <= 0)
throw new NumberFormatException
("The argument " + width + " is a negative number!");
// checks if the depth entered is equal or less than 0
if (depth <= 0)
throw new NumberFormatException
("The argument " + depth + " is a negative number!");
// checks if the hight entered is equal or less than 0
if (hight <= 0)
throw new NumberFormatException
("The argument " + hight + " is a negative number!");
int volume = width * depth * hight;
System.out.println("The volume of a cube with dimensions " + "(" + width
+ "," + hight + "," + depth + ") " + "is " + volume);
} // try
// if there's one than more argument error will be displayed
catch (ArrayIndexOutOfBoundsException exception)
{
System.out.println("Please supply width, depth and hight arguments!");
System.out.println("Exception message was: '" + exception.getMessage()
+ "'");
System.err.println(exception);
} // catch
// if a negative number is entered error will be displayed
catch (NumberFormatException exception)
{
System.out.println("Dimensions for a cube can't be negative, please "
+ "insert only positive whole numbers!");
System.out.println("Exception message was: '" + exception.getMessage()
+ "'");
System.err.println(exception);
} // catch
} // main
} // CubeMain
This:
int width = Integer.parseInt(args[0]);
already throws a NumberFormatException if the String in question is not a valid string representation of an integer.
EDIT:
To address your comments:
public class CubeVolume {
private int width;
private int depth;
private int height;
public static void main(String [] args) {
if (args.length != 3) {
throw new Exception("Width, height and depth are required arguments");
}
width = Integer.parseInt(args[0]);
depth = Integer.parseInt(args[1]);
height = Integer.parseInt(args[2]);
// more stuff here
}
}
You can create your own exception class and throw the instance of that class from a method.
The exception class:
// Extending Exception makes your class throwable
class MyException extends Exception {
public MyException( String string ) {
super( string );
}
}
And for parsing the input string to integer, call a method like this :
int width = parseInt(args[0]);
where your parseInt() method throws your custom exception as follows:
private int parseInt( String number ) throws Exception {
try {
return Integer.parseInt( number );
} catch ( Exception e ) {
throw new MyException( "The input is not a number" );
}
}
Now, you can catch your custom exception MyException similar to other standard exceptions:
// catching your custom exception
catch ( MyException e ) {
System.err.println( e );
}
// if there's one than more argument error will be displayed
catch (ArrayIndexOutOfBoundsException exception)
{
System.out.println("Please supply width, depth and hight arguments!");
System.out.println("Exception message was: '" + exception.getMessage()
+ "'");
System.err.println(exception);
} // catch
// if a negative number is entered error will be displayed
catch (NumberFormatException exception)
{
System.out.println("Dimensions for a cube can't be negative, please "
+ "insert only positive whole numbers!");
System.out.println("Exception message was: '" + exception.getMessage()
+ "'");
System.err.println(exception);
} // catch

Round Robin in Java

I am working on a round robin algorithm in Java, and I have a loop that is not working correctly. I believe it is a simple logic error that I am missing. The exec[] array holds execution times for processes in a cpu. I need the quantam to be subtracted from that time or the amount of time left if less than the quantam. Then I need it to check the next process. Each process should have one pass through until the execution time is 0. The sum makes sure that the statements keep running while there is any one process that needs to run. The sum is simply from adding all the array element times.
while (sum != 0) {
int show = i + 1;
if (exec[i] != 0 && exec[i] > quant) {
exec[i] = exec[i] - quant;
sum = sum - quant;
JOptionPane.showMessageDialog(null, "Process" + " " + show + " is at" + " " + exec[i]);
JOptionPane.showMessageDialog(null, "sum" + " " + " is " + sum);
if (i == irq - 1) {
i = 0;
} else {
i++;
}
}
if (exec[i] != 0 && exec[i] < quant) {
exec[i] = exec[i] - exec[i];
sum = sum - exec[i];
JOptionPane.showMessageDialog(null, "Process" + " " + show + " is at" + " " + exec[i]);
JOptionPane.showMessageDialog(null, "sum" + " " + " is " + sum);
if (i == irq - 1) {
i = 0;
} else {
i++;
}
}
}
Please let me know if there is a fix or if any more information is needed. Thanks!
exec[i]=exec[i]-exec[i];
sum=sum-exec[i];
Is same as
exec[i]=0;
sum=sum-0;
Also, you don't treat the case of exec[i]==quant
I am not sure, what you want to do. It sounds like "I want Multithreading to make my application faster" but within in Single-Core loop, you won't succeed.
If you want a CPU round robin, let the JVM (or the operating system) decide. Both are made for this:
Some kind of java pseudo-Code:
int threadPoolSize = Runtime.getRuntime().availableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(threadPoolSize);
pool.execute(new ImplementationOfCallableOrRunnable());
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

Categories

Resources