Problem with a Try/catch exception

Hello everyone here on the forums. I'm brand new to Java and have a bit of a problem with a try catch statement I'm making. In the following code if a user enters a non-integer number the program will display "Sorry, incompatible data." Problem is it gets caught in a loop and continues to display "Sorry, incompatible data." My aim with the try catch was if the user is not quite smart enough to understand quadratic programs don't use symbols and characters it would state it isn't correct and continue running the program.
Heres my code thus far:
package finishedquadraticprogram;
import java.util.*;
* @author Matt
public class quad {
     * @param args the command line arguments
    public static void main(String[] args) {
        boolean verification = true;
        double a, b, c, root1, root2, discriminant;
        Scanner keyInput = new Scanner(System.in);
        while ( verification)
        try
        System.out.println("a: ");
        a = keyInput.nextDouble();
        System.out.println("b: ");
        b = keyInput.nextDouble();
        System.out.println("c: ");
        c = keyInput.nextDouble();
        discriminant = Math.sqrt(b * b - 4 * a * c);
        root1 = (-b + discriminant) / 2 * a;
        root2 = (-b - discriminant) / 2 * a;
        verification = false;
        System.out.println("Root 1 = " +root1+ "\nRoot 2 = " +root2);
        } //try
        catch  (InputMismatchException iMe)
          System.out.println( "Sorry. incompatible data." );  
}I'm pretty sure the problem is something to do with the keyboard buffer, but I'm not sure what I need to do to either reset it or clear it, whichever one works. (Oh, and how would I go about making the program use complex numbers? I realize Java can't use complex numbers and will just display NaN ... any ideas how to make this work?)
Thanks a lot for all of your help guys, it's appreciated.

this is better:
package finishedquadraticprogram;
import java.util.*;
/** @author Matt */
public class quad
   private static final double TOLERANCE = 1.0e-9;
   /** @param args the command line arguments */
   public static void main(String[] args)
      boolean verification = true;
      double a, b, c, root1, root2, discriminant;
      Scanner keyInput = new Scanner(System.in);
      while (verification)
         try
            System.out.println("a: ");
            a = keyInput.nextDouble();
            System.out.println("b: ");
            b = keyInput.nextDouble();
            System.out.println("c: ");
            c = keyInput.nextDouble();
            discriminant = Math.sqrt(b * b - 4 * a * c);
            if (Math.abs(a) < TOLERANCE)
               root1 = 0.0;
               root2 = -c/b;
            else
               root1 = (-b + discriminant) / (2 * a);
               root2 = (-b - discriminant) / (2 * a);
            verification = false;
            System.out.println("Root 1 = " + root1 + "\nRoot 2 = " + root2);
         } //try
         catch (InputMismatchException iMe)
            System.out.println("Sorry. incompatible data.");
            keyInput.next();
}

Similar Messages

  • Try catch exception handling

    Hi there,
    Was wondering if you could assist in me getting my head around try catch exception handling? I have this code:
    JOptionPane.showMessageDialog(null, "A subject consists of term names and definitions.\nYou should indicate the size and name of the subject");
             inputSubName = JOptionPane.showInputDialog(null, "Enter the Subject Name:");
             inputSubSize = JOptionPane.showInputDialog(null, "Enter the Subject's Term Size:");
             try {
                  size = Integer.parseInt(inputSubSize);
                  catch (NumberFormatException e) {
                            JOptionPane.showMessageDialog(null, "'" + inputSubSize + " is invalid " + " Please enter digits only");
                            inputSubSize = JOptionPane.showInputDialog(null, "Enter the Subject's Term Size:");
                            size = Integer.parseInt(inputSubSize);
             //create a new Subject object and pass in its name and size
             Subject sub = new Subject(inputSubName, size);
    ...My query is, if I catch an exception, how do I get the code to repeat the try again until the user inputs a correct data type? If the user above inputs something other than a number, it will catch it once and repeat the joptionpane inputbox, but if they do the same thing twice round - then the program bombs out. Is there a way i can get the code to retry the try until they input correctly?
    Cheers.

    eg.
    int size = 0;          
    while (true) {
         try {
              size = Integer.parseInt(inputSubSize);
              break;
         catch (NumberFormatException e) {
              JOptionPane.showMessageDialog(null, "'" + inputSubSize
                        + " is invalid " + " Please enter digits only");
              inputSubSize = JOptionPane.showInputDialog(null,
                        "Enter the Subject's Term Size:");
    }

  • "catch is unreachable" compiler error with java try/catch statement

    I'm receiving a compiler error, "catch is unreachable", with the following code. I'm calling a method, SendMail(), which can throw two possible exceptions. I thought that the catch statements executed in order, and the first one that is caught will execute? Is their a change with J2SE 1.5 compiler? I don't want to use a generic Exception, because I want to handle the specific exceptions. Any suggestions how to fix? Thanks
    try {
    SendMail(....);
    } catch (MessagingException e1) {
    logger.fine(e1.toString());
    } catch (AddressException e2) {
    logger.fine(e2.toString());
    public String SendMail(....) throws AddressException,
    MessagingException {....                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I found the problem:
    "A catch block handles exceptions that match its exception type (parameter) and exception types that are subclasses of its exception type (parameter). Only the first catch block that handles a particular exception type will execute, so the most specific exception type should come first. You may get a catch is unreachable syntax error if your catch blocks do not follow this order."
    If I switch the order of the catch exceptions the compiler error goes away.
    thanks

  • Doubt on try/catch exception object

    why it is not advisable to catch type exception in try catch block. Its confusing me. If i catch exception object then it will show whatever exception occured.
    btw, i was just go through duke stars how it works and saw this
    http://developers.sun.com/forums/top_10.jsp
    Congrats!

    Because there are many different kinds of Exception. If you have some specific local strategy for dealing with a particular excepion then you should be using a specific catch block.
    If you don't then you should allow the expection to end the program, and ideally you should deal with all the expceptions in one top-level handler, so you should throw, rather than catch the exceptions in your methods. Often at the outer most level of the program or thread you will actually catch Throwable (not just Exception) to deal with any unanticipated problems in a general kind of way.
    Also, you should be keeping track of what exceptions might be thrown, so that rather than using Exception in a throws clause or catch block, you should use the particular exceptions. Exceptions, generally, indicate a recoverable error that you really ought to be recovering from rather than just printing a stacktrace.
    That's why exceptions are treated differently from runtime errors.

  • Does Labview have Try Catch exception handling?

    1) Does Labview have Try Catch functions, exception handling?
    2) Can Labview access a file or download a file using http or https?
    3) How can labview  read data from an ex ternal server http or https?
    This is in labview 2009 or 2011

    Hi E,
             1. you can chain together your VIs with the error wires, such that if an error occurs in one of them, none of the following VIs will execute.  That's  like throwing an exception - it interrupts the execution chain.  You then "catch" that exception by putting an error handler wherever necessary, but not necessarily in every single VI.Hope  You wouldn't put try..catch inside every single .NET function, instead you handle the exception at the level at which is most appropriate. Same thing can be done in LabVIEW.
    Also see this.
    2. The attached example downloads a picture with http "GET" command.
        Dilbert.Main_LV71.vi 160 KB
    3.see this thread:
       http://forums.ni.com/t5/LabVIEW/Read-a-text-file-from-Labview-web-server-http/td-p/267434
    Yes!!The same thing pointed out by nijims.
    Thanks as kudos only

  • Help with reducing try catch blocks

    Hi,
    I have an object of a class having about 100 get methods. I have about 300 such objects. I want to get all the parameters from all the 100 get methods for all the objects, and for each failed get methods, an exception occurs,
    Now I can loop from - to no of objects but inside I have to declare 100 try catch methods for each get methods.
    for(i=0;i< 300;i++) {
    try {
       a.getname;
    catch { --- }
    try{
    a[i].getno ;
    catch { -- }
    100 such a[i].getXYZ methods
    any alternative. wanted to avoid all the try catch statements
    Please suggest
    thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    tarkesh wrote:
    Its actually a serialized object, which I am trying to extract parameters from. So I actually need to know exactly which get method is failing for which object, as the objects can be in error when they get transported over the network.If it was me I would generate the code so the actual mechanism becomes moot.
    But you can use something like the following (generated or not.)
           String attrName="<Unknown>"
           try
                 attrName = "attr1";
                 attr1=instance.attr1;
                 attrName = "attr2";
                 attr2 = instance.attr2;
           catch(Exception e)
                 // attrName has correct name here.
           }

  • Try catch exceptions

    I got this:public void fileIO() {
            try {
                File file = new File("aNewFile.txt");
                System.out.println(file.exists());
            } catch (IOException ioe) {
                System.out.println("IOException");
        }which tells me : exception java.io.IOException is never thrown in body of corresponding try statement, if I change the catch to } catch (Exception ioe) {, the error goes away.
    My question is why is it giving the error and why is it not giving the error after changing the catch line ?

    Read the API!!!!!!!!!
    new File(String) may through a NullPointerException
    and
    file.exists() may through a SecurityException
    Neither of those are based on an IOException, hence the error message when you use IOException.
    All exceptions are based (somewhere down the line) on Exception, hence no error when you use Exception.

  • How to check a lot of conversion errors with one TRY-CATCH?

    Hi,
    I've to import a lot of data from a flatfile.
    To avoid short dumps when there are non-numeric data's for a numeric field in the file, I load every record in a structure that have only CHAR fields.
    Then I move this fields in a TRY-Catch block to the real fields like this:
    TRY.
        field1 = field_from_file1
        field2 = field_from_file2
        field3 = field_from_file3
    CATCH cx_sy_conversion_no_number INTO lr_exception.
        PERFORM fehler USING lr_exception.
    ENDTRY.
    This construct works until the first field has a conversion error. However I will test all fields to get a complete list of the errors. And I am to lazy to make a TRY-CATCH construct for hundred of move-statements.
    Is there a better trick to check the success of <b>all</b> move operation?
    Regards,
    Stefan

    Hi Stefan,
    sorry, the development system is down right now, so I could not test. But I'm convinced you can figure it out:
    You may specify the parameters of a method as TYPE REF TO DATA.
    Then, in the calling routine you may have
    data:
      anyrefsource type ref to data,
      anyreftarget type ref to data.
    GET REFERENCE OF p_source INTO anyrefsource.
    GET REFERENCE OF p_target INTO anyreftarget.
    call method try_conv
      exporting
        source = anyrefsource
        target = anyreftarget.
    and in the method:
    ASSIGN source->* TO <fs_source>
    and so on...
    BTW: I know you have to use typed parameters in OO. Can't you use "TYPE ANY"?
    regards,
    C.

  • Problem with RFC adapter (JCO Exception RFC logon failure)

    Hi ,
    I have SOAP to RFC scenario.
    Scenario with same configuration (RFC adapter) is working in QA system.but when I have transported to PRODUCTION system
    it is showing
    com.sap.aii.af.ra.ms.api.DeliveryException: RfcAdapter: receiver channel has static errors: can not instantiate RfcPool caused by: com.sap.aii.af.rfc.RfcAdapterException: error initializing RfcClientPool:com.sap.aii.af.rfc.core.repository.RfcRepositoryException: can not connect to destination system due to: com.sap.mw.jco.JCO$Exception: (103) RFC_ERROR_LOGON_FAILURE:
    I have gievn max conn=10 ;Refresh the cache also
    and checked Roles and authorization also but still I am getting the same error.
    Regards

    Hi ,
    I have created all the objects manually. and it is working.
    now it is showing other error when I am sending the messages from SOAP side it is showing
    MAPPING">NO_MAPPINGPROGRAM_FOUND</SAP:Code>
      <SAP:P1>Object ID DF2C6D6E40E935CB970DEE3A71049BF9 Software Component C3D5E1D1C75311DDB94DE33C0A1E01B6</SAP:P1>
      <SAP:P2 />
      <SAP:P3 />
      <SAP:P4 />
      <SAP:AdditionalText />
      <SAP:ApplicationFaultMessage namespace="" />
      <SAP:Stack>Interface mapping Object ID DF2C6D6E40E935CB970DEE3A71049BF9 Software Component C3D5E1D1C75311DDB94DE33C0A1E01B6 does not exist in runtime cache</SAP:Stack>
    for this I checked the Interface determination step and receiver determination ,mapping program all looks correct.
    I have refershed cache also both Complete and SLD.
    but nothing is wroking
    Please advice.
    Regards

  • Will not let me setup email account. says problem with email try again later

    Icloud will not let me setup email @iclould.com. Say has a problem try again later?

    Here's the iPhone email setup assistant:
    iPhone Email Setup

  • Exception handling with try/catch in acrobat

    Hi
    I have a problem using a try/catch block in my acrobat document-script. Try to enter the following into the debugger-console:
    try{nonexistentFunction();}catch(e){console.println('\nacrobat can't catch')}
    and run it. The output will be:
    nonexistentFunction is not defined
    1:Console:Exec
    acrobat can't catch
    true
    The whole point of a rty/catch block is for the application  NOT to throw an exception, but instead execute the catch-part of the  statement. However, acrobat does both: It throws an exception AND  executes the catch-block.
    Is there another way to suppress the exception, or to make the try/catch-block work as it's supposed to?

    > Also Adobe provides for free the JS or compiled file for Acrobat Reader to support the JS console.
    Where is that file located ? How to install it or where to place it ?
    What is the method referred by try67 on his site where he sells a product ?
    Is that the same as the compiled file you refer to ? or did he sell his solution to adobe ?
    It is helpful if people can get an idea of the nature of choices available and make informed decisions, than a cloak and dagger approach.
    For some jobs that we have, I have been very frustrated by a consultant who wont even give basic info for transparent billing despite all assurances for privacy, as a result we are forced to do the job ourselves.
    Dying Vet

  • Try/Catch Unknown Host Exception

    I need to validate for an error of Unknown Host Exception, in case someone tries connected to a server that doesn't exist, or types the wrong host name, so i can display a message. how do I do that, with a try catch block.
    I thought i would do:
    try{
          my code here such as...
          DatagramSocket socket = new DatagramSocket();
          // send request
          InetAddress address = InetAddress.getByName(args[0]);
          DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
          socket.send(packet);
        ...and so on, more code...
           socket.close();
    } catch (IOException e) {
           e.printStackTrace();
           System.out.println("Unknown host " + args[0]);
    }

    thanks, i also had to take out the e.printStackTrace(); and replace that with
    my error message and System.exit(0); and I got what i needed!

  • OutOfMemory Exceptions on Servlets, Try-Catch unable to help

    Hi, I'm playing with Java servlets right now and I seem to be getting some OutOfMemory errors. The weird thing is that even though I had identify the souce of error and tried to enclose it with a try-catch, the exception still occurs. Why is that so?

    OutOfMemoryError is actually a java.lang.Error, not a RuntimeException. So if you use a try/catch like this
    try {
      // stuff
    } catch (Exception e) {..}Errors will fall through, since Error is not a subtype of Exception. (Check the API.)
    You can catch it by catching Error or Throwable, like this:
    try {
      // stuff
    } catch (Error e) { //  this is rarely a good idea
    }But you normally wouldn't want to do this. When there's no memory left, there's not a whole lot you can do about it, and most of the code you might want to put inside the catch block will merely throw another OutOfMemoryError.
    As voronetskyy said, you're either creating too many (or too large) objects (typically in an endless loop), or you have specified too little memory for your application.

  • Problem with exceptions

    hello all.
    plz take a look at this code
    try {
    } catch (Exception e1) {
    System.out.println("execption 1");
    try {
    } catch (Exception e2) {
    System.out.println("execption 2");
    what i want to do is if i have an execption in the first try, i dont want to execute the second one, like an if else block, and i dont want to use an GOTO ...
    and i dont know how to do it.
    can someone help me out plzzz.

    Lazy OP.
    try{
        try{
            methodOne();
        catch(Exception x){
            handlingOne();
            throw x;
        try{
            methodTwo();
        catch(Exception x){
            handlingTwo();
            throw x;
    catch(Exception x){
        beesAndFlowers();
    OR:
    boolean onedone = false;
    try{
        methodOne();
        onedone = true;
        methodTwo();
    catch(Exception x){
        if( onedone ) handlingTwo(); else handlingOne();
    OR:
    boolean oneok = true;
    try{ methodOne() } catch(Exception x){ oneok = false; handlingOne(); }
    if( oneok ){
        try{ methodTwo() } catch(Exception x) { handlingTwo() }
    ET CAETERA.

  • Catch exception, but continue try{ ?

    I have a http timeout error that is handled by a printing of the stack trace, but how do I continue it so the while loop still continues?
    try {
    while(rs.next()) {
    httpConection.setConnectTimeout(15000);
    httpConnection.connect();
        }//end while loop
          con.close();
         catch(Exception e)
         continue; // <--- Won't let me do this, since it is not in a loop
         }//end catch
        thanks in advance

            public static void main(String[] args) {
         try {
          Statement stmt;
          ResultSet rs;
          Class.forName("com.mysql.jdbc.Driver");
          System.out.println("URL: " + url);
          System.out.println("Connection: " + con);
          stmt = con.createStatement();
          stmt = con.createStatement(
                   ResultSet.TYPE_SCROLL_INSENSITIVE,
                         ResultSet.CONCUR_READ_ONLY);
          while(rs.next()){
            int theInt= rs.getInt("id");
            String URLs = rs.getString("url");
            String urlString = URLs;
                  URL httpurl = new URL(urlString);
                URLConnection connection =
                httpurl.openConnection();
                if (connection instanceof HttpURLConnection) {
                    HttpURLConnection httpConnection =
                     (HttpURLConnection)connection;
                     httpConnection.setConnectTimeout(15000);
                     httpConnection.connect();
                  } // End IF
                 // Continue
          // End If(connection instanceof)...
          } // End While
          con.close();
         } // End TRY
        catch(Exception e) { }
            }Thats how I have the exception now.. If i try anything else it says need catch or finally for try?

Maybe you are looking for

  • Helix: Update to Win 8.1 fails

    Hello, I tried to update my Helix to Win 8.1 for several times now. Each time the update fails. The download-process and the installation starts normally. The Helix is also booting sometimes and installing drivers. But then the process fails and I ca

  • Toshiba Satellite C40D-A HD recovery solution to lost password after upgrade to win 8.1?

    Hi, Part No.: PSCDSL-009001 After I bought this laptop in Manila, I initiated it with ONE local account, and NO password, and created a USB recovery stick. There are no privacy-critical data on it, so I'm perfectly happy using it without password. It

  • SAP Delivered forms for an offline scenario?

    Hi, Is there any SAP Standard/delivered forms for an offline scenario? How many number of SAP standard forms are available? Where to look at this information? Thanks Sundar

  • Lightroom RAW files from time machine won't move

    Hey guys and girls, hoping someone can help me out with this brain burner. My macbook crashed! luckily i have a backup of all my stuff on time machine. Using a new mac i have imported and opened the previous category and easily accessed the majority

  • Error while executing BAPI_USER_CREATE1 in SOAPUI

    I am using BAPI_USER_CREATE1 for adding new user. This BAPI is working fine when I am executing it in se37. But when i am  exposing this BAPI as webservice and consuming the WSDL in SOAPUI. Any try to execute the BAPI from SOAPUI. it is returning me