Hello Guest, please login or register.
Did you miss your activation email?
Login with username, password and session length.

Pages: [1]   Go Down

Author Topic: Catching Exceptions?  (Read 4506 times)

0 Members and 1 Guest are viewing this topic.
Catching Exceptions?
« on: March 13, 2011, 05:58:24 pm »
  • *
  • Reputation: +2/-0
  • Offline Offline
  • Gender: Male
  • Posts: 1767
So I'm having a bit of trouble figuring out how to do this problem for my programming class:
Quote from: P11.14
Write a program that asks the user to input a set of floating-point values. When the user enters a value that is not a number, give the user a second chance to enter the value. After two chances, quit reading input. Add all correctly specified values and print the sum when the user is done entering data. Use exception handling to detect improper inputs.

I'll start up the program enter a few numbers, then give it bad input. For some reason it completely disregards the fact I'm even attempting to give the user a second chance and trying to catch another exception.
So this is the kind of output I'm getting:
Quote
Enter a floating point number: 5
Enter a floating point number: 2.5
Enter a floating point number: s
Bad data: Input needs to be a floating point number! Try again.
Enter a floating point number: Bad data: Input needs to be a floating point number! Try again.
The sum is 7.5

Process completed.

The source for my latest attempt is as follows:
InputFloat.java:
Code: [Select]
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class InputFloat
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
boolean done = false;
ArrayList<Double> data = new ArrayList<Double>();
while(!done)
{
try
{
while (true)
{
System.out.print("Enter a floating point number: ");
if (!in.hasNextDouble())
throw new BadDataException("Input needs to be a floating point number! Try again.");
data.add(in.nextDouble());
}
}
catch (BadDataException exception)
{
System.out.println("Bad data: " + exception.getMessage());
in.close();
}
//----------------
in = new Scanner(System.in);
try
{
while (true)
{
System.out.print("Enter a floating point number: ");
if (!in.hasNextDouble())
throw new BadDataException("Input needs to be a floating point number! Try again.");
data.add(in.nextDouble());
}
}
catch (BadDataException exception)
{
System.out.println("Bad data: " + exception.getMessage());
done = true;
}
}
double sum = 0;
for (double d : data)
sum = sum + d;
System.out.println("The sum is " + sum);
}
}

BadDataException.java:
Code: [Select]
import java.io.IOException;

public class BadDataException extends IOException
{
public BadDataException()
{
}

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

I've tried several different approaches and can't seem to make it any further. At this point I'm really not sure what to do. It's probably something simple that I'm overlooking, or perhaps I just don't completely understand how exceptions work. Haha. Any suggestions?
Logged
  • https://colbydude.com

Xiphirx

wat
Re: Catching Exceptions?
« Reply #1 on: March 13, 2011, 08:17:49 pm »
  • Xiphirx
  • *
  • Reputation: +0/-0
  • Offline Offline
  • Gender: Male
  • Posts: 3007
I think you might want to put the try catch block in a while loop. Here is some code for ya (I don't know Java yet so syntax may be !@#$% :P)

Code: [Select]
while (!done)
{
try
{
System.out.print("Enter a float please: ");

if (!in.hasNextDouble())
throw new BadDataException("Input needs to be a floating point number! Try again.");
else
data.add(in.nextDouble());
}
catch(BadDataException exc)
{
System.out.println("Bad data: " + exc.getMessage());

System.out.print("Enter a float please: ");

if (!in.hasNextDouble())
{
System.out.println("Bad data: Input needs to be a floating point number! Chances are up!.");
done = true;
}
else
{
data.add(in.nextDouble());
}
}
}
Logged
  • For The Swarm
Re: Catching Exceptions?
« Reply #2 on: March 13, 2011, 08:35:51 pm »
  • Wooper Don't Give a !@#$%
  • *
  • Reputation: +16/-0
  • Offline Offline
  • Gender: Male
  • Posts: 1457
I'd feel a little more comfortable answering this if I had the JDK setup on this computer and if I had more experience with Java, but I'll give it a shot anyway

Now you notice the program is asking you to continuously accept input until a user screws up twice. It doesn't specify whether the user's chances reset if they put in improper input and then put in proper input, but a user-friendly program would reset that tally for them, so we'll try to put that in too.

So your psuedo-code may look something like

Code: [Select]
while (true)
{
  try
  {
System.out.print("Enter a floating point number: ");
if (!in.hasNextDouble())
       {
throw new BadDataException("Input needs to be a floating point number! Try again.");
        }
        else
       {
         data.add(in.nextDouble());
       }
  }
  catch (BadDataException exception)
  {
  System.out.println("Bad data: " + exception.getMessage());
  try
          {
         System.out.print("Enter a floating point number: ");
         if (!in.hasNextDouble())
                 {
          throw new BadDataException("Input needs to be a floating point number! Try again.");
                 }
                 else
                 {
               data.add(in.nextDouble());
                 }
          }
          catch (BadDataException exception)
          {
                    System.out.println("Bad data: " + exception.getMessage());
                    in.close();
          }
  }
}

I don't think you need a while loop for the program to pause while waiting for input, scanner should do that on its own. Then you just need to keep using try/catch until the user gets it right or runs out of chances, and keep on looping until you get to the exit point (Which I didn't account for, shouldn't be hard to put in there though)

Let me know if I'm totally wrong here, I'm not a Java expert lol
Logged
ROLL TIDE WHAT? **** YOU!!! Geaux Tiga

~The Gaurdians of ZFGC~
Kirby, metallica48423, Max, Vash, walnut100
  • Gamers & Developers Unlimited
Re: Catching Exceptions?
« Reply #3 on: March 13, 2011, 08:38:03 pm »
  • *
  • Reputation: +9/-0
  • Offline Offline
  • Gender: Male
  • Posts: 3725
It has been a while since I used Java. Uhm, I don't know exactly, but I think the problem is that you throw the exception in the main. Usually a method that throws an exception has to be defined as such and main is not. And I do think that even though you use a try-catch block it does not catch exceptions that are generated within the scope of the block. It should have quit your main method, actually. You should read this for more on exceptions: http://download.oracle.com/javase/tutorial/essential/exceptions/index.html

What I would have done is create a class SumUp which has a member variable double sum and 3 functions addToSum(double), double getSum() and double getInput() throws BadDataException. Oh yes having a member variable for the input is also nice. Your main would then be something like this:

Code: [Select]
loop while not finished

    try
        get the next input.
        add the input to the sum.
    catch
        try
            get the next input.
            add the input to the sum.
        catch
            set finished
    
    print the total sum.
Logged
Re: Catching Exceptions?
« Reply #4 on: March 13, 2011, 10:55:44 pm »
  • Doesn't afraid of anything
  • *
  • Reputation: +42/-0
  • Offline Offline
  • Gender: Male
  • Posts: 7002
How about...you keep that arraylist you have...and keep that while (true) condition.  Keep your try and catch as is, but in the catch block, check to see what the value entered was.  If they enter, say a Q (for quit) then the program continues on and does the rest of the output.  If it's anything else, just increment a counter to keep track of how many times they entered bad data.

Quote
I don't think you need a while loop for the program to pause while waiting for input, scanner should do that on its own.
This!  You should only need 1 loop in this program for input!  The second loop should only do arithmetic!

Quote
Usually a method that throws an exception has to be defined as such and main is not.
Although you can do this in Java, it's not necessary.

If you need further clarification, say so and I'll write something up.
Logged



i love big weenies and i cannot lie
Re: Catching Exceptions?
« Reply #5 on: March 13, 2011, 11:37:07 pm »
  • *
  • Reputation: +2/-0
  • Offline Offline
  • Gender: Male
  • Posts: 1767
@ Xiphirx, wally: Unfortunately both of them had the same results, thanks though. =)
@ MG: Yeah I tried that earlier as well, again, same results.

However, Niek's method of creating the SumUp class did it though.
Quote from: Niek
Usually a method that throws an exception has to be defined as such and main is not. And I do think that even though you use a try-catch block it does not catch exceptions that are generated within the scope of the block. It should have quit your main method, actually.

Yep, looks like that was the issue. I did create a class earlier trying to follow this example in my book, for some reason that didn't work either.

Thanks for your help guys. =)
Logged
  • https://colbydude.com
Re: Catching Exceptions?
« Reply #6 on: March 14, 2011, 10:33:35 am »
  • *
  • Reputation: +0/-0
  • Offline Offline
  • Posts: 2245
Just going to add my 2c here. Judging by the code flow, the issue has nothing to do with your exceptions, you can tell that by the output your getting. Exceptions will always be caught if they are in a try catch block, regardless where in the code they are.  If I were to take a random shot in the dark I'd probably say it's because you close the scanner when you catch the first exception, which will also close the stream and thus any further attempts to read from that stream will automatically fail, and as you have it set up so it throws an exception when the next input is not a double, your exception will be thrown again and caught in your try catch block outputting that message.
Logged
Re: Catching Exceptions?
« Reply #7 on: March 17, 2011, 06:49:59 am »
  • *
  • Reputation: +0/-0
  • Offline Offline
  • Gender: Male
  • Posts: 1635
Slightly unrelated, why are you using your own exception class? Java already has a useful exception for this purpose: the InputMismatchException, which is thrown when you attempt to read in some kind of token that is not in your desired format.

http://download.oracle.com/javase/1.5.0/docs/api/java/util/InputMismatchException.html
Logged
Re: Catching Exceptions?
« Reply #8 on: March 17, 2011, 05:02:40 pm »
  • *
  • Reputation: +2/-0
  • Offline Offline
  • Gender: Male
  • Posts: 1767
Slightly unrelated, why are you using your own exception class? Java already has a useful exception for this purpose: the InputMismatchException, which is thrown when you attempt to read in some kind of token that is not in your desired format.

http://download.oracle.com/javase/1.5.0/docs/api/java/util/InputMismatchException.html

Our instructor wanted us to make up our own class, so I just made that one nice and simple. =P

@Windy: Yeah I figured as such, but I was getting even weirder problems before I actually added in the in.close(); and opened a new one. At that point I'm pretty sure it was just me being drained from school. I'm still getting used to Java as a whole so I'll make mistakes here an there, no big deal. All is well now though.
Logged
  • https://colbydude.com
Pages: [1]   Go Up

 


Contact Us | Legal | Advertise Here
2013 © ZFGC, All Rights Reserved



Page created in 0.058 seconds with 55 queries.

anything