Problems with implementing exceptions in Java - 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.

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;
}
}

Java Exception Handling Assignment

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
}

Java: how to read an input int

So, I was looking for an efficient way, using Java's standard packages, to read an input integer... For example, I came across the class "Scanner", but I found two main difficulties:
if I don't insert an int, I'm not actually able to solve the exception;
this class works with tokens, but my aim is to load the string in its full length.
This is an example of execution I would like to realize:
Integer: eight
Input error - Invalid value for an int.
Reinsert: 8 secondtoken
Input error - Invalid value for an int.
Reinsert: 8
8 + 7 = 15
And this is the (incorrect) code I tried to implement:
import java.util.Scanner;
import java.util.InputMismatchException;
class ReadInt{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
boolean check;
int i = 0;
System.out.print("Integer: ");
do{
check = true;
try{
i = in.nextInt();
} catch (InputMismatchException e){
System.err.println("Input error - Invalid value for an int.");
System.out.print("Reinsert: ");
check = false;
}
} while (!check);
System.out.print(i + " + 7 = " + (i+7));
}
}
Use a BufferedReader. Check NumberFormatException. Otherwise very similar to what you have. Like so ...
import java.io.*;
public class ReadInt{
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
boolean check;
int i = 0;
System.out.print("Integer: ");
do{
check = true;
try{
i = Integer.parseInt(in.readLine());
} catch (NumberFormatException e){
System.err.println("Input error - Invalid value for an int.");
System.out.print("Reinsert: ");
check = false;
}
} while (!check);
System.out.print(i + " + 7 = " + (i+7));
}
}
To use with tokens:
int i = Integer.parseInt(in.next());
Then you could do:
int i;
while (true) {
System.out.print("Enter a number: ");
try {
i = Integer.parseInt(in.next());
break;
} catch (NumberFormatException e) {
System.out.println("Not a valid number");
}
}
//do stuff with i
That above code works with tokens.

Categories