• Post Reply Bookmark Topic Watch Topic
  • New Topic

Ask user for 3 integers and find out if they make a triangle or not.  RSS feed

 
Ranch Hand
Posts: 62
2
Java Mac Netbeans IDE
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there another way I can do this as my IF statement if giving me errors and I'm not sure why?

 
Bartender
Posts: 726
23
Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to CodeRanch!

  • You are getting compile time error because we need to initialized local variables before using them, they are not initialized to their respective default values like instance variables are.
  • Variables which are declared in a method or a block are called local variables of that method or block.
  • In your program you haven't initialized int a and b.
  • Below line initialized only c to 0 but not a and b.

  • Edit: Why It is asking you to initialize local variables int a and b because your If statement is outside of try block so when an error occurs in try block while taking input from user to assign values to these local variables then catch block will be executed so local variables int a and b will never be initialized and trying to use them before initializing in If statement is invalid so gives you CE.
  • Don't write that much code in main method creates confusion and also hard to find logical errors, so better create a separate method you can name it verifyTriangle() or anything you feel more expressive.
  • Worth Reading click on -->  Main Is A Pain
  • It is good practice if you separate these expressions using circular braces for easy understanding and better enclose code of If statement using curly braces although it has only one line of code. Like below code
  • From next time please alway post your code using code tag, to post code use code tag from above menus. Just enclose your code with code tag which will appear like below example. Use preview before sumbitting.
  • Example of code posted using code tag:
  • If you get error then always post the complete error you are getting ( but out side of code tag ), only enclose code in code tag.
  •  
    Bartender
    Posts: 2087
    44
    Firefox Browser IntelliJ IDE Java Linux Spring
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Welcome to the Ranch!

    First, you need to separate the logic of getting user input from the logic of validationg a triangle.
    Second, always use curly braces {} with ifs.

    Third, You don't initialize your variables. It could be possible to arrive at line 24 without giving them values (for example if UserInput.nextInt() threw an exception).
    You must always initialize local variables before using them.
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Just to verify that compiler knows that if error occurs in try block while taking input from user to assign values to a and b then a and b will never be initialized before using in If statement which is invalid or we can say against the Java rules.

    do one thing, in this same code just assign values to a and b in catch block which satisfies compiler's conditions, now compiler knows let user enter valid input or invalid which may raise exception, my a and b local variables will definitely be assigned with some numeric values so gives you green signal you can go ahead means No compile time error.    This proves, we always need to initialize local variables before using it.

    What is the solution to make compiler happy?
  • You can write two separate methods, one for input and other to validate triangle as Paweł already mentioned.
  • Declare these variables in class as private int and if valid input entered then invoke triangle validating method which will return boolean value true if it is valid else false. You can name that method like isValidTriangle etc.
  •  
    Marshal
    Posts: 56600
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ganesh Patekar wrote:. . . What is the solution to make compiler happy?   . . .
    There used to be a user here with a signature saying something like this:-
    Ain't the compiler not happy, ain't nobody happy.
    But we are not trying simply to keep the compiler happy, we are trying to write good code. Fortunately the suggestions everybody has made will help no end. I shall make another suggestion:-
    Divide and Conquer. Get the entry of three numbers working and don't do anything with them yet. When your three numbers method works, you can then decide on the next stage of the project. Trying the whole thing all at once is very likely to fail. Doing the task in small pieces is much more likely to succeed.

    And ... again ... welcome to the Ranch
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:But we are not trying simply to keep the compiler happy, we are trying to write good code.
    Yes completely agreed because by assigning values to a and b in catch block makes greedy compiler happy   ( Means compiles successfully) but that is logically incorrect, we won't get what we are expecting from this program.
    Yes working on small pieces of code is more beneficial than whole thing at once. Points jotted down.
     
    Bod MacNeil
    Ranch Hand
    Posts: 62
    2
    Java Mac Netbeans IDE
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thank you all for your responses and welcomes!  I have re'written my code and I think I used all the points you have mentioned.  Here is the updated version?  Is there anything I've missed out or can improve on again?  thanks.

    main (which I think you'll agree looks a lot cleaner)



    triangle class for everything else.

     
    Sheriff
    Posts: 4289
    127
    Chrome Eclipse IDE Java Postgres Database VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
  • Class names should start with an uppercase letter.
  • What is the variable "a" doing here?

  •  
    Bod MacNeil
    Ranch Hand
    Posts: 62
    2
    Java Mac Netbeans IDE
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    the 'a' is supposed to be an 'f' :s  changed.  and I'll need to keep the class name thing, in mind thanks.
     
    Knute Snortum
    Sheriff
    Posts: 4289
    127
    Chrome Eclipse IDE Java Postgres Database VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    It is best to declare variables as close to when they are used as possible.  Currently, a, b, and c are declared outside of any method, so they are visible in all methods.  This is considered a poor practice when it is not needed.  Declare the variables as you initialize them.
     
    Knute Snortum
    Sheriff
    Posts: 4289
    127
    Chrome Eclipse IDE Java Postgres Database VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Challenge: write a method that gets user input, tests to see whether it's an integer, and loops until it gets good input.
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
  • I think everyone would like to see variables named sideOne, sideTwo etc rather than a, b and c which explains nothing what it is for.
  • Code will look more readable If you write a separate method like getUserInput() or anything you feel more expressive to take input from user rather putting that code in constructor as Knute already mentioned.
  • You can declare MyFirst as final class and also create a non-argument constructor of MyFirst with private access modifier so accidently you or anyone will never be able to create an object of MyFirst outside of that class.
  • First just emphasize on taking valid input from user then go for triangle validation as Campbell said, would be much easier to solve this and your are already on path.
  • Knute Snortum wrote:It is best to declare variables as close to when they are used as possible.  Currently, a, b, and c are declared outside of any method, so they are visible in all methods.

  • IMO, 3 sides of a triangle is the property of a triangle so when we store them in variables, I think it suppose to be in class. Yes it is good if it is accessible to other methods of an object of triangle class. I agree outside of class these variable should not be accessible without getter and setter methods.
  • Passing those values from input method as parameter to a method which validates triangle seems not a good way. Please correct me If I'm wrong because now a days this kind of questions are haunting me like which variables should be declared in class and which in method.
  • Suppose there is a class Person which has String name; int age; etc etc. This class has methods which take input from user and one of them just prints information of that person. So in this case what do you think we are suppose to declare name and age variables in class or in input method as local variables and pass them to print method?
  •  
    Bod MacNeil
    Ranch Hand
    Posts: 62
    2
    Java Mac Netbeans IDE
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ok guys I've tried to add all of the things mentioned, except my variables are still at the top of the class.   I've split things up in to different methods.  Is the message() method ok?  or pointless? 

    I've added a new method which uses the Pythagoras theorem to check if the triangle is a right triangle but it always returns false, when it should return true.  I've no idea what the problem is?

     
    Bod MacNeil
    Ranch Hand
    Posts: 62
    2
    Java Mac Netbeans IDE
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I've fixed a section of it.  I wasn't comparing them to the square root of the biggest number;

    //fixed


    still return false when I put 3,4,5 in, which should return true.
     
    Sheriff
    Posts: 22846
    43
    Eclipse IDE Firefox Browser MySQL Database
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    You aren't applying Pythagoras correctly. Remember? "The square of the hypotenuse is equal to..."
     
    Bod MacNeil
    Ranch Hand
    Posts: 62
    2
    Java Mac Netbeans IDE
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ok I just did and got the answer "-1.968118785068667" printed out to my screen.  What does this mean?
     
    Bod MacNeil
    Ranch Hand
    Posts: 62
    2
    Java Mac Netbeans IDE
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I thought the square of the hypotenuse was equal to the sum of the other 2 sides squared?
     
    Bod MacNeil
    Ranch Hand
    Posts: 62
    2
    Java Mac Netbeans IDE
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I've just realised that I'm getting the square root of them and not squaring them!!! problem fixed;



    How is the layout of my code?  Is there anything else I should change?

    cheers;
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Yes your going well   only few changes IMO
  • class name always starts with capital letter so Triangle rather than triangle look good.
  • I don't feel you need to create separate message method just to print message, you can move that code in getUserInput method.
  • Instance variables sideA, sideB and sideC are declared in class so they are accessible to all instance methods of this class, you don't need to pass variables to validateTri method like this
  • You can use them directly by thier name in validateTri and PyTheory methods like below.

  • So you can remove parameters of those two methods and can invoke method without any arguments like this

  • Suppose user entered value for sideA = 10 then in below code you are again assigning sideA = 10 ( value passed int side1 as parameter to PyTheory method ) where sideA already had value 10 assigned to it in getUserInput method so no need to reassign same value again.
  • Would be much readable If you put circular brackets around each condition in If statements.
  • I'm afraid you haven't considered the situation when user enters wrong input like string rather than int number, you better work on Campbell's suggetion and Knute's challenge

  •  
    Bod MacNeil
    Ranch Hand
    Posts: 62
    2
    Java Mac Netbeans IDE
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ganesh Patekar wrote:Yes your going well   only few changes IMO
  • class name always starts with capital letter so Triangle rather than triangle look good.
  • I don't feel you need to create separate message method just to print message, you can move that code in getUserInput method.
  • Instance variables sideA, sideB and sideC are declared in class so they are accessible to all instance methods of this class, you don't need to pass variables to validateTri method like this
  • You can use them directly by thier name in validateTri and PyTheory methods like below.

  • So you can remove parameters of those two methods and can invoke method without any arguments like this

  • Suppose user entered value for sideA = 10 then in below code you are again assigning sideA = 10 ( value passed int side1 as parameter to PyTheory method ) where sideA already had value 10 assigned to it in getUserInput method so no need to reassign same value again.
  • Would be much readable If you put circular brackets around each condition in If statements.
  • I'm afraid you haven't considered the situation when user enters wrong input like string rather than int number, you better work on Campbell's suggetion and Knute's challenge



  • I will get there   I've fixed the minor issues, but now I'm going to work on Knutes challenge so I can add it to my own code! thanks
     
    Bod MacNeil
    Ranch Hand
    Posts: 62
    2
    Java Mac Netbeans IDE
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    ok here is my first attempt at Knutes challenge.  Everything seems to work ok. I wasn't sure weather to make my variable available to the whole class or just the methods.

     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    You seem going well but remember you are suppose to take valid integer input from user for three int variables. Here you can have value for only one int variable.How will you take values for rest two variables?
    But IMO It is not good way to throw exception to let user know that he/she entered invalid value. You can read hasNextInt() and other methods of Scanner which will help you. I have also never tried for this, I will also try that.    
     
    Campbell Ritchie
    Marshal
    Posts: 56600
    172
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Best way to use hasNextInt, which Rob Spoor taught me about a long time ago:-
  • 1: Create a utility class, maybe called KeyboardInputs
  • 2: Give that class a private constructor because you never need any instances of it. See the Java® Language Specification (=JLS).
  • 3: All members of a utility class are static; that is why you don't need any instances.
  • 4: The hasNextInt call goes in a loop. Example method follows.
  • You can add methods to that class and use it for all your keyboard input. If you use the package name, you can write
    import static resources.KeyboardInputs.nextInt;
    before the name of your class and simply write
    int i = nextInt("Enter number of programmers: ");
    Otherwise you can write
    int i = KeyboardInputs.nextInt("Enter number of programmers: ");
    \u2019 is a posh apostrophe like this: ’

    [edit]Additionl. I shall let you work out why you need to ignore the “next” in line 24. I mentioned ignoring a returned value the other day here.
    Note there is no code to close inScan. Never close a Scanner, reader or similar pointing to System.in. Nor Formatters, writers, etc, pointing to System.out or System.err.
     
    Bartender
    Posts: 572
    9
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    The algorithm for determining whether three numbers can represent the lengths of the three sides of a triangle is quite simple, and does not require any squares or roots. It is simply that the sum of the smallest two numbers must be greater than the largest number. Or if you don't want to find the largest number, you can test
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    This is what I tried, please any suggestions? because of long messages may not view properly, please hide categories.
    KeyboardInputUtilty.java
    KeyboardInputUtilityDemo.java
    Ouput:
    Enter value of name
    Ganesh Patek3ar
    Invalid String value, digits are not allowed!
    Enter value of name
    Ganesh Patekar
    Enter value of age
    30.7
    Entered invalid value of age, only integer are allowed!
    Enter value of age
    2q9
    Entered invalid value of age, only integer are allowed!
    Enter value of age
    29
    My name is: Ganesh Patekar
    My age is: 29
     
    Knute Snortum
    Sheriff
    Posts: 4289
    127
    Chrome Eclipse IDE Java Postgres Database VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Looks good!  I have two minor notes:
  • If a variable is static and final, I'd call it READER rather than reader.
  • I'd shorten the two lines in main() to this:

  •  
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Knute Snortum wrote:If a variable is static and final, I'd call it READER rather than reader.
    Oh yes yes, I always name final static in this way but missed. Thank you for noticing.  
     
    Campbell Ritchie
    Marshal
    Posts: 56600
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    The usual convention is to put static before final, but that is a minor style thing.
    If you ask for the input inside the loop, you may get a very verbose output on screen. But that is only a minor point.
    I would have thought that you could shorten the method names, e.g. getInt or nextInt. Using nextInt has the slight advantage that it will match the methods in Scanner.
    I would suggest that you can overload your getXXX methods to permit ranges, then you can have error messages like, “Value must be between 1 and 100”.
    You can pass a regular expression to a getString method and use that regex to validate the String. But such validation is an advanced topic.
    Why are you getting floats? I would recommend you avoid floats as much as possible. Use BigDecimal instead (or double if you have to have a floating‑point number).
    Is reader really a constant? Does it really merit CAPITAL_LETTERS?
     
    Campbell Ritchie
    Marshal
    Posts: 56600
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Now try getting the next line without returning the empty String. That is more difficult with Scanner.
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:I would suggest that you can overload your getXXX methods to permit ranges, then you can have error messages like, “Value must be between 1 and 100”. 

    Suppose I rename method's long name to getInt for int value so becomes public int getInt(String msg); and I'll overload that method by writing another method
    public void getInt(String msg, int fromValue, int toValue ); which will only print appropriate message like, “Value of age must be between 1 and 100”. Is this what you were saying? Or should that method also return boolean value, true for valid range and false for invalid so further I can use that in KeyboardInputUtilityDemo class?
     
    Fred Kleinschmidt
    Bartender
    Posts: 572
    9
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    If you name a method getInt(...), it should return an int.
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Fred Kleinschmidt wrote:If you name a method getInt(...), it should return an int.
    Oh yes yes, I think I better name It, isInRange something like that.
     
    Campbell Ritchie
    Marshal
    Posts: 56600
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ganesh Patekar wrote:. . . overload that method by writing another method
    public void getInt(String msg, int fromValue, int toValue ); which will only print appropriate message like, “Value of age must be between 1 and 100”. Is this what you were saying? . . .
    That method will return an int betwen 0 and 100 (I think that is what I suggested originally) and will only print the error message for a valid int but an invalid value (e.g. -1, 1000). That method may need to throw an Exception; I shall leave you to work out when it shou‍ld throw the Exception.
     
    Campbell Ritchie
    Marshal
    Posts: 56600
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    A few minutes ago, I wrote:. . .  print the error message for a valid int but an invalid value (e.g. -1, 1000). . . .
    I wasn't clear.
    That means the out‑of‑range error message. You will print the not‑an‑int error message for not a valid int.
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    @ Campbell  I hope this is what you meant
     
    Campbell Ritchie
    Marshal
    Posts: 56600
    172
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ganesh Patekar wrote:@ Campbell  I hope this is what you meant
    No. The idea of the loop is that it never throws an InputMismatchException. You take the ordinary method, which returns an int, and wrap it in something. I shall give you a hint:-What is going to happen in the latter case? How are you going to get out of it?
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:What is going to happen in the latter case? How are you going to get out of it?
    Opps!

    Ohh yes I've seen methods in source codes are also written in this fashion.
    Now?
    This is how I invoke It from other class
     
    Paweł Baczyński
    Bartender
    Posts: 2087
    44
    Firefox Browser IntelliJ IDE Java Linux Spring
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Don't return magic numbers like that.

    What if the method call was: and the user typed -1?
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Paweł Baczyński wrote:Don't return magic numbers like that.

    What if the method call was: and the user typed -1?
    Oh yes your right,
    I removed return, code of public static int getInt(String message) would be same as writtend in previous post.

    Yes It prints appropriate message If input value is invalid but what I want to do is If user passes invalid range then It should print message saying invalid range which It does and should not proceed to take input from user which I can do by adding remaining code in else part of if(min>max) but problem is what value to return If invalid range occurs Or value is not in given valid range ? because returned value is being assigned to age variable.
     
    Paweł Baczyński
    Bartender
    Posts: 2087
    44
    Firefox Browser IntelliJ IDE Java Linux Spring
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I think in case of invalid range you should throw IllegalArgumentException as this is a programmer's mistake, not user's mistake.

    If you want to return a value that may or may not exist, consider using OptionalInt.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!