Java Exception Handling Assignment - java

So I've recently learned exception handling for Java and I'm still trying to get used to it and all but I feel like I'm missing something. I was doing an assignment for my class and the compiler doesn't like my code.
I'm supposed to be making a Calculator that takes in an operator and then a number, and if the operator (+, -, *, /) given is not one of the aforementioned four, then an exception is thrown.
I used try-catch but for some reason the try and catch aren't recognizing each other unless I place them next to each other which isn't really what I want.
My question is really: Is there a way for my try and catch to recognize each other without being right next to each other, so I can run code in-between them? Or is that impossible and I'm doing it all wrong?
Here's my code so far:
import java.util.*;
public class Calculator
{
public static void main(String[] args)
{
String operatorInput;
double numberInput;
String userRedo = "Y";
double result = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("Type in an arithmetic operator of your choice and press enter.");
System.out.println("Then, please type in a number that will undergo the operation.");
while((userRedo.toUpperCase()).compareTo("Y")==0)
{
try
{
operatorInput = input.nextLine();
if(operatorInput.compareTo("+")!=0||operatorInput.compareTo("-")!=0||
operatorInput.compareTo("*")!=0||operatorInput.compareTo("/")!=0)
{
throw new UnknownOperatorException("Unknown operator!");
}
}
numberInput = input.nextDouble();
if(operatorInput.compareTo("+")==0)
{
result += numberInput;
} else if(operatorInput.compareTo("-")==0)
{
result -= numberInput;
} else if(operatorInput.compareTo("*")==0)
{
result = result * numberInput;
} else
{
result = result / numberInput;
}
System.out.println("\nresult "+operatorInput+" "+numberInput+"= ");
System.out.println("Updated result: "+result);
System.out.println("Again? (y/n)");
userRedo = input.nextLine();
catch(UnknownOperatorException e)
{
System.out.println(e.getMessage());
}
}
}
}
And here's the exception class I made:
public class UnknownOperatorException extends Exception
{
public UnknownOperatorException()
{
super("Please select an actual operator and try again: ");
}
public UnknownOperatorException(String message)
{
super(message);
}
}

They have to be next to each other. There's a few things you could do:
Move the } at the commented line down a ways, like this
while((userRedo.toUpperCase()).compareTo("Y")==0)
{
try
{
operatorInput = input.nextLine();
if(operatorInput.compareTo("+")!=0||operatorInput.compareTo("-")!=0||
operatorInput.compareTo("*")!=0||operatorInput.compareTo("/")!=0)
{
throw new UnknownOperatorException("Unknown operator!");
}
}//this one here
Take that and move it to here
System.out.println("\nresult "+operatorInput+" "+numberInput+"= ");
System.out.println("Updated result: "+result);
}// put it here
Then take these two lines
System.out.println("Again? (y/n)");
userRedo = input.nextLine();
And move them below the catch:
catch(UnknownOperatorException e)
{
System.out.println(e.getMessage());
}
System.out.println("Again? (y/n)");
userRedo = input.nextLine();
}
}
That will let your while loop still sort of function and make your try/catch work. You might need to tweak things a bit to make them work right though

In order for try/catch to work, as Ghost says in a comment, you will need to put them next to each other.

And the code above has some problems...
maybe this works.
public static void main(String[] args) {
String operatorInput=null;
double numberInput;
String userRedo = "Y";
double result = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("Type in an arithmetic operator of your choice and press enter.");
System.out.println("Then, please type in a number that will undergo the operation.");
while ((userRedo.toUpperCase()).compareTo("Y") == 0) {
try {
operatorInput = input.nextLine().trim();
if (operatorInput.compareTo("+") != 0
&& operatorInput.compareTo("-") != 0
&& operatorInput.compareTo("*") != 0
&& operatorInput.compareTo("/") != 0) {
throw new UnknownOperatorException("Unknown operator!");
}
} catch (UnknownOperatorException e) {
System.out.println(e.getMessage());
continue;
}
numberInput = Double.parseDouble(input.nextLine());
if (operatorInput.compareTo("+") == 0) {
result += numberInput;
} else if (operatorInput.compareTo("-") == 0) {
result -= numberInput;
} else if (operatorInput.compareTo("*") == 0) {
result = result * numberInput;
} else {
result = result / numberInput;
}
System.out.println("\nresult " + operatorInput + " " + numberInput + "= ");
System.out.println("Updated result: " + result);
System.out.print("Again? (y/n) : ");
userRedo = input.nextLine();
}
input.close();
}

public class Building implements CarbonFootprint {
//implement 4a
void getCarbonFootprint(){
System.out.println("Kim Byers, CSIS 505, Exception Handling, Assignment1");
//Building display
double Bill;
}
//class variables
double monthlyElectricBill;
double monthlyGasBill;
//constructor
public void Building(double monthlyElectricBill, double monthlyGasBill) {
monthlyElectricBill = ([monthyly Electric Billmonth;
monthlyGasBill = monthlyGasBill;
//Constructor
//set method statements
}

Related

I'm trying to make my program throw an IllegalArgumentException if the input is not a number

I'm trying to make it to were is will throw my exception if the input is not a number and i cant figure it out, Could someone help me get on the right track
import java.util.Scanner;
class calculations
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int number;
int total = 0;
try
{
} catch ( IllegalArgumentException e)
{
//error
}
while (true)
{
number = scan.nextInt();
if (number == 0)
{
break;
}
total += number;
}
System.out.println("Total is " + total);
}
}
You should use hasNextInt, which will allow you to check if the next token in the stream can be parsed as an int.
if (! scanner.hasNextInt()) throw new IllegalArgumentException()

java catch a NumberFormatException on a Numeric type

Hi I have created a quiz application using java but I am unsure how to implement this small section. It asks me to :
Add an exception to catch a NumberFormatException on a NumericQuestion type if the user enters a character i.e. ‘a’
I initially tried inserting a try catch block at the beginning of the presentQuestion method but it threw me a lot of errors. I don't have much experience in implementing these try-catch methods. I know its probably something simple so any help would be appreciated cheers.
My code is show below.
package QuestionGame;
import java.util.Scanner;
public class NumericQuestionTester {
public static void main(String[] args) {
boolean userCorrect;
Scanner input = new Scanner(System.in);
NumericQuestion quThree = new NumericQuestion("What is the answer to 5 divided by 3?", "1.67", 2, 0.03, 0.07);
presentQuestion(input, quThree);
input.close();
}
public static void presentQuestion(Scanner input, NumericQuestion q) {
boolean userCorrect;
q.displayQuestion();
System.out.println("Enter your answer: ");
String answer = input.nextLine();
userCorrect = q.checkAnswer(answer);
if (userCorrect){
System.out.println("Correct! The answer is : " + q.getAnswer() + " and you have a score of : " + q.getMark());
} else {
System.out.println(answer + " is incorrect. You scored zero.");
}
System.out.println();
}
}
package QuestionGame;
public class NumericQuestion extends Question {
//instance variables
private double ansNumeric;
private double positiveRange;
private double negativeRange;
//constructor
public NumericQuestion(String quText, String answer, int mark, double positiveRange, double negativeRange) {
super(quText, answer, mark);
this.ansNumeric = Double.parseDouble(answer);
this.positiveRange = positiveRange;
this.negativeRange = negativeRange;
}
//accessors & mutators
public double getAnsNumeric() {
return ansNumeric;
}
public void setAnsNumeric(double ansNumeric) {
this.ansNumeric = ansNumeric;
}
//methods
public boolean checkAnswer (String answer) {
double answerDouble = Double.parseDouble(answer);
if (answerDouble > (this.ansNumeric + this.positiveRange)) {
return false;
} else if (answerDouble < (this.ansNumeric - this.negativeRange)) {
return false;
} else {
return true;
}
}
}
Apart exception handling, I suggest you add persistent check while user will not put expected integer answer.
do{
System.out.println("You Numeric answer, please")
String answer = input.nextLine();
}while !answerIsNumeric(answer);
userCorrect = q.checkAnswer(answer);
public boolean answerIsNumeric(String answer){
try{
Double.parseDouble(answer);
}catch(NumberFormatException e){
return false;
}
return true;
}
There are many ways to achieve this, depending on the application design. I'll show you one here - please provide more details if this does not apply, though I guess this is what you are looking for
public static void presentQuestion(Scanner input, NumericQuestion q) {
boolean userCorrect = false;
boolean isAnswerNumeric = false;
String answer = null;
while(! isAnswerNumeric){
q.displayQuestion();
System.out.println("Enter your answer (numeric only) : ");
answer = input.nextLine();
try{
Double.parseDouble(answer);
isAnswerNumeric = true;
}catch(NumberFormatException nfe){
// do nothing in this case.. if the number format is correct,
// the isAnswerNumeric will be set to true
}
}
userCorrect = q.checkAnswer(answer);
if (userCorrect){
System.out.println("Correct! The answer is : " + q.getAnswer() + " and you have a score of : " + q.getMark());
} else {
System.out.println(answer + " is incorrect. You scored zero.");
}
System.out.println();
}
You can adapt the code to display an error message or whatever you want to do in the catch block. In this case, as a simple example, the question is asked again until the answer is numeric
You might just need to parse your answer String into a number with Float.parseFloat and catch the NumberFormatException.
Example:
String answer = "3.14";
try {
float numericAnswer = Float.parseFloat(answer);
System.out.println("numericAnswer=" + numericAnswer);
} catch (NumberFormatException e) {
System.err.println(answer + " is not a number.");
}
And if by Add an exception to catch a NumberFormatException - which does not make much sense as a sentence - they mean throw an exception, just add in the catch block
throw new WhateverException(answer + " is not a number."); (f.ex. you could throw a RuntimeException).

Catching IllegalArgumentException?

I am having a little bit of a problem here. I am trying to figure out how to catch the IllegalArgumentException. For my program, if the user enters a negative integer, the program should catch the IllegalArgumentException and ask the user if he/she wants to try again. But when the exception is thrown, it doesn't give that option. It just terminates. I tried to use the try and catch method but it doesn't work for me. How do I catch this particular exception to continue to run instead of terminating?
public static void main(String[] args) throws IllegalArgumentException
{
String keepGoing = "y";
Scanner scan = new Scanner(System.in);
while(keepGoing.equals("y") || keepGoing.equals("Y"))
{
System.out.println("Enter an integer: ");
int val = scan.nextInt();
if (val < 0)
{
throw new IllegalArgumentException
("value must be non-negative");
}
System.out.println("Factorial (" + val + ") = "+ MathUtils.factorial(val));
System.out.println("Another factorial? (y/n)");
keepGoing = scan.next();
}
}
}
and
public class MathUtils
{
public static int factorial(int n)
{
int fac = 1;
for(int i = n; i > 0; i--)
{
fac *= i;
}
return fac;
}
}
You need to add the try catch block inside the loop to continue the working for the loop. Once it hits the illegal argument exception catch it in catch block and ask if the user wants to continue
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
String keepGoing = "y";
populate(keepGoing);
}
static void populate( String keepGoing){
Scanner scan = new Scanner(System.in);
while(keepGoing.equalsIgnoreCase("y")){
try{
System.out.println("Enter an integer: ");
int val = scan.nextInt();
if (val < 0)
{
throw new IllegalArgumentException
("value must be non-negative");
}
System.out.println("Factorial (" + val + ") = "+ MathUtils.factorial(val));
System.out.println("Another factorial? (y/n)");
keepGoing = scan.next();
}
catch(IllegalArgumentException i){
System.out.println("Negative encouneterd. Want to Continue");
keepGoing = scan.next();
if(keepGoing.equalsIgnoreCase("Y")){
populate(keepGoing);
}
}
}
}
}
Hope this helps.
Happy Learning :)
I don't think you want your main() method to be throwing an exception. Typically, this is the kind of thing that you'd put in try and catch blocks.
Honestly though, for this sort of thing an if/else would work better. (Unless you're just doing this as a toy example, to learn exceptions.)
Make another method called getNumber() that throws the IllegalArgumentException, that returns an int. Then put it inside the try/catch in the main().
public static void main(String[] args)
{
String keepGoing = "y";
Scanner scan = new Scanner(System.in);
while(keepGoing.equals("y") || keepGoing.equals("Y"))
{
int val = 0;
boolean flag=true;
while(flag){
try{
System.out.println("Enter an integer: ");
val = scan.nextInt();
if (val < 0)
{
throw new IllegalArgumentException
("value must be non-negative");
}
flag = false;
} catch(IllegalArgumentException e){
System.out.println("value must be non-negative");
}
}
System.out.println("Factorial (" + val + ") = "+ MathUtils.factorial(val));
System.out.println("Another factorial? (y/n)");
keepGoing = scan.next();
}
}
}
I would suggest you add a test on the negative value and display your message on the spot, then use an else block. Also, you could use String.equalsIgnoreCase() in your loop test like
String keepGoing = "y";
Scanner scan = new Scanner(System.in);
while (keepGoing.equalsIgnoreCase("y")) {
System.out.println("Enter an integer: ");
int val = scan.nextInt();
if (val < 0) {
System.out.println("value must be non-negative");
} else { // <-- skip negative value
System.out.println("Factorial (" + val + ") = "
+ MathUtils.factorial(val));
}
System.out.println("Another factorial? (y/n)");
keepGoing = scan.next();
}
Also, an int factorial(int) method can only the first 12 correct values. You could use a long or a BigInteger like
public static BigInteger factorial(int n) {
BigInteger fac = BigInteger.ONE;
for (int i = n; i > 1; i--) {
fac = fac.multiply(BigInteger.valueOf(i));
}
return fac;
}
Similar to some other answers, I would say that your main() method should not throw an exception to display an error message to the user, because that is not the purpose of exception handling mechanisms in Java. Exception handling is designed to enable methods to signal that something happened that should not have happened, so the methods that call those methods will know that they need to deal with them. In general, exceptions are caught, not thrown, by main() methods and other user interface methods.
I would make the method factorial() throw the IllegalArgumentException, rather than your main() method in your program class. Your main() method should use try and catch to handle this exception. With this design, if someone else wanted to use your MathUtils class, they would know that your factorial() method throws an IllegalArgumentException (especially if you document your code with javadoc), and would write their code to handle the exception. In the current situation, if someone tries to call MathUtils.factorial(-1), the return value would be 1 because the for loop inside factorial() would not execute at all (because i is initially set to -1, which is not greater than 0).
This is how I would revise your code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String keepGoing = "y";
while(keepGoing.equalsIgnoreCase("y")) {
try { // This code might throw an exception
System.out.println("Enter an integer: ");
int val = scan.nextInt();
System.out.println("Factorial (" + val + ") = "+ MathUtils.factorial(val));
System.out.println("Another factorial? (y/n)");
keepGoing = scan.next();
} catch (IllegalArgumentException | InputMismatchException e) {
/* An InputMismatchException is thrown if the input is not an integer.
See the documentation for Scanner method nextInt() for more details.
*/
System.out.println("You must enter a non-negative integer.");
System.out.println("Try again? (y/n)");
keepGoing = scan.next();
}
}
}
}
and
public class MathUtils throws IllegalArgumentException {
public static int factorial(int n) {
if (fac < 0) {
throw new IllegalArgumentException("value must be non-negative");
}
int fac = 1;
for(int i = n; i > 0; i--) {
fac *= i;
}
return fac;
}
}

Array not Recognized

My program is to enter 10 numbers and add them together then display the result. Then I am to divide the smaller number by the larger number and display the result. Users cannot enter characters or zero.
I am new and have been working on this for DAYS. I do not see my mistake.
Now my problem is the Variable i isn't being recognized.
I introduced an Exception (try..catch) and it wouldn't read. I tried moving things all over (I'm new, I'm guessing and seeing what does what..) I did something wrong and probably something stupidly small. I need some help and fresh eyes.
I also need to end the program when the user enters 9999. Any idea where that would go? 'Cause I'm about to break out into tears.
public static void main(String[] args) throws NumberFormatException {
Scanner in = new Scanner(System.in);
Scanner input = new Scanner(System.in);
double[ ] digit = new double[11];
int sum = 0;
//Declare an array
System.out.print("Please Enter Ten Numbers:");
System.out.println();
try{
for (int i = 1; i < digit.length; i++)
System.out.print("Numbers " + i + ": ");
digit[i] = (double)in.nextInt(); //Array Not recognized here
sum += (int)digit[i];//Or recognized here
// Input the data into array from the user.
if(digit[i]==0.0)//None of these are recognized either, what did I do?
{
System.out.println("You can't enter zero. Try again");
--i; //nope
in.nextLine();//dispose of wrong number
}
}catch (NumberFormatException e){
System.out.println("You Can Only Enter Numbers!");
--i; //nope, not recognizing here either
in.nextLine();//dispose of wrong input
}
System.out.println("Total Values in Array:"+ sum);
// Calculate the sum and print the total
System.out.println();
System.out.println("Would you like to divide the values?");
System.out.println("Yes or No to Exit the Program");
String a = input.next();
if(a.equalsIgnoreCase("yes")){
double [] divisionResult = new double[digit.length / 2];
//Division array declared
for (int i = 1; i < digit.length; i += 2)
//These are all good and recognized. No problem with the division part
{
double result = digit[i];
if (result > digit[i + 1])
result = result / digit[i + 1];
else {
result = digit[i + 1] / result;
}
divisionResult [i / 2] = result;
System.out.println(result);
}
}
else if(a.equalsIgnoreCase("no")){
System.exit(0);
}
}
}
}
You for loop doesn't have braces around it. Only the first line below it is part of the loop.
You need braces around the contents of your for loop.
I have tried to modified the attached code snippet. Hope this might help you.
package com.so.general;
import java.util.Scanner;
public class AddNumbers
{
private static final int SIZE_OF_ARRAY = 10;
public static void main(String[] args)
{
int counter = 0;
double sumOfTenDigits = 0.0;
double[] digit = new double[SIZE_OF_ARRAY];
int listOfElements = digit.length;
System.out.print("Please Enter Ten Numbers:"+"\n");
Scanner readInputFromUser = new Scanner(System.in);
try
{
for (counter=0; counter<listOfElements; counter++)
{
System.out.print("Numbers " + (counter+1) + ": ");
digit[counter] = Double.parseDouble(readInputFromUser.next());
if(digit[counter] == 0.0)
{
System.out.println("Zero is not allowed. Please try again.");
System.out.print("Numbers " + (counter+1) + ": ");
digit[counter] = Double.parseDouble(readInputFromUser.next());
}
sumOfTenDigits += digit[counter];
}
}
catch(NumberFormatException numberFormatExcep)
{
System.err.println(" You have entered other than numbers. Only numbers are allowed. Terminating the program.");
numberFormatExcep.printStackTrace();
System.exit(0);
}
System.out.println("Addition is: "+ sumOfTenDigits);
System.out.println("Would you like to divide the values? Press Y to continue, any other character to terminate the program.");
Scanner continueWithDivide = new Scanner(System.in);
String userInput = continueWithDivide.nextLine();
closeScanner(readInputFromUser);
closeScanner(continueWithDivide);
if(readInputFromUser != null)
{
readInputFromUser.close();
}
// Always use static string literals on the left hand side.
// This prevents Null pointer exception.
if("Y".equalsIgnoreCase(userInput))
{
double[] divisionResult = new double[listOfElements/2];
for(int i=0; i<listOfElements; i+=2)
{
double result = digit[i];
if (result > digit[i+1])
{
result = result/digit[i+1];
}
else
{
result = digit[i+1]/result;
}
divisionResult[i/2] = result;
System.out.println(result);
}
}
else
{
System.out.println("You have entered "+userInput+". Terminating the program.");
System.exit(0);
}
}
/**
* Closed the scanner
* #param scanner
*/
public static void closeScanner(Scanner scanner)
{
if(scanner != null)
{ try
{
scanner.close();
}
catch(IllegalStateException illegatStateExcep)
{
System.err.println("Scanner is already closed.");
illegatStateExcep.printStackTrace();
}
}
}
Please note the below points:
Always use proper indentation.
Always match { }
Even if your if or for is having only one statement, use { }.
For example:
for (int counter=1; i<digit.length; i++)
{
System.out.print("Numbers " + i + ": ");
}
Above three points will save a lot of your time if some thing goes wrong in your program.
Use proper name for the variables and method.
Always close the IO resources after the use.
For example:
if(scanner != null)
{
scanner.close();
}

Problems with implementing exceptions in Java

I want to write a program which converts a binary number in a decimal.
Ive found out that the problem is that I cant even get the "catch path".
I also know that I have to change somthing with the char but I absolutely dont get a working solution. Thank you.
import java.util.Scanner;
public class BinaryStringToNumber {
public static void main(String[] args) {
String inputBinaer;
Scanner input = new Scanner(System.in);
System.out.print("Type in a binary number: ");
inputBinaer = input.next();
input.close();
try
{
convert(inputBinaer);
}
catch (NumberFormatException e)
{
System.out.println( "Just numbers!" );
} finally {
System.out.println( "Finally" );
}
}
public static void convert(String inputBinaer) throws NumberFormatException{
char [] puffer;
int dez = 0;
puffer = inputBinaer.toCharArray();
for(int i=0;i<puffer.length;i++){
if(puffer[i]== '1'){
dez = (int) (dez + Math.pow(2, puffer.length-1-i));
}
}
System.out.println("The decimal number is: " + dez);
}
}
To get to the catch block, an exception has to be thrown somewhere. Normally, the Java methods do this for you, but since you are parsing everything yourself, you will have to throw the exception. One way would be to add a throw statement to the convert() method whenever it encounters an invalid digit:
import java.util.Scanner;
public class BinaryStringToNumber {
public static void main(String[] args) {
String inputBinaer;
Scanner input = new Scanner(System.in);
System.out.print("Type in a binary number: ");
inputBinaer = input.next();
input.close();
try
{
convert(inputBinaer);
}
catch (NumberFormatException e)
{
System.out.println( "Just numbers!" );
} finally {
System.out.println( "Finally" );
}
}
public static void convert(String inputBinaer) throws NumberFormatException{
char [] puffer;
int dez = 0;
puffer = inputBinaer.toCharArray();
for(int i=0;i<puffer.length;i++){
if(puffer[i]== '1'){
dez = (int) (dez + Math.pow(2, puffer.length-1-i));
} else if (puffer[i] != '0') {
throw new NumberFormatException("Invalid digit: " + puffer[i]);
}
}
System.out.println("The decimal number is: " + dez);
}
}
You need to specify where do you throw the NumberFormatException. I'd put an if in the for loop where I'd check the char, and if it was not a '0' or a '1', I'd throw an exception. Hope I helped.
You can throw NumberFormatException in case of bad input. That is allowed in Java.

Categories