• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Print Selected Array Element - Test Program

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm putting together a beginner exercise. I have an array, which has a list of paragraphs. Based on inputed arguments (a number), I want to show the paragraph number. Below is the code. There is no error in NetBeans when I view the code, but I do get the following message when the program is run:



I have notes below on what I am trying to do with each step. I'm looking for how to make the program work (and what I did wrong, so I can avoid it in the future), and also looking to find out how to streamline my code a bit, and get rid of any unnecessary steps.



 
Bartender
Posts: 1251
87
Hibernate jQuery Spring MySQL Database Tomcat Server Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Dj Galla wrote:There is no error in NetBeans when I view the code, but I do get the following message when the program is run:  

because you are suppose to run this program using command line then only you will get the value of ParaStrNum I ran your program successfully.
 
Dj Galla
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ganesh Patekar wrote:

Dj Galla wrote:There is no error in NetBeans when I view the code, but I do get the following message when the program is run:  

because you are suppose to run this program using command line then only you will get the value of ParaStrNum I ran your program successfully.



Ok. Got it. Any suggestions on how to clean up the code? Or does everything look good?
 
Dj Galla
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ganesh Patekar wrote:

Dj Galla wrote:There is no error in NetBeans when I view the code, but I do get the following message when the program is run:  

because you are suppose to run this program using command line then only you will get the value of ParaStrNum I ran your program successfully.



Also, when I enter a text string for my initial arguements (like "test text"), I get an error. So, my error checking isn't working...
 
Ganesh Patekar
Bartender
Posts: 1251
87
Hibernate jQuery Spring MySQL Database Tomcat Server Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
  • Rather than writing that much code in main, I would prefer to make a separate method the way you made isNumeric(String str)
  • Here you are converting String into int but what that String contains special symbols or String value rather than number? that time this conversion fails and gives NumberFormatException

  • Not good practice to use == or != with boolean, here
  • better do like this

  • isNumeric(String str) method should be called before converting String values of ParaStrNum = args[0]; into int. If it is numeric then convert that String value to int.
  •  
    Marshal
    Posts: 79177
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    There is another way to verify that a String is numeric, which you will find discussed in great detail in this recent thread. Beware: that technique will recognise 1,000,000 and -123 as valid numbers (using British or English‑speaking North American locales):-What you are doing first is checking that there is a command‑line argument at all with args.length, otherwise you get an array index ouf of bounds exception. Then you create a new Scanner object to deal with that argument and convert it to an int. The use of the short‑circuit operator && (don't use &) ensures the Scanner object is only created when the argument is available to it. Did you know you can create a Scanner to deal with a String object? If that String argument isn't a valid int, you never call the nextInt method, but print the error message. Note the format of that error message as a useful way to warn the user of incorrect use of the command line. This is one of the few instances where you are allowed to lengthen the main method, but if you go through it carefully and count how many statements it contains, it will still come to one statement. An if‑else counts as one statement.

    [edit]Line 4 needed additional ) to compile
     
    Dj Galla
    Greenhorn
    Posts: 20
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:if (args.length > 0 && (numberScan = new Scanner(args[0])).hasNextInt())[/code]



    This line is showing an error in NetBeans before running the project...
     
    Dj Galla
    Greenhorn
    Posts: 20
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Here is what I have so far... the program works, but shows an error when I enter a non integer...

    Here is the main java file...


    java file containing the paragraph list, and a method to get a specific paragraph....


    And the error checking class... I think the TRY-CATCH isn't "catching" the parsing error...



    Any idea what I am doing wrong?
     
    Saloon Keeper
    Posts: 10705
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Your IF statement on line 14 should be using OR not AND.
     
    Carey Brown
    Saloon Keeper
    Posts: 10705
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Dj Galla wrote:Here is what I have so far... the program works, but shows an error when I enter a non integer...


    If you enter a non-integer your array index value will be -1 which will give you an out of bounds exception.

    When you say "shows an error" you should cut-n-paste the error text into a post.
     
    Dj Galla
    Greenhorn
    Posts: 20
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Carey Brown wrote:When you say "shows an error" you should cut-n-paste the error text into a post.



    Yup, an out of bounds error when I run it in NetBeans ...


    Any idea how to fix it? I'm trying to allow the user to only enter a number from 1 to 147 ... anything outside that range, and show an error message. Any other characters (non numbers), so the error message.
     
    Carey Brown
    Saloon Keeper
    Posts: 10705
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    On line 12 you have

    theNum = 0; // If Error, Set to 0

    So, you return 0, then subtract 1, that gives you a -1, then you try to use that as an array index, and there is no valid index less than zero.
     
    Dj Galla
    Greenhorn
    Posts: 20
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Carey Brown wrote:On line 12 you have

    theNum = 0; // If Error, Set to 0

    So, you return 0, then subtract 1, that gives you a -1, then you try to use that as an array index, and there is no valid index less than zero.



    I got'cha.  The reason I subtract one, is because paragraph 1 is in position 0 of the array.   I'll play with it and see if I can get it working. Thanks!
     
    Dj Galla
    Greenhorn
    Posts: 20
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Carey Brown wrote:...there is no valid index less than zero.



    Fixed it. And it's running fine...
    (I also fixed replaced the AND with OR)

    Thanks again!



    Note: This is an ongoing project, that will grow... so I'll probably be back with some more questions later.  
     
    Campbell Ritchie
    Marshal
    Posts: 79177
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Dj Galla wrote:This line is showing an error in NetBeans before running the project...

    Did you leave the closing code tag in when trying to run the code? There was an error in what I wrote originally, but I had corrected it long before you tried out the code. When I wrote a something() method, my code ran normally.

    Your solution shows some really poor style, with badly‑name variables. You also have far too much code in the main method. Because you didn't show us the workings of the chkErr (bad name for a class), we cannot comment on whether the code is correct or not.
     
    Campbell Ritchie
    Marshal
    Posts: 79177
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Dj Galla wrote:

    Carey Brown wrote:...there is no valid index less than zero.



    Fixed it. And it's running fine...

    You have not sorted out the problem of negative numbers.


    (I also fixed replaced the AND with OR). . . .

    Where? I can's see any ands or ors.

    I have however found your code for checking numbers and would not regard that as correct code. If anything goes wrong, you are returning 0 which we already know is an invalid number. You are also using Exceptions instead of if‑else, which is simply inefficient.
     
    Dj Galla
    Greenhorn
    Posts: 20
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:You have not sorted out the problem of negative numbers.



    Before, the issue was coming from a negative number being an array key (i.e. array[-1]).  When w.parseStr(args) is run (line 8 of class DWarsPara), it returns a number from 0 to 147.  I then added a conditional if statement to check if parNum is not equal to 0 (line 10 of class DWarsPara), and if true, it runs the conditional block using parNum (with only values of 1 to 147). That block enters array keys 0-146 - no negative numbers, and no issues.

    Campbell Ritchie wrote:Where? I can's see any ands or ors.


    I changed this in the chkErr class, which I just didn't repost (see my original post)

    Campbell Ritchie wrote:If anything goes wrong, you are returning 0 which we already know is an invalid


    0 is an invalid number?  Not sure what you mean ... seems like it works like most numbers, and is fine as an array key. Can you explain?


    Campbell Ritchie wrote:You are also using Exceptions instead of if‑else, which is simply inefficient.


    Any recommendations you can give are definitely welcome.  Not sure how to avoid errors using if-else statements...
     
    Sheriff
    Posts: 7125
    184
    Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    In the following code...

    ...you don't need thePara variable at all.  Can you reduce in the number of lines in the method to one?
     
    Knute Snortum
    Sheriff
    Posts: 7125
    184
    Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Your inclination to add comments is admirable, but you don't have to add comments like this:

    You're simply stating what can be seen by reading the code.  Instead, comment on why the code is the way it is:

    In this situation, you probably don't need any comment at all, but this is an illustration.
     
    Campbell Ritchie
    Marshal
    Posts: 79177
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Dj Galla wrote:. . . Before, the issue was coming from a negative number being an array key (i.e. array[-1]).  When w.parseStr(args) is run (line 8 of class DWarsPara), it returns a number from 0 to 147.  I then added a conditional if statement to check if parNum is not equal to 0 (line 10 of class DWarsPara), and if true, it runs the conditional block using parNum (with only values of 1 to 147). That block enters array keys 0-146 - no negative numbers, and no issues.

    Just a bit of incredibly complicated and illegible code, which I think will return a 0 and you are then ignoring it. The user enters incorrect input and never finds out about it. And you still think no issues?

    . . .

    Campbell Ritchie wrote:If anything goes wrong, you are returning 0 which we already know is an invalid


    0 is an invalid number?  Not sure what you mean ... seems like it works like most numbers, and is fine as an array key. Can you explain?

    And you are subtracting 1 from all numbers? You have a bit of convoluted code which will confuse everybody who reads it.

    Campbell Ritchie wrote:You are also using Exceptions instead of if‑else, which is simply inefficient.


    Any recommendations you can give are definitely welcome.  Not sure how to avoid errors using if-else statements...

    Didn't you see my earlier post about Scanner#hasNextInt?
     
    Dj Galla
    Greenhorn
    Posts: 20
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:The user enters incorrect input and never finds out about it. And you still think no issues?


    The user enters text ... if it is out of the range, or incorrect code (not a number), then I have the parseStr() return a 0 ... and I issue an error message to the user at the very end of the main code (where, if it equals 0, the user gets a message saying to "enter a number between 1 and 147"). Otherwise, parseStr returns a number from 1-147 ... and that gives a valid result when looking for the array element.

    Campbell Ritchie wrote:And you are subtracting 1 from all numbers?


    I subtract "1" from the number that is returned from parseStr ... which is a number between 1-147. So, it results in a number from 0-147 (the elements in the array).

    Campbell Ritchie wrote:You have a bit of convoluted code which will confuse everybody who reads it.


    That's one of the reason's I'm here... to learn how to fix things, and make it cleaner.

    Campbell Ritchie wrote:Didn't you see my earlier post about Scanner#hasNextInt?


    I tried getting that to work, but it didn't work when I tried - so I pursued another path. I'll take another look...
     
    Dj Galla
    Greenhorn
    Posts: 20
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Knute Snortum wrote:Can you reduce in the number of lines in the method to one?



    Thanks...

     
    Dj Galla
    Greenhorn
    Posts: 20
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I used Scanner to parse the string, and get the number. All of the revised code is below. No errors....

    main DWarsPara....



    parseNchk class (renamed from errChk)


    and, the class containing the paragraphs, and lets the user select the array element...
     
    Ganesh Patekar
    Bartender
    Posts: 1251
    87
    Hibernate jQuery Spring MySQL Database Tomcat Server Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
  • I think you mistakenly wrote parseNchk rather ParseNchk( class name first letter capital)
  • int arrKey; not necessary
  • You can try these also
  • OR

     
    Carey Brown
    Saloon Keeper
    Posts: 10705
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Ganesh Patekar wrote:

    I think that's ugly. Would much rather see
     
    Ganesh Patekar
    Bartender
    Posts: 1251
    87
    Hibernate jQuery Spring MySQL Database Tomcat Server Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Carey Brown wrote:I think that's ugly. Would much rather see

    Why I turned simple code into gnarled one ,   Agreed! Thank you Carey Brown
     
    I will suppress my every urge. But not this shameless plug:
    a bit of art, as a gift, the permaculture playing cards
    https://gardener-gift.com
    reply
      Bookmark Topic Watch Topic
    • New Topic