Using hasNextInt()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • miller587
    New Member
    • Nov 2007
    • 10

    Using hasNextInt()

    Trying to code in hasNextInt() for data type checking. Basicall my code ask user for input and if user doesn't use an int they get an error. I know i should have a if and else statement with this.
    I am trying this data type checking in this block of code and I get tons of errors

    while (isValid==false )
    }
    System.out.prin t("How many Hammers? ");
    if(input.hasNex tInt())
    {
    numHammers = input.NextInt() ;
    isValid = true;
    }
    else
    }
    input.nextLine( );
    System.out.prin tln("\nError! Please enter a number!");
    }
    }
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    After the else you use a close brace, not an open one. Switch that } to a { and you'll be fine.

    Comment

    • miller587
      New Member
      • Nov 2007
      • 10

      #3
      Thanks have fixed problem, but now I have error that my varaible might not have been intialized looking for numHammers which is my int. I new to java and trying to learn this.

      Comment

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #4
        Originally posted by miller587
        Thanks have fixed problem, but now I have error that my varaible might not have been intialized looking for numHammers which is my int. I new to java and trying to learn this.
        Yep, the local variables have to be definitely assigned in that block. You could initialize it to some negative number.

        Comment

        • miller587
          New Member
          • Nov 2007
          • 10

          #5
          your saying in loop I must initialize numHammers to a number

          Comment

          • miller587
            New Member
            • Nov 2007
            • 10

            #6
            I got 5 Items that user inputs amount of product he or she wants, only trying to determine if user enters an int when entering number for second product. I have been searching all over net for examples. I am sure I am missing something simple. I get an error saying numHammers not intailized. Puzzeled. Here is my input of code.

            System.out.prin t("How many Hacksaws? ");
            numHackSaws = input.nextInt() ;

            while (numHackSaws <0 || numHackSaws >10)
            {
            System.out.prin t("Incorrect! Please re-enter a number between(0-10): ");
            numHackSaws = input.nextInt() ;
            }

            while (isValid==false )
            {
            System.out.prin t("How many Hammers? ");
            if(input.hasNex tInt())
            {
            numHammers = input.nextInt() ;
            isValid = true;
            }
            else
            {
            input.nextLine( );
            System.out.prin tln("\nError! Please enter a number!");
            }
            }

            System.out.prin t("How many Drills? ");
            numDrills = input.nextInt() ;
            System.out.prin t("How many HardHats? ");
            numHardHats = input.nextInt() ;
            System.out.prin t("How many pairs of Safety Goggles? ");
            numSafetyGoggle s = input.nextInt() ;

            Comment

            • r035198x
              MVP
              • Sep 2006
              • 13225

              #7
              Look at the error message (they are usually very informative) and initialize the variable (during declaration) being reported there to a negative number.

              Comment

              • miller587
                New Member
                • Nov 2007
                • 10

                #8
                To use hasNextInt() in scanner class to validate input do I have to add in a range check for this to work.

                Comment

                • r035198x
                  MVP
                  • Sep 2006
                  • 13225

                  #9
                  Originally posted by miller587
                  To use hasNextInt() in scanner class to validate input do I have to add in a range check for this to work.
                  I don't fully understand that but could you post the full code you have now and the error message you are getting.
                  Note: When posting code in the forum please make sure you use code tags.

                  Comment

                  • miller587
                    New Member
                    • Nov 2007
                    • 10

                    #10
                    import java.util.Date;
                    import java.util.Scann er;

                    class JohnVanHoutanP2
                    {
                    Code:
                    private static final double HACKSAW_COST = 15.99;		//class constants
                    	  private static final double HAMMER_COST = 12.18;
                    	  private static final double HARDHAT_COST = 18.75;
                    	  private static final double DRILL_COST = 19.99;
                    	  private static final double SAFETYGOGGLES_COST = 16.47;
                    	  private static final double TAX_RATE = 0.05;
                    	  private static final double SHIPPING_COST = 0.08;
                    /*************** *************** *************** *************
                    main Method - program starts execution here
                    *************** *************** *************** ************/

                    public static void main(String[] args)
                    {
                    Code:
                     int numHackSaws, numHammers, numDrills, numHardHats, numSafetyGoggles, numItems;  //local variarables
                    		double totalCost, tax, shipping, bill,average;
                    		boolean isValid = false;
                    Scanner input = new Scanner(System. in); //create an object of the Scanner class
                    Date today = new Date(); //create an object of the Date class

                    System.out.prin tln();
                    System.out.prin tf("John VanHoutan Java 9:30TTH %tD\n",today);
                    System.out.prin tln();

                    printDisplay();
                    System.out.prin tln();

                    /*************** *******input*** *************** ***********/
                    Code:
                    System.out.print("How many Hacksaws?                 ");
                    		numHackSaws = input.nextInt();
                    
                    		while (numHackSaws <0 || numHackSaws >10)
                    		{
                    			System.out.print("Incorrect! Please re-enter a number between(0-10): ");
                    			numHackSaws = input.nextInt();
                    		}
                    
                    		while (isValid==false)
                    		{
                    			System.out.print("How many Hammers? ");
                    			if(input.hasNextInt())
                    			{
                    				numHammers = input.nextInt();
                    				isValid = true;
                    			}
                    			else
                    			{
                    				input.nextLine();
                    				System.out.println("\nError! Please enter a number!");
                    			}
                    		}
                    
                    		System.out.print("How many Drills?                   ");
                    		numDrills  = input.nextInt();
                    		System.out.print("How many HardHats?                 ");
                    		numHardHats  = input.nextInt();
                    		System.out.print("How many pairs of Safety Goggles?  ");
                    		numSafetyGoggles  = input.nextInt();
                    /*************** ******processin g************** ***********/
                    Code:
                    totalCost = (numHackSaws*HACKSAW_COST) + (numHammers*HAMMER_COST) +
                    				    (numDrills*DRILL_COST) + (numHardHats*HARDHAT_COST) +
                    				    (numSafetyGoggles*SAFETYGOGGLES_COST);
                    
                    		tax = TAX_RATE * totalCost;
                    		bill = totalCost + tax;
                    
                    		numItems = numHackSaws + numHammers + numDrills +
                    				   numHardHats + numSafetyGoggles;
                    
                    		shipping = calcShipping (totalCost);
                    		average = calcAvg(totalCost,numItems);
                    /*************** ********output* *************** ***********/
                    System.out.prin tln();
                    System.out.prin tf("\nCost of Items: $%6.2f",totalCo st);
                    System.out.prin tf("\nShipping Cost: $%6.2f",shippin g);
                    System.out.prin tf("\nTax: $%6.2f",tax);
                    System.out.prin tf("\nFinal Bill: $%6.2f\n\n",bil l);
                    System.out.prin tf("\nTotal Number of Items Purchased: %6d",numItems) ;
                    System.out.prin tf("\nAverage Price of Items: $%6.2f\n\n",ave rage);
                    } //end of main method

                    /*************** *************** *************** *************** ***
                    printDisplay Method - list items with prices
                    *************** *************** *************** *************** **/
                    public static void printDisplay()
                    {
                    System.out.prin t("Welcome To The Hardware Store");
                    System.out.prin tln();
                    System.out.prin t("------------------------------");
                    System.out.prin tf("\nHackSaw\t \t\t$%5.2f",HAC KSAW_COST);
                    System.out.prin tf("\nHammer\t\ t\t$%5.2f",HAMM ER_COST);
                    System.out.prin tf("\nDrill\t\t \t$%5.2f",DRILL _COST);
                    System.out.prin tf("\nHardHat\t \t\t$%5.2f",HAR DHAT_COST);
                    System.out.prin tf("\nSafetyGog gle\t\t$%5.2f", SAFETYGOGGLES_C OST);
                    System.out.prin tln();
                    } //end of printDisplay method

                    /*************** *************** *************** *************** ***
                    calcShipping Method - returns a double
                    *************** *************** *************** *************** **/
                    public static double calcShipping(do uble purchaseCost)
                    {
                    double shipping;

                    shipping = purchaseCost * SHIPPING_COST;

                    return shipping;
                    } //end of calcShipping method

                    /*************** *************** *************** *************** ***
                    calcAverage Method - returns a double
                    *************** *************** *************** *************** **/
                    public static double calcAvg(double purchaseCost, int numProducts)
                    {
                    double average;

                    average = purchaseCost / numProducts;

                    return average;
                    } //end of calcAvg method

                    } //end of JohnVanHoutanP2 class

                    Comment

                    • miller587
                      New Member
                      • Nov 2007
                      • 10

                      #11
                      Not quite sure what I should tag as [CODE]

                      Error reads as follows: variable numHammers might not have been initialized
                      totalCost = (numHackSaws*HA CKSAW_COST) + (numHammers*HAM MER_COST) +

                      I am only trying to determine if user put an int when asked for number of 2nd item.

                      I have never used any of the scanner methods to check validation of input

                      Comment

                      • r035198x
                        MVP
                        • Sep 2006
                        • 13225

                        #12
                        Originally posted by miller587
                        Not quite sure what I should tag as
                        Code:
                        Error reads as follows:  variable numHammers might not have been initialized 
                        totalCost = (numHackSaws*HACKSAW_COST) + (numHammers*HAMMER_COST) +
                        
                        I am only trying to determine if user put an int when asked for number of 2nd item.
                        
                        I have never used any of the scanner methods to check validation of input
                        Code:
                        1.) Unlike C, Java does not require you to declare all variables at the top. In fact it is encouraged to declare variables closest to where they are used.
                        2.) Your error is because you have not initialized the numHammers variable.
                        Just a simple  [CODE=java]int numHammers = -1;
                        at the start of your main method will make that error disappear.

                        Comment

                        • miller587
                          New Member
                          • Nov 2007
                          • 10

                          #13
                          thanks for the interpetation I have used C in past makes sense. thanks, for helping me out

                          Comment

                          Working...